Home  |  FAQ  |  About  |  Contact  |  View Source   
 
SEARCH:
 
BROWSE:
    My Hood
Edit My Info
View Events
Read Tutorials
Training Modules
View Presentations
Download Tools
Scan News
Get Jobs
Message Forums
School Forums
Member Directory
   
CONTRIBUTE:
    Sign me up!
Post an Event
Submit Tutorials
Upload Tools
Link News
Post Jobs
   
   
Home >  Tutorials >  C# >  Microsoft C# versus Java, Part I
Add to MyHood
   Microsoft C# versus Java, Part I   [ printer friendly ]
Stats
  Rating: 3.77 out of 5 by 35 users
  Submitted: 11/25/01
Jared Miniman ()

 
Microsoft C# vs. Java: A Syntactical and Functional Comparison
By: Jared Miniman, Cornell University, 10-14-2001
Manager: John Nordlinger


When Microsoft sought after its next universal programming language, it surveyed the competition and realized that while the future of programming languages
is in object orientation, no language in existence truly fit this model.  C#’s purpose is to deliver a fully OOP language, pushing beyond the limitations of
Java and C++.  Throughout this summary of key expression and conceptual differences between Java and C#, it will be made clear that programming in C# saves the
developer a great deal of time not only in code writing but also in eliminating errors from that code. 


C# empowers the user with exceptional debugging abilities through the Microsoft intermediate language viewer.  This allows you to more or less see “assembly
code,” MSIL, for all programming chunks created and therefore create code that is extremely efficient for a given task. Java provides no low-level debugging
support.


Microsoft C# Java
Even the deconstruction of a simple application like “Hello World” reveals a great deal about how the .NET runtime makes code calls. Java bitcode is read into the Java Virtual Machine (JVM); no intermediate language of human recognition is created

All data is treated as objects, including primitive types (called value types in C#).  This is useful
because all objects inherit from System.Object and therefore can use a several handy functions predefined for each value type like Equals, GetHashCode, toString,
Finalize (for clean-up), etc.  Reference types are all the other objects standard to Java.  These can point to NULL, unlike the value types, which are required
to be non-null.  Converting to a reference type from a data type just takes a simple “boxing” call.  Boxed objects are created by default and require the least
amount of overhead.  Unboxed objects provide greater pre-defined functionality.


Microsoft C# Java
int foo = 309;      // Type value
object bar = foo; // Bar is boxed foo
int hash = bar.GetHashCode(); // Gets HC 
foo = new java.lang.Integer(309);
int hash = foo.hashCode();

Multiple main methods are supported within class files. 

Microsoft C# Java
using System;
class Main1 {public static void Main() {...}}
class Main2 {public static void Main() {...}}


To use Main1, call “csc Fo.cs /main:Main1”
Only one main method per class file is supported

The read-only access modifier allows a value to be determined at run-time in its
constructor, then remains immutable throughout the application.  Java only has
constant (which C# also has), but this value must be determined during compilation. 


Microsoft C# Java
… public static readonly int specialVal;
static specialType()
{  
    // Code to do calculations   
       
specialVal = someValue;
}
public static int specialVal = knownValue;

If desired, C# gives complete control over garbage collection (supports deconstructors),
but can be left to intelligently clear up memory after execution.  Java forces
use of its own garbage collection system.


Microsoft C# Java
An optional public method called suggestively Dispose or Cleanup is exposed,
which a class user should call when done using an object.  Several .NET
framework classes use such a Dispose method.  Implementation and use of
these finalization methods are not required and will be handled automatically
by a low-priority thread that scans for abandoned objects.
Java handles all garbage collection automatically and doesn’t suggest the
use of finalization methods.

The passing of objects with keyword “ref” into a function results in the object
being written to and returned in its modified form.  The “out” keyword does the
same thing but does not require pre-initialization of object(s) being passed in. 


Microsoft C# Java
// Inside main . . .
 
int red;
 
colorObject.getRed(ref int red);
 
… // Now use modified/updated value of red
// In Java, ref doesn’t exist, so
 
int red;
 
colorObject.getRed(red);
 
… // Value of red won’t change (still 0)

Instead of being bound
to a function argument list of rigidly-defined size, you can use the “params”
keyword to pass in a variable-length list of arguments, more or less passing in
an array of length to be determined at run time. 


Microsoft C# Java

public void Foo(params
items[] i) { … }
    // Treat arguments as array so don’t
   

    // worry about argument list size


No simple way of passing in a run-time determined number of arguments

Use of getter/setter
methods allows you to create new objects much more naturally.  This lets you treat
accessor methods as properties, rather than functions. 


Microsoft C# Java
Address addr = new Address();

addr.ZipCode = “55555”;

string zip = addr.ZipCode;
Address addr = new Address();
Addr.SetZipCode(“55555”);

String zip = addr.getZipCode();

Objects in C# can
be treated as arrays through the utilization of “indexers.”  The benefit to this
syntax is that you can manage many objects of the same type in a more systematic
fashion.  It lets you “box” a given number of objects into a single array-like
object with very simple syntax.


Microsoft C# Java
class foo {   
   
public object this[int index] { … }
}  // Then in main . . .
foo sample = new foo();
sample[0] =  . . .  // use getter
sample[1] =  . . .  // use getter again
     . . .      
// Then perform something on foo, which points to
// the ordered objects created
In Java, you can manually create arrays of objects of a given class, but there
is no way to do this without using inheritance, thereby creating a new type
that is a class that contains several object members of its parent class.

Interfaces are essential
because multiple inheritance isn’t supported.  The “is” keyword allows you to
test if a given type is compatible with another type during run time.  The “as”
keyword first uses the same compatibility test as “is,” but then will perform
a cast to the target type if compatibility exists.  NULL is returned if the types
are not compatible.  This is a great way to do safe casts!


Microsoft C# Java
if (myControl is ISerializable) { ... }
// returns true if myControl implements
// ISerializable.   If true, you can treat
// myControl as an ISerializable    
   
ISerializable i = myControl as ISerializable; // Will be non-null iff myControl
implements
// ISerializable
if (myControl typeof ISerializable) {...}
// Same behavior as in C#
ISerializable I = if myControl is ISerializable then perform_Cast else null

Case statements in
C# can be collapsed such that varying expression evaluations can lead to the same
output.  

Microsoft C# Java
switch (expression) {    
   
case (expressionGuess1):  
   
case (expressionGuess2):    
… } // Do the same thing for multiple values
switch (expression) {    
   
case (expressionGuess1): action1;    
   
case (expressionGuess2): action1;     
… } // Do the same thing for multiple values

The “foreach” keyword
allows you to traverse arrays and collections without having to setup the iteration
specification!  Hence, you need not define the start/end point—foreach looks at
ALL items in the array or collection.  


Microsoft C# Java
// Inside a function looking at string array foreach (string word in stringArray)
{…}
No equivalent simple keyword in Java

Goto is supported. 
This is useful in “loop-and-a-half” problems, where we can avoid reading a value
twice (which means double the software maintenance work should that statement
need to be changed).  Here is the pseudocode that would drive your actual program
snippet:

Microsoft C# Java
loop  
    read in a value
    if value == sentinel then exit
    process the value
end loop
read in a value
while value != sentinel     
    process the value    
    read in a value
end while

User-defined conversions
(explicit cast behavior) is easily programmed for each class.   Also, like in
C++, basic operators can be overloaded through user-defined implementations. 
This is extremely useful when a specific operation needs to be done to the same
object over and over again, and intuitive syntax is sought. 


Microsoft C# Java
Pound h = 139.0F;
Ounce o = (Ounce)h; // User-defined cast

// If you wish to keep cummulative grade
// reports for a student, you could do: GradeReport cumm = new GradeReport();
Foreach(GradeReport report in reportArray)      
   
{  cumm+= report
}
Must provide explicit toObject cast functions.  Again, a matter of syntactic
clarity.  Basic operators cannot be overloaded, and behavior must be placed
in functions.

Conclusion:
           
Clearly, C# carries over the programming simplicity of Java, but strides in leaps
and bounds to improve code legibility and to make class and method use much more
intuitive.  By treating all data types as objects, C# defines a true object-oriented
programming language.   Allowing the developer to make syntactical shortcuts is
a proven way to reduce maintenance and testing costs, and C# makes great advances
in language structure.  Best of all, C# allows a developer to express complex
thoughts in a natural way, not to bogged down by complicated API calls and the
paranoia over improper garbage collection.


Return to Browsing Tutorials

Email this Tutorial to a Friend

Rate this Content:  
low quality  1 2 3 4 5  high quality

Reader's Comments Post a Comment
 
This content isn't really a tutorial, it should be submitted as your own work in the articles section.
-- Benjamin Collins, November 26, 2001
 
hehe....not to be overly critical, i think this was really good! It just needs to be submitted somewhere else.
-- Benjamin Collins, November 26, 2001
 
Also, it really isn't "Microsoft C#". C# is a Microsoft invention, but it isn't proprietary.
-- Adam Azarchs, November 27, 2001
 
More comparison information can be found at
from the slashdot article
.
-- Nick Terrible, November 27, 2001
 
Good overview, but I agree it's more of an article. Also, the format is a bit tough to read.
-- D P, November 27, 2001
 
try doing microsoft's J# against Sun's Java.
-- Michael Elfassy, November 27, 2001
 
I think this was a great article, a much shorter version of "A Programmers Introduction to C#" (APress).

Much of the same ideas presented there, but I would much rather spend the five minutes reading this article than that book (grin). I especially liked the code samples.
-- Greg McMurray, November 28, 2001
 
The article nicely covers areas where C#'s stands out compared to Java, but how about its shortcomings. Could someone also post a similar comparison about the disadvantage of using C# compared to using Java so that we can get a comprehensive look. Thanks!
-- Zhen Hao (Howard) Zhou, December 01, 2001
 
I expected a little more, but what was there was helpful. Not sure how it fits the tutorial label though.
-- John Allen, December 06, 2001
 
Interesting.
-- Chris Roberts, December 06, 2001
 
Pretty neat comparision. Certainly not a tutorial. It will be very helpful for a starter to compare C# and Java. Good job. I am waiting for the next part.
-- Krishnan Subramanian, December 07, 2001
 
Are there things that you can do in Java that you cannot do in C#?0
-- Jim Jones, December 07, 2001
 
While there are a few good points here, most of the differences listed point out are purely syntax. This could easily be expanded to include things such as parameter marshalling (ref and out), delegators, and reflection. Syntax can help in maintaining code, but there are far more features related to COM and distributed applications that put c# in it's own category.
-- Ryan Fosnaugh, December 07, 2001
 
good list
-- Siyan Li, January 12, 2002
 
as other ppl have noted, this is much more of an article than a tutorial. thanks.
-- Alice Chen, January 16, 2002
 
I think the tutorial is awefully biased...
-- Ricardo Siu, January 17, 2002
 
http://www.csharp-station.com/
-- Arturo Ordaz, January 17, 2002
 
Good article, but biased in that it doesn't even state one advantage of Java. Should be retitled "New Features in C#" or something like that.
-- Wayne Kao, January 17, 2002
 
Seems a bit bias to C#. Java is easy to use too.
-- William Chu, January 18, 2002
 
A few corrections: you forgot to implement "get{...}" for your readonly property, and the reason that Java does not support multiple main/Main methods is simple: you can only have one public class for java source file. This makes for better development, especially amoung teams. In addition, your public class name has to match the filename of the file. These are all development issues, not language issues. In some ways, it's nice that Microsoft handles source files like in C++, VB, etc., but it also makes searching for classes more difficult when the filename reflects nothing of the class(es) contained within. A nice IDE helps with this, but sometimes it's just nice to find files and know where to look without having to fire-up a resource-hogging IDE (which they all are, not just VS.NET).
-- Heath Stewart, January 22, 2002
 
Although it is a little hard to read, it is a good overview. It's shorter than "A Programmers Introduction to C#" (APress) which is also great.
-- Abin Shahab, January 24, 2002
 
Although it is a little hard to read, it is a good overview. It's shorter than "A Programmers Introduction to C#" (APress) which is also great.
-- Abin Shahab, January 24, 2002
 
tutorial? i agree it does seem a bit biased
-- Ben Ratzlaff, January 25, 2002
 
This tutorial was very helpful for me in understanding the basic features and differences between C# and other OO such as Java. Yet, on the level of a tutorial, I feel there could have been more :)
-- Ben VanEvery, January 27, 2002
 
I think this article is way too biased in favor of C#, to the point of containing inaccuracies and "forced" comparisons. For example, take the case arguing for C#'s goto statement:
loop
read in a value
if value == sentinel then exit
process the value
end loop
You can do the same thing in Java, using the break keyword! No need to do "loop-and-a-half" acrobatics.

And is this snippet (taken from the article) Java code?
if (myControl typeof ISerializable) {...}
// Same behavior as in C#
ISerializable I = if myControl is ISerializable then perform_Cast else null
-- Adrian Solis, January 28, 2002
 
A good article (not a tutorial). Maybe the author is slightly biased towards C#.
-- A Vallur, January 29, 2002
 
I have to agree, nice article (not tutorial) =) But still very comprehensive and interesting. I liked that it was rather compact.
-- Jun Nozaki, January 29, 2002
 
Good overview of the language.
-- Tanaka Murinata, February 01, 2002
 
Not bad, but when you submit a tutorial it should be a bit more objective.

Also, the java for a case statement can also be written like this:


switch(variable)
{
case '1':
case '2': Some code;break;
case '3'; Other code; break;

}

This will allow 1 and 2 to do the same thing.
-- Demetrios Vasiadis, February 04, 2002
 
A biased article, but still interesting.
-- Brian Simoneau, February 25, 2002
 
Really good information, but a little over-editorialized.
-- Naseer Siddique, March 03, 2002
 
I'd have to same I am impressed with some of these nice features of C#.
-- Jared Betteridge, March 27, 2002
 
This article will help me get started in my quest to learn C#.
-- Laurent Vauthrin, April 16, 2002
 
good tutorial. well researched, and so on.
-- Aaron Brethorst, October 21, 2002
 
If you were trying to say that C# is better than Java with these examples, you failed pretty miserably. They illustrate a clear lack of understanding of Java and of developing (not programming) in general.
-- Eric Savage, May 07, 2003
 
Copyright © 2001 DevHood® All Rights Reserved