Comparison of Java and C Sharp

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

Template:Pound

Template:ProgLangCompare

Contents

Introduction

This is a comparison of the C# programming language with the Java programming language. While the focus of this article is mainly the programming languages and their features, such a comparison will necessarily also consider some platform features and some library features. Neither Java nor C# can be evaluated without taking the respective platforms and libraries into consideration.

The comparison will naturally focus on the areas where the languages differ. This may skew the fact that the two languages and their platforms are actually more alike than they are different: Both are (primarily) statically, strongly and explicitly typed, both are class-based object-oriented, both are designed with semi-interpretation or runtime compilation in mind, both use garbage-collected memory models and both are considered "curly brace" C/C++ style languages. The common ancestry is also evident in the fact that common concepts are often termed the same way and more often than not have very similar syntax.

Platforms

Java (the programming language) is designed to execute on the Java platform, the Java Runtime Environment (JRE). The runtime environment includes the Java Virtual Machine (JVM) as well as a common set of libraries. C# is designed to execute on the Common Language Runtime.

Language

Object handling

Both C# and Java are designed from the ground up as object oriented languages using dynamic dispatch, with syntax similar to C++ (C++ in turn is derived from C). Neither language is a superset of C or C++, however. Both use garbage collection as a means of reclaiming memory resources, rather than explicit deallocation of memory. Both include thread synchronization mechanisms as part of their language syntax.

In both languages objects are created with a new.

References

In both languages references are a central concept. All instances of classes are by reference.

While not directly evident in the language syntax per se, both languages support the concept of weak references. An instance which is only referenced by weak references is eligible for garbage collection just as if there was no references at all. In both languages this feature is exposed through the associated libraries, even though it is really a core runtime feature.

In addition to weak references, Java has soft references. Soft references are much like weak references, but the JVM will not deallocate softly-referenced objects until the memory is actually needed.


feature Java C#
Garbage collectionyesyes
Deterministic disposalnoyes
Weak referencesyesyes
Soft referencesyesno
Object pinning (fixed to address throughout lifetime)noyes

Pointers

C# allows use of pointers and corresponding pointer arithmetic. Pointers and pointer-arithmetic are potentially unsafe in a managed environment as they can be used to bypass the strict rules for object access. C# addresses that concern by requiring that code blocks or methods that use the feature be marked with the unsafe keyword, so that all clients of such code can be aware that the code may be less secure than otherwise. The compiler requires the /unsafe switch to allow compilation of a program that uses such code. Generally, unsafe code is either used to allow better interoperability with unmanaged APIs or system calls (which are inherently "unsafe"), or for performance reasons. Java does not allow pointers or pointer-arithmetic to be used.

Data types

feature Java C#
Signed integer types (bit widths)8,16,32,648,16,32,64
Unsigned integer types (bit widths)only 16 (char)8,16,32,64
IEEE floating point types (bit sizes)32,6432,64
Big decimal (financial) typeyes[1]no[2]
Strings and charactersyes; immutable reference type, unicodeyes; immutable reference type, unicode
Date/time typeyes; mutable reference typeyes; value type
Booleanyesyes
Fixed-length stringsnoyes


Both languages support the idea of primitive types which are all value types in C#/.NET, except for String which is a reference type. C# has more primitive types than Java, with unsigned as well as signed integer types being supported, and a decimal type for decimal floating-point calculations. Java lacks unsigned types. In particular, Java lacks a primitive type for an unsigned byte, while C# bytes are unsigned by default. Strings are treated as (immutable) objects in both languages, but support for string literals provides a specialized means of constructing them. C# also allows verbatim strings for quotation without escape sequences, which also allow newlines.

Both allow automatic boxing and unboxing to translate primitive data to and from their object form. Effectively, this makes the primitive types a subtype of the Object type. In C# this also means that primitive types can define methods, such as an override of Object's ToString() method. In Java, separate primitive wrapper classes provide such functionality. In Java primitive values are not implicitly boxed when dereferenced and an explicit cast is required for an instance call on a primitive value — ((Integer)42).toString() instead of a C# instance call 42.ToString(). Another difference is that Java makes heavy use of boxed types in generics (see below), and as such allows an implicit unboxing conversion (in C# this requires a cast). As these implicit unboxing conversions can potentially throw null pointer exceptions, modern integrated development environments and compilers can be configured to highlight them.

Value types

C# allows the programmer to create user-defined value types, using the struct keyword. From the programmer's perspective, they can be seen as lightweight classes. Unlike regular classes, and like the standard primitives, such value types are passed by value rather than by reference. They can also be part of an object (either as a field or boxed), or stored in an array, without the memory indirection that normally exists for class types. Structs also come with a number of limitations. Because structs have no notion of a null value and can be used in arrays without initialization, they always come with an implicit default constructor that essentially fills the struct memory space with zeroes. The programmer can only define additional constructors with one or more arguments. This also means that structs lack a virtual method table, and because of that (and the fixed memory footprint), they cannot allow inheritance (but can implement interfaces). Java does not include the concept of value types.

Enumerations

Enumerations in C# are derived from a primitive integer type (8, 16, 32, or 64 bit). Any value of the underlying primitive type is a valid value of the enumeration type, though an explicit cast may be needed to assign it. C# also supports bitmapped enumerations where an actual value may be a combination of enumerated values bitwise or'ed together. Enumerations in Java, on the other hand, are objects. The only valid values in a Java enumeration are the ones listed in the enumeration. As objects, each enumeration can contain its own fields which can be modified. Special enumeration set and map collections provide fully type-safe functionality with minimal overhead. Java enumerations allow differing method implementations for each value in the enumeration. Both C# and Java enumerations can be converted to strings and can be used in a switch statement.

Arrays

Array and collection types are also given significance in the syntax of both languages, thanks to an iterator-based foreach statement loop. In C# an array corresponds to an object of the Array class, while in Java each array is a direct subclass of the Object class (but can be cast to an array of an element type that is an ancestor of its true element type), and does not implement any of the collection interfaces. C# has true multidimensional arrays, as well as the arrays-of-arrays that are available in Java (and which in C# are commonly called jagged arrays). Multidimensional arrays can in some cases increase performance because of increased locality (as there is a single pointer dereference, instead of one for every dimension of the array as is the case for jagged arrays). Another advantage is that the entire multidimensional array can be allocated with a single application of operator new, while jagged arrays require loops and allocations for every dimension. Note, though, that Java provides a syntactic construct for allocating a multidimensional jagged array with regular lengths (a rectangular array in C# terminology); the loops and multiple allocations are then performed by the virtual machine and need not be explicit at the source level.

Inner classes

Both languages allow inner classes, where a class is defined lexically inside another class. However, in each language these inner classes have rather different semantics.

In Java, unless the inner class is declared static, a reference to an instance of an inner class carries a reference to the outer class with it. As a result, code in the inner class has access to both the static and non-static members of the outer class. To create an instance of a non-static inner class, one has to name the instance of the embracing outer class [3]. This is done via a new new-operator introduced in JDK 1.3: outerClassInstance.new Outer.InnerClass(). This can be done in any class that has a reference to an instance of the outer class.

In C#, an inner class is conceptually the same as a normal class. In a sense, the outer class only acts as a namespace. Thus, code in the inner class cannot access non-static members of the outer class unless it does so through an explicit reference to an instance of the outer class. The inner class can be declared private to allow only the outer class to have any access to it.

Java provides another feature called local classes or anonymous classes, which can be defined within a method body. These are generally used to implement an interface with only one or two methods, which are typically event handlers. They can also be used to override virtual methods of a super-class however. The methods in those local classes have access to the outer method's local variables declared final. C# satisfies the use-cases for these by providing anonymous delegates; see event handling for more about this.

C# also provides a feature called anonymous classes, but it is rather different from Java's concept with the same name. It allows the programmer to instantiate a class by providing only a set of names for the properties the class should have, and an expression to initialize each. The types of the properties are inferred from the types of those expressions. These implicitly-declared classes derived directly from object.

Partial classes

C# allows a class definition to be split across several source files using a feature called partial classes. Each part must be marked with the keyword partial. All the parts must be presented to the compiler as part of a single compilation. Parts can reference members from other parts. Parts can implement interfaces and one part can define a base class. The feature is useful in code generation scenarios (such as UI design) where a code generator can supply one part and the developer another part to be compiled together. The developer can thus edit their part without the risk of a code generator overwriting that code at some later time. Unlike the class extension mechanism a partial class allows "circular" dependencies amongst its parts as they are guaranteed to be resolved at compile time. Java has no corresponding concept.

Generics

feature Java C#
Type compilationType erasureReified
co-varianceuse-sitelimited, use-site
contra-varianceuse-siteno (yes in .net 4.0)
type parameter static membersnoyes
static scopeshared among all generic realizationsseparate for each generic realization
array component typeslimitedall types

Both languages now support generics programming, but they have taken different paths to its implementation.

Generics in Java are a language-only construction; they are implemented only in the compiler. The generated classfiles include generic signatures only in the form of metadata (allowing the compiler to compile new classes against them). The runtime has no knowledge of the generic type system, which meant that JVM implementations only needed minimal updates to handle the new class format.

To achieve this goal the compiler replaces all generic types by their upper bounds and inserts casts appropriately in the various places where the type is used. The resulting byte code will contain no references to any generic types or parameters. This technique of implementing generics is known as type erasure. This means that runtime information about the actual types is not available at runtime, and imposes some restrictions such as the inability to create new instances or arrays of generic type arguments. (See also Generics in Java.)

C# took a different route. Support for genericity was integrated into the virtual execution system itself and first appeared in .NET 2.0. The language then becomes merely a front-end for the underlying generics support in the execution system. As in Java, the compiler provides static type safety checking, but additionally the JIT performs load time verification of the correctness. Information on generic types is fully preserved at runtime, and allows complete reflection support as well as instantiation of generic types.

Java does not allow to specialize generic classes with primitive types, while C# allows generics for both reference types and value types, including primitive types. Java instead allows the use of boxed types as type parameters (e.g., List<Integer> instead of List<int>), but this comes at a cost since all such values need to be heap-allocated. In both Java and C#, generic specializations that use different reference types share equivalent underlying code,[4] but for C# the Common Language Runtime (CLR) dynamically generates optimized code for specializations on value types.

Notation and special features

Special feature keywords

keyword feature, example usage
checked, unchecked In C#, checked statement blocks or expressions can enable run-time checking for arithmetic overflow.
get, set C# implements properties as part of the language syntax with their optional corresponding get and set accessors, as an alternative for the accessor methods used in Java, which is not a language feature but a coding pattern based on method name conventions.
goto C# supports the goto keyword. This can occasionally be useful, for example for implementing finite state machines or for generated code, but the use of a more structured method of control flow is usually recommended (see criticism of the goto statement). Java allows labeled breaks and continues, which make up for many of the uses of goto.
switch(color)
{
    case Color.Blue:
         Console.WriteLine("Color is blue"); break;
    case Color.DarkBlue:
         Console.WriteLine("Color is dark");
         goto case Color.Blue;
    // ...
}
out, ref C# has support for output and reference parameters. These allow returning multiple output values from a method, or passing values by reference.
strictfp Java uses strictfp to guarantee the results of floating point operations remain the same across platforms.
switch In C#, the switch statement also operates on strings and longs but only allows fallthrough for empty statements. Java switch statement does not operate on strings nor long primitive type but falls through for all statements (excluding those with 'break').
throws Java requires every method to declare the checked exceptions or superclasses of the checked exceptions that it can throw. Any method can also optionally declare the unchecked exception that it throws. C# has no such syntax.
public int readItem() throws java.io.IOException
{
    // ...
}
using C#'s using causes the Dispose method (implemented via the IDisposable interface) of the object declared to be executed after the code block has run or when an exception is thrown within the code block.
// Create a small file "test.txt", write a string, 
// ... and close it (even if an exception occurs)
using (StreamWriter file = new StreamWriter("test.txt"))
{
    file.Write("test");
}
yield C# allows the use of the yield keyword to express iterator generators. In Java, iterators can be defined only using (possibly anonymous) classes, requiring considerably more Boilerplate code. Below is an example of an iterator that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
    foreach (int i in numbers)
    {
        if (i % 2 == 0)
            yield return i;
    }
}

Callbacks and Event handling

C# implements object oriented method pointers in the form of delegates. A delegate is a special type which can capture a reference to an instance or static method if its signature is compatible. Multicast-delegates are called events (see below). Delegates provide support for event-driven programming. They are type-safe references to methods and can be combined to allow multicasting. To support them there is a special syntax to define events in classes and operators to register, unregister or combine event handlers. Delegates support covariance and contravariance, and can be created as anonymous methods with full-featured closure semantics. In .NET, closures and anonymous delegates are syntactic sugar.[5][6]

Java does not have a language-level construct like the C# delegate. The observer[7] pattern is used for event-driven programming in Java. Anonymous inner classes are commonly used to implement the listener, allowing you to define the body of the class and create an instance of it in a single point in the code. Java anonymous classes has been seen by some as syntactic sugar, and to be more verbose than C# delegates.[citation needed]

Numeric applications

To adequately support applications in the field of mathematic and financial computation, several language features exist.[8] In this category, Java provides the strictfp keyword, that enables strict floating-point calculations for a region of code. This will ensure that calculations return the exact same result on all platforms. C# provides no equivalent, but does provide the built-in decimal type, for accurate decimal floating-point calculations. This forgoes the problems that exist with binary floating-point representations (float, double). Such binary representations are not suited to accurately represent decimal numbers and hence introduce rounding errors. For financial applications, an accurate decimal type is essential.

The Template:Javadoc:SE class also provides such characteristics for Java. BigDecimal and Template:Javadoc:SE are types provided with Java that allow arbitrary-precision representation of numbers. The current release of the .NET framework (3.5) does not currently include such classes, although third party implementations exist (see Arbitrary-precision arithmetic).

In Java there is no way to provide the same level of integration for library-defined types such as BigDecimal or complex numbers as there is for the primitive types. For this purpose, C# provides the following:

  • Operator overloading and indexers providing convenient syntax (see below).
  • Implicit and explicit conversions; allow conversions such as exist for the built-in int type that can implicitly convert to long.
  • Valuetypes and generics based on valuetypes; in Java every custom type must be allocated on the heap, which is detrimental for performance of both custom types and collections.

In addition to this, C# can help mathematic applications with the checked and unchecked operators that allow to enable or disable run-time checking for arithmetic overflow for a region of code. It also offers rectangular arrays, that have advantages over regular nested arrays for certain applications.[8]

Operator overloading

C# includes a large number of notational conveniences over Java, many of which, such as operator overloading and user-defined casts, are already familiar to the large community of C++ programmers. It also has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate to its own class methods, or to provide different implementations for two methods with the same name and signature inherited from two base interfaces.

Java does not include operator overloading in order to prevent abuse of the feature, and to keep the language simple.[9] C# allows operator overloading (subject to certain restrictions to ensure logical coherence), which, when used carefully, can make code succinct and more readable.

C# includes indexers which can be considered a special case of operator overloading (like C++ operator[]), or parametrized get/set properties. An indexer is a property named this[] which uses one or more parameters (indexes); the indices can be objects of any type:

myList[4] = 5;
string name = xmlNode.Attributes["name"];
orders = customerMap[theCustomer];

Java does not include indexers. The common Java pattern is to write explicit get_ and set_ methods where a C# programmer would use an indexer.

Methods

Methods in C# are non-virtual by default, and have to be declared virtual explicitly if desired. In Java, all non-static non-private methods are virtual. Virtuality guarantees that the most recent override for the method will always be called, but incurs a certain runtime cost on invocation as these invocations cannot be normally inlined, and require an indirect call via the virtual method table. However, some JVM implementations, including the Sun reference implementation, implement inlining of the most commonly called virtual methods.

In Java methods are virtual by default (although they can be "sealed" by using the final modifier to disallow overriding). There is no way to let derived classes define a new, unrelated method with the same name. This can be a problem when a base class is designed by a different person, and a new version introduces a method with the same name and signature as some method already present in the derived class. In Java, this will mean that the method in the derived class will implicitly override the method in the base class, even though that was not the intent of the designers of either class. To prevent this versioning problem, C# requires that if a method should be overridden, the override keyword must be specified. Otherwise, the method will "hide" the inherited method. A compiler warning to this effect is issued, which can be silenced by specifying the new keyword. This avoids the problem which can arise from a base class being extended with a protected/public method whose signature is already in use by a derived class. In Java a recompilation will lead the compiler to regard the method of the derived class as an override of the method of the base class, which was probably not the intent of the base-class developer. To partially accommodate for these versioning problems, Java 5.0 introduced the @Override annotation, but to preserve backwards compatibility it could not be made compulsory, so it cannot prevent the above accidental overriding situation. Like the override keyword in C#, it can however help ensure that a method in the base class with the same signature exists and is correctly overridden.

Explicit interface implementation

In either language if a method (or property in C#) is specified with the same name and signature in multiple interfaces, the members will clash when a class is designed which implements those interfaces. An implementation will by default implement a common method for all of the interfaces. If separate implementations are required (because the methods really do serve separate purposes, or because return values differ between the interfaces) C# explicit interface implementation will solve the problem. In Java there is no way to solve this problem other than to refactor one or more of the interfaces to avoid name clashes. C# explicit implementation will also hide the method from the primary class interface, and can thus help reduce the class interface complexity.

Closures

When a reference to a method can be passed around for later execution, a problem arises about what to do when the method has references to variables/parameters in its lexical scope. C# has true closures in which the referenced method can fully capture any variable/parameter from its lexical scope. In Java's anonymous inner classes only references to final members of the lexical scope are allowed, thus requiring the developer to artificially introduce extra levels of indirections and boxing primitive types if he wants to reference and update those from the inner class.

Java does not currently feature closures; however, it has been announced that some form of closures will be included in JDK 7. [10]

In Java, anonymous inner classes remains the preferred way to emulate closures. Aside from being a more verbose construction, this approach also has some drawbacks compared to real closures, such as limited access to variables from the enclosing scopes (only final members can be referenced).

Lambdas and expression trees

C# features a special type of inline closures called lambdas. These are anonymous methods: they have a signature and a body, but no name. They are not methods in that they cannot form part of a class interface. They are mainly used to specify local function-valued arguments in calls to other methods, a technique mainly associated with functional programming. On top of that, lambda functions can double as a way to define special data structures called expression trees. Whether they are seen as an executable function or a data structure depends on compiler type inference and what type of variable or parameter they are assigned/cast to. Lambdas and expression trees play key roles in LINQ. Java does not feature lambdas or expression trees; its primary mechanism for inline scope capture and method definition is the anonymous inner class syntax.

Partial methods

Related to partial classes C# allows partial methods to be specified within partial classes. A partial method is an intentional declaration of a method with a number of restrictions on the signature. These restrictions ensure that if a definition is not actually provided by any class part, then the method and every call to it can be safely erased. This feature allows code to provide a large number of interception points (like the template method GoF design pattern) without paying any runtime overhead if these extension points are not being used by another class part at compile time. Java has no corresponding concept.

Extension methods

Using a special this designator on the first parameter of a method, C# allows the method to act as if it were a member method of the type of the first parameter. This extension of the foreign class is purely syntactical. The extension method needs to be static and defined within a purely static class. It must obey any restriction on such external static methods and thus cannot break object encapsulation. The "extension" is only active within scopes where the namespace of the static host class has been imported. Java has no corresponding concept.

Generator methods

A C# method which is declared as returning IEnumerable, IEnumerator or the generic versions of these interfaces, can be implemented using yield syntax. This is a form of limited, compiler-generated continuations and can drastically reduce the code required to traverse or generate sequences, although that code is just generated by the compiler instead. The feature can also be used to implement infinite sequences, e.g. the sequence of Fibonacci numbers. Java has no corresponding concept.

Conditional compilation

Unlike Java, C# implements conditional compilation using preprocessor directives. It also provides a Conditional attribute to define methods that are only called when a given compilation constant is defined. This way, assertions can be provided as a framework feature with the method Debug.Assert(), which is only evaluated when the DEBUG constant is defined. Since version 1.4, Java provides a language feature for assertions, which are turned off at runtime by default but can be enabled using the "-enableassertions" or "-ea" switch when invoking the JVM.

Namespaces and source files

C#'s namespaces are similar to those in C++. Unlike package names in Java, a namespace is not in any way tied to location of the source file. While it's not strictly necessary for a Java source file location to mirror its package directory structure, it is the conventional organization.

Both languages allow importing of classes (e.g., import java.util.* in Java), allowing a class to be referenced using only its name. Sometimes classes with the same name exist in multiple namespaces or packages. Such classes can be referenced by using fully qualified names, or by importing only selected classes with different names. To do this, Java allows importing a single class (e.g., import java.util.List). C# allows importing classes under a new local name using the following syntax: using Console = System.Console. It also allows importing specializations of classes in the form of using IntList = System.Collections.Generic.List<int>.

Java has a static import syntax that allows using the short name of some or all of the static methods/fields in a class (e.g., allowing foo(bar) where foo() can be statically imported from another class). C# has a static class syntax (not to be confused with static inner classes in Java), which restricts a class to only contain static methods. C# 3.0 introduces extension methods to allow users to statically add a method to a type (e.g., allowing foo.bar() where bar() can be an imported extension method working on the type of foo).

The Sun Microsystems Java compiler requires that a source file name must match the only public class inside it, while C# allows multiple public classes in the same file, and puts no restrictions on the file name. C# 2.0 and later allows a class definition to be split into several files, by using the partial keyword in the source code.

Exception handling

Java supports checked exceptions (in addition to unchecked exceptions). C# only supports unchecked exceptions. Checked exceptions force the programmer to either declare the exception thrown in a method, or to catch the thrown exception using a try-catch clause.

Checked exceptions can be helpful for good programming practice, ensuring that all errors are dealt with. However Anders Hejlsberg, chief C# language architect, and others argue that they were to some extent an experiment in Java and that they haven't been shown to be worthwhile except in small example programs.[11][12]

One criticism is that checked exceptions encourage programmers to use an empty catch block (catch (Exception e) {}), which silently eats exceptions, rather than letting the exceptions propagate to a higher-level exception-handling routine. Another criticism of checked exceptions is that a new implementation of a method may cause unanticipated checked exceptions to be thrown, which is a contract-breaking change. This can happen in methods implementing an interface that only declares limited exceptions, or when the underlying implementation of a method changes. To allow for such unanticipated exceptions to be thrown, some programmers simply declare the method can throw any type of exception ("throws Exception"), which defeats the purpose of checked exceptions. In some cases however, exception chaining can be applied instead; re-throwing the exception in a wrapper exception. For example, if an object is changed to access a database instead of a file, an Template:Javadoc:SE could be caught and re-thrown as an Template:Javadoc:SE, since the caller may not need to know the inner workings of the object.

There are also differences between the two languages in treating the try-finally statement. The finally is always executed, even if the try block contains control-passing statements like throw or return. In Java, this may result in unexpected behavior if the try block is left by a return statement with some value, and then the finally block that is executed afterwards is also left by a return statement with a different value. C# resolves this problem by prohibiting any control-passing statements like return or break in the finally block.

A common reason for using try-finally blocks is to guard resource managing code, so that precious resources are guaranteed to be released in the finally block. C# features the using statement as a syntactic shorthand for this common scenario, in which the Dispose() method of the object of the using is always called.

Finally Blocks and Uncaught Exceptions

A significant difference between Java and C# is over the question of whether finally blocks should execute in response to an unhandled exception. Both languages allow a program to disregard some exceptions. In C#, any exception type may be uncaught. In Java descendents of RuntimeException, such as NullPointerException, need not be declared and therefore need not be caught, as they indicate a bug.

The ECMA standard for the CLI (from which C# derives its exception features) states that exceptions are handled in a two-pass search of the stack.[13] The first pass attempts to locate a matching catch block, and terminates the program if none is found. Only if a matching catch block is found does the second pass execute, which runs the intervening finally blocks. This allows the problem to be diagnosed without the program state first being modified by the finally blocks; it also eliminates the risk that finally blocks may have undesirable side-effects when the program is in an unknown state (such as corruption of external data, or throwing further exceptions).

The Java Language Specification states that finally blocks run even if an exception is uncaught, and gives a code example showing the expected output.[14]

Lower level code

The Java Native Interface (JNI) feature allows Java programs to call non-Java code. However, JNI does require the code being called to follow several conventions and impose restrictions on types and names used. This means that an extra adaption layer between legacy code and Java is often needed. This adaption code must be coded in a non-Java language, often C or C++. Java Native Access (JNA) allows easier calling of native code that only requires writing Java code, but comes at a performance cost.

In addition, third party libraries provide for Java-COM bridging, e.g. JACOB (free), and J-Integra for COM (proprietary).

.NET Platform Invoke (P/Invoke) offers the same capability by allowing calls from C# to what Microsoft refers to as unmanaged code. Through metadata attributes the programmer can control exactly how the parameters and results are marshalled, thus avoiding the need for extra adaption code. P/Invoke allows almost complete access to procedural APIs (such as Win32 or POSIX), but limited access to C++ class libraries.

In addition, .NET Framework also provides a .NET-COM bridge, allowing access to COM components as if they were native .NET objects.

C# also allows the programmer to disable the normal type-checking and other safety features of the CLR, which then enables the use of pointer variables. When this feature is used, the programmer must mark the code using the unsafe keyword. JNI, P/Invoke, and "unsafe" code are equally risky features, exposing possible security holes and application instability. An advantage of unsafe, managed code over P/Invoke or JNI is that it allows the programmer to continue to work in the familiar C# environment to accomplish some tasks that otherwise would require calling out to unmanaged code. An assembly (program or library) using unsafe code must be compiled with a special switch and will be marked as such. This enables runtime environments to take special precautions before executing potentially harmful code.

Language history and evolution

Java

Java is older than C# and has built up a large and highly active user base, becoming the lingua franca in many modern branches of computer science, particularly areas which involve networking.[citation needed] Java dominates programming courses at high school and college level in the United States, and there are currently more Java than C# books.[15] Java's maturity and popularity have ensured more third party Java API and libraries (many of them open source)[citation needed] than C#.

An occasionally voiced criticism [16] of the Java language is that it evolves slowly, lacking some features which make fashionable programming patterns and methodologies easier.[citation needed] Some critics[who?] argue the designers of C# are perhaps too quick to pander to current trends in programming, thus lacking focus and simplicity.[citation needed] Java's designers seem[original research?] to have taken a more conservative stand on adding major new features to their language syntax than other current languages, perhaps[who?] not wanting to tie the language too tightly with trends which may prove to be dead ends.

These trends[original research?] have been broken with the Java 5.0 release, which introduced several new major language features: a foreach construct, autoboxing, methods with variable number of parameters (varargs), enumerated types, generic types, and annotations. With the exception of Generics, C# included all these features from its beginning, some under different names.[17] Proposals and specifications for the new features had been worked on in the Java community for considerable time before they were introduced. Indeed, some had been in gestation since before C#'s initial release (e.g., work on Generics formally began in May 1999[18]) such was the Java community's conservatism at that time.

Problem-specific language additions to Java have been considered and, for now at least, rejected. This approach, along with a number of other new languages and technologies that address themselves specifically towards current programming trends, has sparked a renewed debate within the Java camp about the future direction of the Java language and whether its 'conservative evolution' is right.[citation needed]

As of 2008, there is an ongoing debate about the inclusion of closures[19] and properties[20] into the language syntax for Java 7.

C#

By contrast, C# is a relatively new language. Microsoft has studied existing languages such as Java and Object Pascal, and has changed some aspects of the language and runtime environment in response to perceived failures and difficulties with its predecessors. C# accommodates constructs more commonly found in languages such as C++, Delphi (the design of which was Anders Hejlsberg's principal job when he was at Borland), and, in recent C# versions, borrows from dynamic scripting languages such as Ruby and Python.

C# has evolved rapidly, attempting to streamline development for problem-specific features. C# 3.0 adds SQL-like language integrated queries suited for querying data from collections, databases or XML documents, building upon general-purpose language features, including lambda expressions and extension methods, to allow queries to be expressed and optimized for user types.

Before creating C#, Microsoft implemented a modified Java environment, called J++, adding new features in a manner which was in direct contravention to the standards and conventions ensuring the platform neutrality which lies at the heart of Java. This violated the license agreement Microsoft had signed, requiring that standards and specifications be strictly adhered to in return for using the Java name and brand logos. Sun Microsystems sued, and in settling the suit, Microsoft agreed to discontinue J++. (Other existing Microsoft products that used Java were permitted to continue such use for seven years.[21]) With the release of the .NET framework (and C#), the project was revived in the form of J#.

See also

References

  1. "Class BigDecimal". Sun Microsystems. http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html. Retrieved 2009-12-24. 
  2. "decimal (C# Reference)". Microsoft. http://msdn.microsoft.com/en-us/library/364x0z75%28VS.80%29.aspx. Retrieved 2009-12-24. 
  3. Java Language Specification Third Edition: section 15.9 Class Instance Creation Expressions
  4. Generics in C#, Java, and C++
  5. Richter, Jeffrey (April 2001). "An Introduction to Delegates". MSDN Magazine. http://msdn.microsoft.com/en-ca/magazine/cc301810.aspx. Retrieved 2008-12-23. 
  6. Campbell, Dustin (9 February 2007). "What's In A Closure?". Did it with .NET. http://diditwith.net/PermaLink,guid,235646ae-3476-4893-899d-105e4d48c25b.aspx. Retrieved 2008-12-23. 
  7. Goetz, Brian (26 July 2005). "Java theory and practice: Be a good (event) listener". IBM Developer Works. http://www.ibm.com/developerworks/java/library/j-jtp07265/index.html. Retrieved 2008-12-23. 
  8. 8.0 8.1 Java for Scientific Computation: Prospects and Problems
  9. August 1998 Java News
  10. Closures Coming in Java 7
  11. The Trouble with Checked Exceptions
  12. Why doesn't C# have exception specifications?
  13. ECMA-355 4th Edition 12.4.2.5 Overview of exception handling
  14. Java Language Spec. 3rd Edition 14.20.2 Execution of try-catch-finally
  15. O'Reilly, Tim (2006-08-02). "Programming Language Trends". Radar. O'Reilly. http://radar.oreilly.com/archives/2006/08/programming_language_trends_1.html. 
  16. i-Technology Viewpoint: Java's Not Evolving Fast Enough
  17. Java 5 catches up with C#
  18. JSR 14: Add Generic Types To The JavaTM Programming Language
  19. Debate over closures for Java
  20. Property Support in Java, the Java Way
  21. CNET. "Sun, Microsoft settle Java suit". http://news.cnet.com/2100-1001-251401.html. 

External links

ja:C SharpとJavaの比較

ru:Сравнение C Sharp и Java zh:比較C Sharp和Java

Personal tools

Served in 0.842 secs.