Comparison of C Sharp and Java

From Free net encyclopedia

Template:Pound Template:Tone

This is a comparison of the C# programming language with the Java programming language. As two modern garbage-collected runtime-compiled languages derived from C and [[C++]], Java and C# are very similar. This page documents the strong general similarities of the languages and then points out those instances where the languages diverge. Both languages were designed carefully, and if one language has a feature another lacks it is the result of a conscientious design decision. Thus, the reader is advised to avoid the temptation to 'keep score,' and instead think about why the designers made each decision.

Contents

Rivalry and competition in the marketplace

Since C#'s inception the two languages have been compared and contrasted. It is undeniable that C# and the CLR (Common Language Runtime) managed code environment in which many C# applications run owe a lot to Java and the JRE (Java Runtime Environment). However C# also accommodates constructs more commonly found in languages such as C++ and scripting languages such as Ruby.

It is a frequently held charge that C# was created out of a political motivation by Microsoft, when the company recognised Java's long term threat to their operating system market lead, but became largely locked out of Java's future evolution following a legal spat with Sun Microsystems. (A legal action sparking claims of Embrace, extend and extinguish tactics, after Microsoft made key changes to the Java language, outside of the recognised development process, binding it more tightly to their Windows operating system and breaking an important core principle of the Java platform.)

It could also be argued, however, that Microsoft developed C# as a result of recognising the managed code environment which Java champions has many virtues in an increasingly networked world, particularly as the internet moves out onto devices other than personal computers, and security becomes ever more important. Finding the Java evolutionary process too rigid, and unable to influence the future direction of Java as it wanted, Microsoft created an alternative which more appropriately suited their own needs and vision of the future.

Little evidence is available to prove or disprove either theory, and which version one believes is usually down to whether one has largely pro or anti Microsoft leanings.

Despite this fractious start, as time has passed it has become apparent that the two languages rarely compete one-on-one in the marketplace. Java dominates the mobile sector, and has a large following within the web based applications market. C# is very slowly becoming recognised in the desktop market, which is probably Microsoft's desire as they increasingly push towards the use of managed code environments with their operating systems. C# is also a player in the web application market, thanks to Microsoft's .Net (dot net) framework.


Desktop Applications Market

Java has sometimes been accused of promising much and delivering little when it comes to desktop applications. It is true that although Java's AWT (Abstract Windowing Toolkit) and Swing libraries are not shy of features, Java has struggled to establish a foothold in the desktop market. Its rigid adherence to the notion of write once, run anywhere makes it difficult to use to the maximum the unique features and modes of working within each individual desktop environment.

Sun Microsystems have also been slow, in the eyes of some, to promote Java to developers and end users alike in a way which makes it an appealing choice for desktop software. Even technologies such as Java Web Start, which have few parallels within rival languages and platforms, have barely been promoted.

The release of Java version 6.0, sometime in 2006, sees a renewed focus on the desktop market — with an extensive set of new and interesting tools for better and closer integration with the desktop.


Server Applications Market

This is probably the arena in which the two languages are closest to being considered rivals. Java, through its J2EE (aka JavaEE, Java(2) Enterprise Edition) platform, and C# through .Net, compete to create web based dynamic content and applications.

Both languages are well used and supported in this market, with a bevy of tools and supporting products available for JavaEE and .Net.

However, Java and C# do not directly lock horns in this market, due to the development language usually being a secondary concern (some might even say a side effect) to the choice of operating system or framework. In short, the real rivalry is between Windows and Linux, or .Net and Apache, not Java and C#.

Mobile Applications Market

Java's J2ME (aka JavaME, Java(2) Micro Edition) has a very large base within the mobile phone and PDA markets, with only the cheapest devices now devoid of a KVM (a cut down Java Virtual Machine for use on devices with limited processing power.) Java software, including many games, is commonplace.

Currently few mobile applications are written in C#.

Similarities

Both languages are object oriented from the ground up, with a syntax similar to [[C++]]. (C++ in turn is derived from C.) Neither language is a superset of C or C++, however.

Both languages use garbage collection as a means of reclaiming memory resources, rather than formal deallocation of memory. And both include thread synchronization mechanisms as part of their language syntax.

Both languages support the idea of primitive types, and both allow boxing and unboxing to translate primitive data to and from object form. Strings are treated as objects, but support for string literals provides a specialised means of constructing them. Array and collection types are also given significance in the syntax of both languages, thanks to a modified iterator-based for loop, commonly known as foreach. Object types can be parameterized, to allow for generic programming. However, Java's generics employ erasure, making them compile time only.

Differences

C#'s syntax supports a wider range of constructs and notations than Java — borrowing, as it does, from many other languages in an attempt to appeal to as broad a church as possible.

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.

In terms of data types and data handling, C# implements properties as part of the language syntax. C# has support for output parameters, aiding in the return of multiple values. Event handling in C# is a "first class citizen" (part of the language syntax itself). Coupled with this, C# allows for Anonymous methods, providing closure functionality. Switch statements in C# also operate on strings.

C# permits the definition of "structs" — similar to classes but allocatable on the stack. C# carries more primitive types, with unsigned as well as signed types being supported. Java forgoes most unsigned types in favour of greater efficiency at the bytecode level. The biggest complaint here is that java lacks an unsigned byte primative.

C# language has many more features than Java. Whereas Java keeps things simple.

Java's strictfp keyword guarantees the result of floating point operations remain the same across platforms. While support for checked exceptions better enforces error trapping and handling.

Enumerations in C# uses a primative as the data. All valid values of the primative are valid values of the enum. This allows for ORing of flags together. Enumerations in Java are objects. The only valid values in a java enumeration are the ones listed in the enumeration. Java enumerations allow different methods implementations for each value in the enumeration.

Java has a staic import syntax that allows using the short name of some or all of the static methods/fields in a class.

C# allows a class to be refered by a different name via its using keyword.

Java has soft and weak references, and allows registering a listener that will be notified when a reference is garbage colleted, which allows for the good performance of the WeakHashMap that C# lacks. C# only has weak references.

The .Net Framework and the Java Virtual Machine

The .NET Framework is tied closely to the Windows operating system, allowing for native UI. While other implementations exist, they are not as developed as the official Microsoft version. The C# implementation Mono for Linux, Mac OS X, et al. is still incomplete. (It should be noted that only the C# language itself, not its associated tools and APIs, are non-proprietary.)

Java is ubiquitous across many disparate operating systems and environments. Numerous JVM implementations exist, some under open source licensing.

Java Webstart and Java applets provide convenient, lightweight and secure means of distributing an application to the desktop, while the efficiency of its bytecode representation, coupled with aggressive Java-specific compression technologies such as pack200, makes Java a very bandwidth-friendly means of distributing applications over a network.


Differences in maturity

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. Java dominates programming courses at high school and college level in the West, and there are currently many more Java than C# books. Java's maturity and popularity have ensured more third party Java API's and libraries (many of them open source) than C#.

By contrast, C# is a relatively new language. Microsoft has studied Java, building on its successes, and changed some aspects of the language to better suit certain types of applications. Over time Java's headstart may become less relevant.

An occassionally voiced criticism of the Java language is that it evolves slowly, lacking some features which make fashionable programming patterns and methodologies easier. An occassionally voiced criticism of the C# language is that its designers are perhaps too quick to pander to current trends in programming - lacking focus and simplicity. Certainly Java's designers seems to have taken a more conservative stand on adding major new features to their language syntax than other current languages - perhaps not wanting to tie the language too tightly with trends which may in the medium/long term be dead ends.

C# has evolved rapidly to include some very problem-specific features, such as (in 3.0) support for the database language SQL and the metadata format XML, directly within the syntax of the language itself (rather than as API's). Similar language additions to Java have been considered and, for now at least, rejected. While adding syntactic shortcuts may be popular in the short term, the danger is that in years to come the language syntax may become cluttered with ideas and technologies which, while once popular, have long since been abandoned or replaced. This approach, along with a number of other new languages and technologies which address themselves specifically at 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.

Philosophical differences between the languages

  • There are no unsigned primitive numeric types in Java. While it is universally agreed that mixing signed and unsigned variables in code is bad, Java's lack of support for unsigned numeric types makes it somewhat unsuited for low-level programming.
  • C# does not include checked exceptions. Some would argue that checked exceptions are very helpful for good programming practice. Others, including Anders Hejlsberg, chief C# language architect, argue that they were to some extent an experiment in Java and that they haven't been shown to be worthwhile [1] [2].
  • C#'s namespaces are more similar to those in C++. Unlike Java, the namespace does not specify the location of the source file. (Actually, it's not strictly necessary for a Java source file location to mirror its package directory structure.)
  • C# includes delegates, whereas Java does not. Some argue that delegates complicate the method invocation model, because they are handled through reflection, which is generally slow. On the other hand, they can simplify the code by removing the need to declare new (possibly anonymous) classes to hook to events.
  • Java requires that a source file name must match the only public class inside it, while C# allows multiple public classes in the same file.
  • C# allows the use of pointers, which some language designers consider to be unsafe, but certain language features try to ensure this functionality is not misused accidentally. Pointers also greatly complicate technologies such as Java's RMI (Remote Method Invocation), where program objects resident on one computer can be referenced within a program running on an entirely separate computer. Some have speculated that the lack of memory pointers in Java (substituted by the more abstract notion of object references) was a nod towards the coming of grid computing, where a single application may be distributed across many physical pieces of hardware.
  • C# supports the goto keyword. This can occasionally be useful, but the use of a more structured method of control flow is usually recommended. However, Java allows qualified breaks and continues, which make up for many of the uses of goto.
  • C# has true multi-dimensional arrays, as well as the array-of-arrays that is available to Java (which C# calls jagged arrays). Multi-dimensional arrays are always rectangular (in the 2D case, or analogous for more dimensions), whereas an array-of-arrays may store rows (again in the 2D case) of various lengths. Rectangular arrays may speed access if memory is a bottleneck (there is only one memory reference instead of two; this benefit is very dependent on cache behavior) while jagged arrays save memory if it's not full but cost (at the penalty of one pointer per row) if it is. Rectangular arrays also obviate the need to allocate memory for each row explicitly.
  • Java does not include operator overloading, because abuse of operator overloading can lead to code that is harder to understand and debug. C# allows operator overloading, which, when used carefully, can make code terser and more readable. Java's lack of overloading makes it somewhat unsuited for certain mathematical programs. Conversely, .NET's numeric types do not share a common interface or superclass with add/subtract/etc. methods, restricting the flexibility of numerical libraries.
  • Methods in C# are non-virtual by default. In Java however, methods are virtual by default. Virtual methods guarantee that the most overridden method of an object will be called which is determined by the runtime. You always have to keep that in mind when calling or writing any virtual method! If the method is declared as non-virtual, the method to invoke will be determined by the compiler. This is a major difference of philosophy between the designers of the Java and .NET platforms.
  • Java 1.5's generics use type-erasure. Information about the generic types is ignored at runtime, and only obtainable via reflection on the static class objects. .NET 2.0's generics are preserved at runtime due to generics support starting in version 2.0 of the .NET Common Language Runtime, or CLR for short. Java's approach requires additional type checks, does not guarantee that generic contract will be followed, and lacks reflection on the generic types, whereas in C# each new generic combination requires classes and methods be recompiled which requires more memory.
  • C# is defined by ECMA and ISO standards, whereas Java is proprietary, though largely controlled through an open community process.
  • The C# API is completely controlled by Microsoft, whereas the Java API is managed through an open community process.
  • The .NET run-time allows both managed and unmanaged code, enabling certain classes of bugs that do not exist in Java's pure managed code environment but also allows interfacing with existing code.

See also

  • [[Comparison of Java and C++]]

External links