Comparing .NET to Java

Team-Fly    

 
.NET and COM Interoperability Handbook, The
By Alan Gordon
Table of Contents
Chapter One.  What's in a Name ?


If you know anything about Java, by the time you have reached this point in this chapter, you are probably thinking that .NET sounds like Microsoft just created its own version of Java. To some extent, that is an accurate assessment of .NET. There are some important differences though between the .NET architecture and Java. This sidebar summarizes the important similarities and differences.

Let's start by clearing up some misconceptions about Java. People often refer to Java as a single entity when it is really composed of three distinct (and largely independent) pieces of technology:

  1. The Java programming language Sun Microsystems defined a simple, object-oriented language that borrows most of the syntax of C++, but eschews most of C++'s more complexand difficult to understandfeatures like pointers, operator overloading, and templates. Garbage collection and support for try/catch exception handling also makes this language a less error-prone and more productive language than C or C++.

  2. The Java libraries The Java SDK includes an object-oriented library that abstracts all the services that an operating system provides. In the Java libraries, which ship with the Java SDK, you will find classes for essential operating system services like basic GUI primitives (Windows, dialogs, message boxes, and standard controls like edit boxes and list boxes), more complex GUI elements (grids, trees, date/time pickers, and so forth), file and console I/O, 2D and 3D graphics, networking, and security. You will also find classes that provide you with the essential building blocks that you need to build any nontrivial application like collections, string manipulation, mathematics, database access, and more. You could use the Java programming language and not use the libraries. Microsoft created operating system specific APIs like J-Direct and the Windows Foundation Classes (WFC) for use with the Java programming language (precipitating the now-famous lawsuit against them). However, having a common, platform-independent API to the operating system and other essential services is the key to the Java programming language running on all platforms, which is why Sun Microsystems sued Microsoft when it attempted to separate the Java programming language from the Java libraries. The Java libraries are absolutely key to the Java programming language's cross-platform potential.

  3. The Java runtime The Java programming language was designed to be an interpreted language. Java source code is compiled into platform-independent bytecodes. You can think of these bytecodes as a virtual assembly language. These bytescodes are executed using a Java interpreterthe Java runtime. This is the recommended way of executing Java code. You can use the Java language and the Java libraries without using the Java runtime. There are Java compilers available that can compile Java source to native executables for a particular platform. Some Java interpreters also use JIT compilation to convert the bytecodes into native code for a particular platform as it is running.

Microsoft's .NET Framework competes against each of these Java technologies. Let's consider each Java technology versus its .NET counterpart .

The Java Programming Language versus C#

To put it bluntly, C# is almost identical to the Java programming language. However, I don't think it's fair to say that C# is a Java programming language "ripoff" as I'm sure many people will say. Both languages have a common lineage. They are both simplified and more object-oriented variants of C++. The biggest difference between the Java programming language and C# is that, in order to use the Java libraries and the Java runtime, you must also use the Java programming language. You can, however, use all the features of the .NET Framework without using C#. The .NET Framework includes a CLR that allows you to use a variety of languages, including: Visual Basic, JScript, Cobol, Pascal, Smalltalk, and even the Java programming language, and you can still take advantage of the .NET Framework libraries and the .NET runtime environment.

Note

Microsoft has released a .NET version of the Java programming language called J# (pronounced J-Sharp). You can find out more about J# at the following URL: http://msdn.microsoft.com/vjsharp/.


I can illustrate the similarity and some of the key differences between the Java programming language and C# using a simple program that I write in both languages. This program was carefully designed to illustrate the important differences between the two languages (see Listings 1.1 and 1.2).

Listing 1.1 A simple program written in the Java programming language
 1.  import java.io.*; 2.  import java.util.Date; 3.  class Employee 4.  { 5.    public Employee(String nm,Date hireDate) 6.    { 7.      m_name=nm; 8.      m_hireDate=hireDate; 9.    } 10.   public float getSalary() 11.   { 12.     return 50; 13.   } 14.   public String JobDescription() 15.   { 16.     return "Employee"; 17.   } 18.   public String getName() 19.   { 20.     return m_name; 21.   } 22.   public void setName(String newName) 23.   { 24.     m_name=newName; 25.   } 26.   public void WriteToStream(PrintStream strm) throws IOException 27.   { 28.     strm.println(this.JobDescription()); 29.     strm.print("Name = "); 30.     strm.println(this.getName()); 31.     strm.print("Salary = "); 32.     strm.println(this.getSalary()); 33.     strm.print("Hire date = "); 34.     strm.println(m_hireDate.toString()); 35.   } 36.   private String m_name; 37.   private Date m_hireDate; 38. } 39. 40. class Manager extends Employee 41. { 42.   public Manager(String nm,Date hireDate, int numStockOptions) 43.   { 44.     super(nm,hireDate); 45.     m_numStockOptions=numStockOptions; 46.   } 47.   public float getSalary() 48.   { 49.     return 500; 50.   } 51.   public String JobDescription() 52.   { 53.     return "Manager"; 54.   } 55.   private int m_numStockOptions; 56. } 57. class HelloWorld 58. { 59.   public static void main(String[] args) 60.   { 61.     try 62.     { 63.       if (args.length == 2) 64.       { 65.         Employee emp=new Manager(args[0],new Date(),Integer.parseInt(args[1])); 66.         emp.WriteToStream(System.out); 67.       } 68.       else 69.       { 70.         System.err.println("Usage: HelloWorld Name #OfStockOptions"); 71.       } 72.     } 73.     catch (IOException ex) 74.     { 75.       System.err.println(ex.getMessage()); 76.     } 77.     catch (NumberFormatException ex) 78.     { 79.       System.err.println("The second argument must be a number"); 80.     } 81.     catch (Exception ex) 82.     { 83.       System.err.println("The second argument must be a number"); 84.     } 85.   } 86. } 

If you run this program with the following command line:

 HelloWorld "Alan Gordon" 5000 

you will see the following output:

 Employee: Name = Alan Gordon Salary = 500.0 Hire Date = Mon Oct 02 00:38:57 PDT 2000 

Now consider the same program written in C#.

Listing 1.2 A simple program written in C#
 1.  using System; 2.  using System.IO; 3.  class Employee 4.  { 5.    public Employee(string nm,DateTime hireDate) 6.    { 7.      m_name=nm; 8.      m_hireDate=hireDate; 9.    } 10.   virtual public float getSalary() 11.   { 12.     return 50; 13.   } 14.   virtual public string JobDescription() 15.   { 16.     return "Employee"; 17.   } 18.   public string Name 19.   { 20.     get 21.     { 22.       return m_name; 23.     } 24.     set 25.     { 26.       m_name=value; 27.     } 28.   } 29.   public void WriteToStream(TextWriter strm) 30.   { 31.     strm.WriteLine(this.JobDescription()); 32.     strm.Write("Name = "); 33.     strm.WriteLine(this.Name); 34.     strm.Write("Salary = "); 35.     strm.WriteLine(this.getSalary()); 36.     strm.Write("Hire date = "); 37.     strm.WriteLine(m_hireDate.ToString()); 38.   } 39.   private string m_name; 40.   private DateTime m_hireDate; 41. } 42. class Manager : Employee 43. { 44.   public Manager(String nm,DateTime hireDate, int numStockOptions) : 45.     base(nm,hireDate) 46.   { 47.     m_numStockOptions=numStockOptions; 48.   } 49.   override public float getSalary() 50.   { 51.     return 500; 52.   } 53.   override public string JobDescription() 54.   { 55.     return "Manager"; 56.   } 57.   private int m_numStockOptions; 58. } 59. 60. class HelloWorld 61. { 62.   public static void Main(String[] args) 63.   { 64.     try 65.     { 66.       if (args.Length == 2) 67.       { 68.         Employee emp=new Manager(args[0],DateTime.Now,args[1].ToInt32()); 69.         emp.WriteToStream(Console.Out); 70.       } 71.       else 72.       { 73.         Console.Error.WriteLine("Usage: HelloWorld Name #OfStockOptions"); 74.       } 75.     } 76.     catch (IOException ex) 77.     { 78.       Console.Error.WriteLine("IOException: {0}",ex.Message); 79.     } 80.     catch (FormatException ex) 81.     { 82.       Console.Error.WriteLine("FormatException: {0}",ex.Message); 83.     } 84.     catch (Exception ex) 85.     { 86.       Console.Error.WriteLine("Exception: {0}",ex.Message); 87.     } 88.   } 89. } 

At this point, it's not important that you understand every line of code in these two listings. The important point for you to grasp is how similar the two listings are. In fact, when I created these two programs, I coded the Java programming language version first. I then made less than five minutes worth of changes, and I had the C# version.

Notice that C# uses the keyword "using" to specify that the program will use unqualified names in a namespace (see Lines 1 and 2 of Listing 1.2). The Java programming language uses the import keyword for the same thing (see Lines 1 and 2 of Listing 1.1). The C# libraries contain a DateTime class to represent dates and times (see Lines 5, 37, and 40 in Listing 1.2). The Java programming language has an equivalent class called Date . Both languages support a generic mechanism to convert any object into a string representation of itself. The Java programming language supports a method called toString, and C# has a method called ToString. These differences are minor, and a Java-to-C.htm# or C#-to-Java translator could easily resolve them.

Note

As part of its Jump to .NET Strategy, Microsoft is creating both a Java-to-C.htm# and a J++-to-J# converter. See the following URL: msdn.microsoft.com/visualj/jump/default.asp.


More significant differences, which would be harder for a translator to resolve, have to do with each language's support for runtime lookup of methods with object hierarchies. This is often referred to as virtual functions and relates to the language's implementation of polymorphism. If you're not sure what I mean by this, consider Line 68 of Listing 1.2:

 Employee emp=new Manager(args[0],DateTime.Now,args[1].ToInt32()); 

Notice that we have an Employee reference, emp, that points to a Manager object. Employee is a base class of Manager , so these types are assignment compatible in this way. If I call the getSalary method through the Employee reference, am I invoking the getSalary method associated with the type of the reference ( Employee ), in which case I will see $50.00, or am I invoking the getSalary method associated with the type of the object that the reference points to ( Manager ), in which case the method will return $500.00. The latter case is called runtime binding or sometimes a virtual function and is the correct implementation of polymorphism. The former case is an example of compile-time binding and is usually not the desired behavior, although in some cases you may want your methods to behave this way. The Java programming language always uses runtime binding (virtual functions). With C#, you can choose. Notice on Line 10 of Listing 1.2 that I declared the getSalary method in the Employee class using the virtual keyword:

 virtual public float getSalary() 

In C#, this is our way of indicating that we want the compiler to generate code that binds references to this method at runtime. When we derive a Manager class from Employee , we can now choose whether we want the base-class references to call the method in the derived class. You make this choice using either the new or override keyword. In the case of our Manager class, we used the override keyword as shown on Line 49.

 override public float getSalary() 

Note

This is actually an interview question that I use quite often to see if an applicant really understands object-oriented concepts.


The Java Libraries versus the .NET Framework Libraries

The .NET libraries and the Java libraries are almost equivalent. Both the .NET libraries and the Java libraries are object-oriented libraries that contain classes that encapsulate all of the essential operating system services and building block components required to build applications. Both libraries have split the hundreds of classes that they contain into hierarchical namespaces. In the Java programming language, the main difference is that the Java libraries are designed to be cross-platform whereas the .NET Framework libraries are optimized for the Windows platform. For instance, the .NET libraries contain a set of classes in a namespace called system.runtime.interopservices that you can use to interoperate with COM components A set of classes are also in a namespace called System.EnterpriseServices that you can use to take advantage of the COM+ services. The data access classes in the System.Data namespace also have two sets of classes: system.data.OleDb to work with any database that is accessible through ADO/OLEDB and system.data.SqlClient for working with Microsoft SQL Server databases. The Java libraries eschew this kind of platform-specific functionality. You won't see any Sun.SolarisServices namespaces in the Java libraries. The Java library was designed from the ground up to be a platform-independent library. In addition, most of the APIs in the Java library (APIs are typically a group of classes in the same namespace) were designed with input from companies other than Sun Microsystems. The .NET libraries were designed for and optimized for the Windows platform. With that said, Microsoft seems to be hinting that it will port the .NET Framework to other platforms. My suspicion though is that .NET will always run best on Windows. Until Microsoft shows otherwise , you should assume that your .NET applications will run on Windows, but be easily integrated with other platforms through SOAP and Web services. If your applications themselves need to run on other platforms, you should consider using Java instead.

The Java Runtime versus the CLR

The Java runtime and the CLR could not be more different. A Java compiler compiles your Java source code into a virtual assembly language called Java bytecodes. Java bytescodes are conceptually similar to MSIL. In fact, the instruction set for Java bytecodes uses a stack-based architecture just like MSIL.

Note

If you are not sure what I mean by an instruction set or a stack-based architecture, don't worry about it. You will understand after I discuss MSIL in-depth in Chapter 3.


The Java runtime includes an interpreter called the Java Virtual Machine (Java VM) that interprets Java bytecodes and executes them. In order to support Java applications on a given platform, Sun Microsystems (or a third party) only needs to provide an implementation of the Java VM for that platform.

A .NET compiler will compile your source code into a virtual assembly languageMSIL. However, the CLR is not an interpreter like the Java runtime. When you run a .NET application, the execution engine in the CLR will compile the MSIL into native code as it runs the application. It will compile the code method by method as each method is called, replacing the MSIL code in memory with the compiled code, so that it does not have to recompile the method again during that session. This process is called JIT compilation. Microsoft calls the entire process the VES. In order to support a .NET application on a give platform, Microsoft (or a third party) only needs to provide a JIT compiler that can compile MSIL code into the native code for that platform.

Which approach is better? The CLR (.NET) approach is faster in most circumstances. You will notice a slight delay at start-up with most .NET applications as the CLR compiles MSIL code into native code. However, with most applications, you will eventually reach a steady state where most of the code that you are going to use in that session has already been compiled into native code and your application will run nearly as fast as a "regular" executable. It may run faster in some circumstances because the JIT compiler is compiling the code on the same machine where the code will run. Therefore, it can take advantage of knowing the CPU speed, amount of available, and so forth to optimize the generated code. An interpreter will never approach the speed of native code despite Sun Microsystem's attempts to prove otherwise.

Note

Some Java VMs do use JIT compilation.


It's no wonder that Microsoft boldly ported Sun Microsystem's performance benchmarking application for Java Enterprise Edition called J2EE (Java Pet Store) and showed .NET to be 28 times faster! See gotdotnet.com/team/compare/ for more information.

At the end of the day, the best conclusion I can offer is that, if you can choose your server platform, use Windows and .NET. If you cannot control the server platform and the parties who do have control do not want Windows, or if your application must support several platforms on a single source base, the Java programming language is your best bet. The reality is that both platforms are here to stay. I don't expect .NET to replace the Java programming language or vice-versa. The Java programming language and the .NET Framework will likely coexist as the two dominant development platforms for new development work for the foreseeable future. Pick one and become an expert at it, and you will be gainfully employed for a long time. I don't recommend trying to become a master of both because there is too much to learn for that to be realistic.


Team-Fly    
Top
 


. Net and COM Interoperability Handbook
The .NET and COM Interoperability Handbook (Integrated .Net)
ISBN: 013046130X
EAN: 2147483647
Year: 2002
Pages: 119
Authors: Alan Gordon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net