|
The correct title of this article is Comparison of Java and C#. The substitution or omission of a # sign is because of technical restrictions.
You may be looking for Comparison of C# and Visual Basic .NET.
This is a comparison of the C# programming language with the Java programming language. As the two are both garbage-collected runtime-compiled languages with syntax derived from C and C++, there are many similarities between Java and C#. However, there are also many differences, with C# being described as a hybrid of C++ and Java, with additional new features and changes. This page documents the strong general similarities of the languages and then points out those instances where the languages differ.
[edit] Language[edit] Object handlingBoth C# and also Java are designed from the ground up as object oriented languages using dynamic dispatch, with a 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. [edit] ReferencesC# allows restricted use of pointers. 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 [edit] Data typesBoth languages support the idea of primitive types (all of which, except for string, are value types in C#/.NET). C# has more primitive types than Java, with unsigned as well as signed integer types being supported, and a 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 [edit] Value typesC# allows the programmer to create user-defined value types, using the [edit] EnumerationsEnumerations in C# are derived from a primitive 8, 16, 32, or 64 bit integer type. 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. [edit] ArraysArray 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 [edit] Inner classesBoth languages allow inner classes, where a class is defined entirely within another class. In Java, these classes have access to both the static and non-static members of the outer class (unless the inner class is declared C# also provides inner classes, but unlike Java, requires an explicit reference to the outer class to its non-static members. Also, C# provides anonymous delegates as a construct that can provide access to local variables and members (see Event handling). Local classes and anonymous classes are not available. [edit] Partial classesC# 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 [edit] Generics
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., [edit] Notation and special features[edit] Special feature keywords
[edit] Callbacks and Event handlingC# 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.[2][3] Java does not have a language-level construct like the C# delegate. The observer[4] 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] [edit] Numeric applicationsTo adequately support applications in the field of mathematic and financial computation, several language features exist.[5] 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 The In Java there is no way to provide the same level of integration for library-defined types such as
In addition to this, C# can help mathematic applications with the [edit] Operator overloadingC# 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. C# includes indexers which can be considered a special case of operator overloading (like C++ myList[4] = 5; string name = xmlNode.Attributes["name"]; orders = customerMap[theCustomer]; Java does not include operator overloading in order to prevent abuse of the feature, and to keep the language simpler.[6] C# allows operator overloading (subject to certain restrictions to ensure logical coherence), which, when used carefully, can make code succinct and more readable. [edit] MethodsMethods 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 [edit] Explicit interface implementationIf 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) 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. [edit] ClosuresWhen 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 Javas 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. Closures have also been proposed as a new feature for Java SE 7.[7] Like delegates in C#, such closures would have full access to all local variables in scope, not just read-only access to those marked [edit] Lambdas and expression treesC# also features a special type of inline closures called lambdas. These are not methods as they cannot form part of a class interface; they are more in the realm of 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, expression trees or any corresponding concept. [edit] Partial methodsRelated 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 ensures 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. [edit] Extension methodsUsing a special this designator on the first parameter of a method, C# allows the method to act as if it was 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. [edit] Generator methodsA C# method which is declared as returning [edit] Conditional compilationUnlike Java, C# implements conditional compilation using preprocessor directives. It also provides a [edit] Namespaces and source filesC#'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., 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 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 [edit] Exception handlingJava supports checked exceptions (in addition to unchecked exceptions). C# only supports unchecked exceptions. Checked exceptions force the programmer to declare all exceptions thrown in a method, and to catch all exceptions thrown by a method invocation. 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 for in small example programs.[8][9] One criticism is that checked exceptions encourage programmers to use an empty catch block, which silently eats exceptions rather than letting the exceptions propagate to a higher-level exception-handling routine: There are also differences between the two languages in treating the 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 [edit] Lower level codeThe Java Native Interface (JNI) feature allows Java programs to call non-Java code. However, JNI does require the code to be 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++. 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 [edit] Language history and evolution[edit] 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.[10] 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[who?] 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.[11] 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[12]) 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 on going debate with the inclusion of closures[13] and properties[14] into the language syntax for Java 7. [edit] 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 (designing 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. C# has evolved rapidly to attempt 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. It however builds upon general-purpose language features; lambda expressions and extension methods features, that also allow such 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 won, thus preventing Microsoft from further production of J++. With the release of the .NET framework (and C#), the project was revived in the form of J#. [edit] See also
[edit] References
[edit] External links
offerte voli | hoteles | precios | voli | die verzeichnis | annuarie web | stop smoking london | |||||||||||||||||||||||||||||||||||||||||||||||||||||||