Comparison of C Sharp and Java
From Wikipedia, the free encyclopedia
- The correct title of this article is Comparison of C# and Java. The substitution or omission of a # sign is because of technical restrictions.
This article is part of the Programming Language Comparison series. |
General Comparison |
Basic Syntax |
String Operations |
String Functions |
|
Evaluation strategy |
List of "hello world" programs |
|
Compatibility of C and C++ |
Comparison of C and Pascal |
Comparison of C++ and Java |
Comparison of C# and Java |
Comparison of C# and Visual Basic .NET |
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 differ. Both languages were designed carefully, and if one language has a feature another lacks it is the result of a conscious 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
|
[edit] Language
[edit] Object handling
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 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 Java and C# have strong and weak object references. Java allows registering a listener that will be notified when a reference is garbage collected, which allows for the good performance of the WeakHashMap that C# lacks. C# only supports this by using a finalizer (which is also available in Java). C# on the other hand allows the programmer to suppress the finalizer of a specific object (e.g., an SQL connection or a file stream that always needs to be properly closed). This can be very useful since finalizers are expensive in generational garbage collection (applied by both Java and .NET), and are often used only as a fail-safe for when the programmer does not close the object. An object with a finalizer will normally be promoted to an extra generation and kept alive longer before it is collected.
C# allows restricted use of pointers, which are considered unsafe by some language designers. 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 only used to allow better interoperability with unmanaged APIs or system calls (which are inherently "unsafe"), or sometimes as a small performance enhancement.
[edit] Data types
Both languages support the idea of primitive types (known as value types in C#). C# has more primitive types than Java, with unsigned as well as signed integer types being supported, and a special decimal
type for decimal floating-point calculations. Java lacks unsigned types. In particular, Java lacks a primitive type for an unsigned byte. Strings are treated as (immutable) objects in both languages, but support for string literals provides a specialised means of constructing them. C# also allows verbatim strings for quotation without escape sequences, which also allow newlines.
Both allow 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 the primitive types can define methods, such as an override of Object's ToString()
method. In Java, separate primitive wrapper classes are provided for this, which means it requires a static call Integer.toString(42)
instead of an instance call 42.ToString()
. Another difference is that Java makes heavy use of such types in generics, and as such allows an implicit unboxing conversion (in C# this requires a cast). This conversion can potentially throw an (unchecked) null pointer exception, which may not be obvious by inspection of the code in Java.
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 allocated on the stack rather than on the heap. 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).
Enumerations in C# are derived from a primitive 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. This allows to combine enumeration values together using the bitwise OR operator if they are bit flags. Enumeration values in Java, on the other hand, are objects. The only valid values in a Java enumeration are the ones listed in the enumeration. A special enumeration set object is needed to combine enumeration values together. Java enumerations allow differing method implementations for each value in the enumeration. Both C# and Java enumerations can be converted to strings, but only Java enumerations allow to customize such conversion.
[edit] Arrays
Array and collection types are also given significance in the syntax of both languages, thanks to an iterator-based foreach statement loop. In both languages an array corresponds to an object of the Array
class, although in Java this class does not implement any of the collection interfaces. C# has true multi-dimensional arrays, as well as the arrays-of-arrays that are available in Java (and which in C# are commonly called jagged arrays). Multi-dimensional 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 multi-dimensional array can be allocated with a single application of operator new
, while jagged arrays require explicit loops and allocations for every dimension.
[edit] Inner classes
Both 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 static
, then it only has access to the static members). Local classes can be defined within a method and have read-only access to the method's local variables, and anonymous local classes allow to create class instances overriding some of their class methods.
C# only provides static inner classes, and requires an explicit reference to the outer class to its non-static members; no local inner classes are supported. Instead, C# provides anonymous delegates as a construct that can provide access to local variables and members (see Event handling).
[edit] Generics
- Further information: Generic programming
Generics in Java are implemented by using type erasure. This means that information about the generic types is ignored at runtime, and only obtainable via reflection on the static class objects. In .NET 2.0, information on generic types is fully preserved at runtime. Java's approach requires additional run time type checks, does not guarantee that generic contract will be followed, and lacks reflection on the 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,[1] but for C# the CLR dynamically generates optimized code for specializations on value types. In .NET, type safety for generics is fully checked at compile time and enforced at load time by the CLR. In Java, it is only partially checked at compile time and needs to be enforced using cast operations at run time, as the Java VM is not aware of generic types.
[edit] Notation and special features
[edit] Special feature keywords
keyword | feature, example usage |
---|---|
get, set | C# implements properties as part of the language syntax, as an alternative for the accessor methods used in Java. |
out, ref | C# has support for output and reference parameters. These allow returning multiple output values from a method, or passing values by reference. |
switch | In C#, the switch statement also operates on strings and long. Java switch statement does not operate on long primitive type. |
strictfp | Java uses strictfp to guarantee the result of floating point operations remain the same across platforms. |
checked, unchecked | In C#, checked statement blocks or expressions can enable run-time checking for arithmetic overflow. |
using | C#'s using forces the object created to be disposed or closed after the code block has run.
// 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"); } |
goto | C# supports the goto keyword. This can occasionally be useful, but the use of a more structured method of control flow is usually recommended. A common use of the goto keyword in C# is to transfer control to a different case label within a switch statement. Both C# and Java allow qualified 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; // ... } |
[edit] Event handling
Java requires the programmer to implement the observer pattern manually, though it provides some syntactic sugar in form of anonymous inner classes, which allow one to define the body of the class and create an instance of it in a single point in the code. This is typically used to create observers.
C# provides extensive support for event-driven programming at language level, including delegate types. These 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.
Closures have also been proposed as a new feature for Java SE 7. [2] Like delegates in C#, such closures would have full access to all local variables in scope, not just read-only access to those marked final
(as with anonymous inner classes).
[edit] Numeric applications
To adequately support applications in the field of mathematic and financial computation, several language features exist.[3] 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 representation decimal numbers and hence introduce rounding errors. For financial applications, an accurate decimal type is essential. Since Java 5.0, the BigDecimal
class also provides such characteristics for Java.[4] BigDecimal
and BigInteger
are types provided with Java that allow arbitrary-precision representation of numbers. The .NET framework does not currently include such classes, although third party implementations exist as well as plans to include such types for the next framework version.[5]
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 tolong
. - 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.[3]
[edit] 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.
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 indexes can be objects of any type:
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 terser and more readable.
[edit] Methods
Methods in C# are non-virtual by default, and have to be declared virtual explicitly if desired. In Java, non-final methods are virtual by default. Virtualness 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. Some JVM implementations, including the Sun reference implementation, implement inlining of the most commonly called virtual methods to reduce the runtime overhead from virtual method calls.
In Java there is no way to make methods non-virtual (although they can be "sealed" by using the final
modifier to disallow overriding). This means that 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 explicit declaration of intent when overriding virtual methods in a derived class. If a method should be overridden, the override
modifier must be specified. If overriding is not desired, and the class designer merely wishes to introduce a new method shadowing the old one, the new
keyword must be specified.
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.
[edit] 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 that can be enabled and disabled at runtime.
[edit] 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 default behavior.
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 classes (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 will introduce 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
).
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, and puts no restrictions on the file name. As of Version 2, C# allows a class definition to be split into several files, by using the partial
keyword in the source code.
[edit] Exception handling
Java supports checked exceptions (in addition to unchecked exceptions). C# only supports unchecked exceptions. Checked exceptions enforce the programmer to declare all exceptions thrown in a method, and to catch all exceptions thrown by a method invocation.
Some would argue that checked exceptions are very helpful for good programming practice, ensuring that all errors are dealt with. 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 except for in small example programs.[7][8] One criticism is that checked exceptions encourage programmers to use an empty catch block, resulting only in code bloat: catch (Exception e) {}
. 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 SQLException
could be caught and re-thrown as an IOException
, 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
. This may result in unexpected behavior, especially if try-code and finally-code return different values. C# resolves this problem by prohibiting any control-passing statements like return
or break
in the finally block.
[edit] Lower level code
The 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 no direct access to legacy 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. A program or assembly 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.
[edit] Implementations
[edit] JVM and CLR
Java is ubiquitous across many disparate operating systems and environments. Numerous JVM implementations exist.
C# is also a cross-platform standard. The primary platform is Windows, but implementations do exist for other platforms as well, most notably the Mono Project.
[edit] Standardization
The two languages, their programming interfaces, their binary formats, and their runtime environments have largely been governed by very different means.
C# is defined by Ecma and the ISO, which define the language syntax, executable format (known as the Common Language Infrastructure, or CLI), and foundation classes (the Base Class Library, or BCL). The standards do not include many new libraries that Microsoft has implemented on top of the standard framework, such as those for accessing databases, or building GUI and Web applications, such as Windows Forms, ASP.NET and ADO.NET.
To date, no part of Java has been standardized by Ecma, the ISO, the ANSI, or any other third-party standards organization. While Sun Microsystems has unlimited and exclusive legal rights to modify and license its Java trademarks, source code, and other materials, Sun voluntarily participates in a process called the Java Community Process (JCP) that allows interested parties to propose changes to any of Sun's Java technologies (from language and tools to API) via consultation exercises and expert groups. Within the rules of the JCP, any proposal for new Platform Edition Specifications or changes to the Java language, is subject to unilateral rejection by Sun because approval requires a Yes vote by Sun. The JCP requires a membership fee for commercial contributors, while non-commercial contributors and individuals can join for free.
[edit] License
While "Java" is a Sun trademark, and only Sun can license the name "Java", numerous free software projects exist that are partially compatible with Sun Java. Most notably, GNU Classpath and GCJ provide a free software class library and a compiler that are partially compatible with the current version of Sun Java.[9] Sun has announced in November 13, 2006 that all Java source code, excluding closed-source code for which they do not retain rights, will be released as free software under a modified version of the GPL by March 2007.[10] Sun is currently distributing its HotSpot Virtual Machine and Java programming-language compiler under the GPL, but the standard Sun Java runtime environment is not currently available under a free software license.[11][12] Because Sun will retain copyright proprietorship for its Java source code, a release under the GPL will not prohibit Sun from distributing non-free or non-open versions of Java, or licensing others to do so.[13]
C#, the CLI executable environment, and much of the corresponding class library have been standardized and can be freely implemented without a license. Several standards-compliant free software C# environments have been implemented such as the Mono Project and DotGNU. The Mono Project has also implemented many of Microsoft's non-standard libraries by examining Microsoft materials, similar to GNU Classpath and Java. The Mono project aims to avoid infringing on any patents or copyrights, and to the extent that they are successful, the project can be safely distributed and used under the GPL.[14][15] .Microsoft is currently distributing a shared source version of its .NET runtime environment for non-profit use. [16]
[edit] Usage
[edit] Community
In its proprietorship of Java, Sun works with an open culture, allowing multiple parties, from organizations to individuals, to steer the decision making process. While Sun retains exclusive and unlimited legal rights to its Java intellectual properties, and the Java community is subject to those rights, Sun's acceptance of third-party contributions goes to solve the problem of vendor lock-in at the cost of creating a baffling array of options for beginners wishing to choose a Java-based solution. Java has grown in popularity to become one of the most popular languages of the early 21st century, and the pluralist nature of its development has resulted in many different groups tackling the same (or similar) problems. This issue is particularly acute in the Enterprise space (web/Ajax/Web2.0 applications), where one must not only be familiar with Java, but also the various competing frameworks.
On the other hand, while Microsoft has developed C# and .NET without a formal community contribution system, the language and some parts of the executable format and runtime have been standardized and freely distributed through Ecma and the ISO in an open and vendor-neutral process, rather than a process that retains veto and copy rights for Microsoft. However, the standards do not include many new libraries that Microsoft has implemented on top of the standard framework (see Standardization). Numerous C# and CLI community software projects, help and documentation sites, and discussion forums are under active development and maintenance, including those focusing on Windows development with Microsoft .NET or the Mono project, Free software Operating system development under the Mono project, and mobile development using Microsoft's .NET compact framework.
Microsoft is distributing a shared source release (version 1.0) of the .NET virtual machine that can be compiled and used on Windows, FreeBSD, Mac OS X, and other platforms.[17] An updated version (2.0) is currently available, but the only officially supported platform is Windows.[18] A community port to Linux of the 1.0 shared source .NET virtual machine is also available.[19] In March 2003, O'Reilly Media published a book about Microsoft's shared source .NET virtual machine.[20]
Sun has announced that all Java source code will be released under a GPL license by March 2007 (see License).
[edit] Popularity and evolution
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 United States, and there are currently more Java than C# books [5]. Java's maturity and popularity have ensured more third party Java API and libraries (many of them open source) than C# [21] [6].
By contrast, C# is a relatively new language. Microsoft has studied existing languages such as Java and Delphi, and has changed some aspects of the language and runtime environment in response to perceived failures and difficulties with its predecessors.
An occasionally voiced criticism of the Java language is that it evolves slowly, lacking some features which make fashionable programming patterns and methodologies easier.[citation needed] An occasionally 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.[citation needed] Certainly Java's designers seem 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. With the Java 5.0 release, this trend may have been broken, as it introduced several new major language features: foreach statement, autoboxing, methods with variable number of parameters (varargs), enumerated types, generic types, and annotations. It should be noted that all of those, except generic types, were already present in C# by that time, some under different names.[22]
C# has evolved rapidly to attempt to streamline development for problem-specific features. C# 3.0 adds a 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. 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 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.
[edit] 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 most 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++, Delphi (designing which was Anders Hejlsberg's principal job when he was at Borland), and, in recent C# versions, borrowing from dynamic scripting languages such as Ruby.
It can be argued that Microsoft developed C# in some part as a result of recognizing that 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. 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#.
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 well recognized in the Windows desktop market, and is being pushed by Microsoft as the language for Windows applications. C# is also a player in the web application market, thanks to ASP.NET.
[edit] Desktop applications
Java has sometimes been accused of promising much and delivering little when it comes to desktop applications.[citation needed] 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. In the past, desktop applications written in Java have often been accused of looking "alien" on any platform they are run on, although recent versions of Java have started allowing greater use of native widgets.[23] Sun Microsystems has also been slow, in the eyes of some,[citation needed] 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 in December 11, 2006, saw a renewed focus on the desktop market with an extensive set of new tools for closer integration with the desktop.
[edit] Server applications
This is probably the arena in which the two languages are closest to being considered rivals. Java, through its Java EE (aka J2EE, Java(2) Enterprise Edition) platform, and C# through ASP.NET, compete to create web-based dynamic content and applications.
Some of Sun's current Java-related license agreements for Java EE define aspects of the Java platform as a trade secret,[24] and prohibit the end user from contributing to a third-party Java environment. Specifically, at least one current license for a Sun Java EE development package contains the following terms: "You may make a single archival copy of Software, but otherwise may not copy, modify, or distribute Software." — "Unless enforcement is prohibited by applicable law, you may not decompile, or reverse engineer Software." — "You may not publish or provide the results of any benchmark or comparison tests run on Software to any third party without the prior written consent of Sun." — "Software is confidential and copyrighted." For the full license text, select "Review License Agreement" from the referenced Sun Java SDK download page.[24] However, while Sun's software is subject to the above license terms, Sun's Java EE API reference has been implemented under an open source license by the JOnAS project.
Microsoft's implementation of ASP.NET is not part of the standardized CLI, and while Microsoft's runtime environment and development tools are not subject to comparable secrecy agreements to Java EE, the official Microsoft tools are not open source or free software, and require Windows servers. However, a cross-platform free software ASP.NET 1.1 implementation is part of the Mono project.[25]
Both languages are well used and supported in this market, with a bevy of tools and supporting products available for Java EE and .NET.
[edit] Mobile applications
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.
While almost every mobile phone includes a JVM, these features are not always heavily used by users (particularly in North America). Initially Java applications on most phones typically consisted of menuing systems, small games, or systems to download ringtones etc. However, more powerful phones are increasingly being sold with simple applications pre-loaded, such as translation dictionaries, world clock displays (darkness/light, timezones, etc.) and calculators. Some of these are written in Java, although how often phone owners actually use them is probably unknown.
[edit] Leading edge technologies
Java has found a market in digital television, where it can be used to provide software which sits alongside programming, or extends the capabilities of a given Set Top Box. TiVo, for example, has a facility called "Home Media Engine", which allows JavaTV software to be transmitted to an appropriate TiVo device to compliment programming or provide extra functionality (for example, personalised stock tickers on a business news program.)
A variant of Java has been accepted as the official software tool for use on the next generation optical disc technology Blu-ray, via the BD-J interactive platform. This will mean that interactive content, such as menus, games, downloadables, etc. on all Blu-ray optical discs will be created under a variant of the Java platform. Blu-ray equipment first went on sale to the consumer in 2006, and is currently not widely owned. However, the release of the Sony Playstation 3 in late 2006 and early 2007 may give the platform a boost.
Rather than using Java, HD DVD (the high definition successor to DVD) uses a technology jointly developed by Microsoft and Disney called iHD that is based on XML, CSS, JavaScript, and other technologies that are comparable to those used by standard web browsers.
The BD-J platform is more sophisticated than its iHD rival, effectively capable of delivering a rich client, almost 'desktop-application-like' experience, compared to the 'Web-application' experience of iHD. However, as format wars have proven in the past, the most powerful technology is not always the winner.
[edit] Runtime market share
Free software operating systems are currently unable to include any Sun Java Runtime Environment because Sun has not yet released its Java class library under a license that is compatible with the GPL.[12][26][27] However, Sun has announced that it intends to release a Java runtime environment under a modified version of the GPL by March 2007, and has already released two fundamental parts of the JRE and JDK: HotSpot and the javac compiler under the GPL.
On Windows platforms, Microsoft is promoting C# as its flagship language,[28] in part by including the .NET runtime in all recent Windows environments, and by distributing the Visual C# Express development environment at no cost.[29] C# and the CLI have recently become popular with a number of Linux and BSD based operating systems by way of including the free software Mono Project.[30][31][32] Both Microsoft .NET and the Mono project have complete support for the standardized C# language and runtime, and Mono has extensive support for various non-standardized .NET components such as Windows Forms.
As a result of inclusion of .NET or Mono runtimes in the official distributions of many desktop operating systems, desktop applications that utilize the programming interfaces that are common to both .NET and Mono can be developed in C# and then seamlessly deployed across many operating systems and processor architectures using a runtime environment that is available as a part of the operating system's installation.[7][8][9]
Windows does not currently ship with a Java runtime environment, however some OEMs pre-install the JRE on their desktop and laptop models [33]. Apple's support for Java means it has come pre-installed on all new Apple computers since the launch of MacOS X. However, Sun's Java runtime environment can not be included with free software operating systems (of which some Linux flavours are leading examples, see above), and the free software GNU classpath project is only partially compatible with the current version of Sun Java.[34] GNU classpath is 99% compatible with the 1.4 version of Sun Java.[35] While Mono has complete support for the portions of Microsoft .NET that have been standardized by Ecma and the ISO, and 99% complete support for the Windows Forms graphical application toolkit 1.1,[36] Mono lacks support for parts of the latest Microsoft .NET runtime and API, such as the EnterpriseServices namespace (see Mono status), or Windows Forms 2.0[37].
[edit] See also
- Comparison of C# and VB.Net
- Comparison of Java and C++
- Criticism of Java
- Java programming language
- C#
[edit] References
- ^ Generics in C#, Java, and C++
- ^ InfoQ: Closures proposed for Java
- ^ a b Java for Scientific Computation: Prospects and Problems
- ^ JSR 13: Decimal Arithmetic Enhancement specifies enhancements to the
BigDecimal
type that were implemented in Java 5.0, to allow broader usage of the type. - ^ Introducing: System.Numeric.BigInteger
- ^ August 1998 Java News
- ^ The Trouble with Checked Exceptions
- ^ Why doesn't C# have exception specifications?
- ^ Results of comparison between jdk15 and classpath
- ^ http://www.sun.com/software/opensource/java/project_overview.jsp
- ^ Sun openjdk: Home
- ^ a b Sun Java 2 Runtime License Agreement
- ^ GNU General Public License - GNU Project - Free Software Foundation (FSF)
- ^ On November 2, 2006, Microsoft and Novell announced a joint agreement whereby Microsoft agreed to not sue Novell or its customers for patent infringement [1]. According to a statement on the blog of Mono project leader Miguel de Icaza, this agreement extends to Mono but only for Novell developers and users. It was criticized by the open source community because it violates the principles of giving equal rights to all users of a particular program (see Patent Agreement with Microsoft and Mono and Microsoft's patents). On February 2007, the Free Software Foundation announced that it is reviewing Novell's right to sell Linux versions, and even may ban Novell from selling Linux, because of this agreement [2]
- ^ Mono FAQ: Licensing (Patents)
- ^ Rotor: Shared Source CLI Provides Source Code for a FreeBSD Implementation of .NET
- ^ Shared Source Common Language Infrastructure 1.0 Release
- ^ Shared Source Common Language Infrastructure 2.0 Release
- ^ Rotor Comes to Linux
- ^ oreilly.com -- Online Catalog: Shared Source CLI Essentials
- ^ In November 2005, there were more Java projects on Sourceforge than for any other language, including C and C++ (more than 16000 projects by end 2005, almost 24000 by end 2006). By contrast, there were less than 3000 C# projects by en 2005, and less than 6000 by end 2006 [3] (see also here for updated 2006 informations measured in hits in Google blogs).
- ^ Java 5 catches up with C#
- ^ Java – What's New in Java SE 6
- ^ a b Java EE SDK 5 Update 2 No JDK download page (reference to license agreement)
- ^ Mono: ASP.NET
- ^ GNU Classpath FAQ: isn't java free already?
- ^ GNU classpath tainted developer description
- ^ Microsoft article that refers to C# as its "flagship" language.
- ^ microsoft.com: Visual C#
- ^ Fedora embraces Mono - ZDNet UK
- ^ Debian -- mono
- ^ Wikipedia Uses Mono; Mono Integrated into Ubuntu/Debian - OSNews.com
- ^ Sun signs up five more OEMs for Java
- ^ Results of comparison between jdk15 and classpath
- ^ Results of comparison between jdk14 and classpath
- ^ Mono Windows forms status
- ^ Mono current version is 1.2.3 (as of February 2007). This version provides the core API of the .NET Framework 2.0, but its implementation of this API is still incomplete [4]
[edit] External links
- Contrasting C# and Java Syntax
- Java vs. C# - Code for Code Comparison
- Nine Language Performance Round-up
- Java and C-Sharp Compared
- MSDN: The C# Programming Language for Java Developers
Architecture: | Common Language Infrastructure • .NET assembly • .NET metadata • Base Class Library |
Common Language Infrastructure: | Common Language Runtime • Common Type System • Common Intermediate Language • Virtual Execution System |
Languages: | C# • Visual Basic .NET • C++/CLI (Managed) • J# • JScript .NET • Windows PowerShell • IronPython • F# |
Windows Foundations: | Presentation • Communication • Workflow • CardSpace |
Related: | Windows Forms • ASP.NET • ADO.NET • .NET Remoting • XAML |
Other Implementations: | .NET Compact Framework • .NET Micro Framework • Shared Source CLI • Portable.NET • Mono |
Comparison: | C# vs. Java • C# vs. VB.NET |