Comparison of C# with Java: A Developer Perspective


The latest emerging technology from Microsoft is the .NET platform. The .NET is a language and operating system (on Windows as of now) independent platform pretty similar to Java. The language independency enables us to create an object or a class in one language (gr. VB.net) & use the object, inherit the object & use it in another .Net-enabled language (e.g. C#). It's in fact a great achievement to remove the barriers of programming languages. 

The Java Virtual Machine (JVM) is the firmware, which interprets the byte-code into system& platform dependent code. The Common Language Runtime or CLR could be considered as the equivalent of JVM in the .net platform. . Net complier compiles the .net compatible language code into MSIL (Microsoft Intermediate Language), which is something equivalent to the byte code. These virtual machines(CLR/JVM) are activated as soon as any program is run & they take care of loading the classes(byte code or MSIL) & Garbage Collection. At the time of execution, JIT (Just in-time compiler or jitter) compiles the MSIL code to platform (OS & hardware) dependent executable code. In the case of JVM, byte code is being interpreted at runtime, where as in the case of CLR the JIT or jitter converts the MSIL into exe for better performance. 

Java was a refined version of C, C++ with the removal of pointers, multiple-inheritance & operator overloading with multiple-platform support. Java was able to achieve, "Write once Run every where" magically. But the .net framework has gone one more step further of giving the liberty to the programmer to choose the programming language of his/her choice. As of date there are 20 languages supporting the .net framework. The new language C# pronounced as CSharp could be considered as a refined version of Java. C# inherits it's syntactical features from C & C++ & resembles java in being 100% object-oriented, removal of pointers & multiple-inheritance. Unlike java, C# allows the programmer to over-load operators. But, to ease the life of Win32 & VC++ programmers, the feature of "UnManaged Code" has been introduced into CSharp/.net Frame work. With that, the users can use the pointers & non-.net compatible code. But for the most part C# is a refined version of Java. Both Java & C#, have Object class as their root class & support only single inheritance. Multiple inheritance is supported selectively through interfaces in both Java & C#. Java allows the usage of native(C & C++) code, which is referred to as un-managed code in .net terminology through the use of JNI or Java native Interface, where .net achieves the same by the usage of un-managed code. Both C# & Java use the Reflection classes to query the Object references or jars/assemblies at runtime & get the types, manifest info, etc.. 

In C#, the data types have been categorized logically into the following types, based on their access mechanisms. 

  1. Refrence Type,
  2. Value Type, &
  3. Pointers. 

Reference types represent the data, which actually is initialized & allocated memory on the heap. All the variable instances on this type would actually reference a single memory location. These memory (on heap) types of (managed) objects needs to be cleared by the Garbage Collector, once they go out of scope & the heap if filled. The data types in C#, which fall under this category are:

  1. Class,
  2. Interface, &
  3. Delegate.

Value types are actually initialized & allocated memory on the Stack. Each variable of this type would have it's own copy of the variable. The memory on the top of the stack is cleared as soon as the (local) variable goes out of scope. The data types, which fall under this category are:

  1. Primitive data types
    (byte, sbyte, short, ushort, int, uint,long, ulong, float, ufloat, double, udouble, char,&boolean)
  2. Structures &
  3. Enumerations.

Pointers fall under the un-managed category of C# code, which is actually not much memory safe. The pointers (as in C/C++), represent the memory address of other variables. Garbage Collector of the .net runtime does not manage the memory of such unsafe objects. 

C# introduces a couple of more data types (from C/C++).Unlike Java, C# supports data types like delegates (function pointers), Structures, & Enumerations. But in C#, these data types all derive from their base classes, rather than being a primitive data type. System.Object, is the super class of all the classes in C#, which is similar to Java. 

DataType Java CSharp
Structures Not supported Represents value data type with key word struct
Enumeration Not supported Represents value data type with key word enum
Delegates Not supported Represents reference data type with key word delegate(function pointer)
Class Represents a template or reference data type with key word class. Represents reference data type with key word class.
Interface Represents reference data type with keyword interface. Represents value data type with key word interface.
Pointers Not supported Supported only in the un-managed code & represents the memory location of other variables.

As far as the object-oriented nature is concerned, C# resembles java in all of it's aspects. But, as we saw above C# provides the liberty of writing un-managed code to the traditional Win32 programmers. Interface-based programming & classes are same in both Java & C#, where as Atrributes are a new feature in C#. Attributes enable the CLR, to identify a function or a block of code as a thread, web method, etc. There are lots of pre-defined attributes in C#. The user-defined or custom attributes are also possible by extending the System.Attribute class. For Ex.

[WebMethod]- marks a particular function/method as a Web Method in a Web Service.

[Serializable] - marks a particular class to be qualified for serialization. (bytes/XML) 

The exception handling mechanism in C# is exactly same as in Java. The try, catch & finally blocks are similar in both of those languages. The actual code is placed inside the try block, where as the code, which needs to re-initialize the system or handle the exception is placed in the catch block & finally contains the code, which is supposed to be executed irrespective of the occurrence of the exception. User-defined  exceptions could also be built by inheriting the System.Exception class & providing custom messages. 

String manipulation is C# exactly the same as in Java. Instead of String Buffer, the System.StringBuilder is being used to make more faster string operations. Even in C#, the System.String class is sealed (non-inheritable) & produces immutable strings, which the runtime (CLR or JVM), makes a pool of objects. 

The table below lists the keywords in Java & their corresponding C# counterparts.

Java C# Description
Public,private,protected Public,private,protected Access descriptors
Friendly internal Provides access within the assembly or the package(injava)
Package namespace A programmatic grouping of the classes & interfaces.
Class class A basic unit of  OOPS.(User Defined Data Type)
Interface interface A collection of abstract methods.
Implements
:
Key word, to be used by the classes to provide an implementation for the interface(s).
Extends :
Key word for inheriting an existing class/interface.
Final sealed Non-inheritable /immutable classes.
static static Keyword for representing "static" variables, which are loaded into CLR as soon as the class is loaded & is shared by all the instanced of the class.
Synchronized Lock Obtains a lock for a method/ block of code.
Abstract Abstract Non instantiable class, which is meant only for being inherited by other classes.
This This Reference to the same class
Super Base Reference to the parent/base class.
 

Apart from the above mentioned operators, there are some new features & functionalities in C#, which are not present in Java. 

1. "is" operator

The "is" operator checks whether a particular object is an instnce of a given class or implements a given interface, & returns true or false.

Eg:

String s1 = "myString";
If(s1
is string)
{
//do something
}

2. "as" operator 

The "as" operator , converts one reference  type into another type at runtime. Null is returned, if the other reference type is not supported.

Eg

String s1 [] = {"myString"};
String s2 = s1 [0]
as string 

Boxing & UnBoxing is another feature of C#, which is not present in Java. Boxing refers to the conversion of a value type to a reference type.

Eg:

int i 1 = 10;
object o = i1;

UnBoxing refers to the conversion of a reference type to a value type.
                     
object o = 10;
int i1 = (int) o;

Conclusively, let's see a simple class in both C# & Java, which's going to add two numbers. 

package mypackage; 

/*
* This class is a general utility to add two numbers or subtract the same.
*/
public class Calc
{
private int a;
private int b;
/*
* Initializes & constructs an object of Class class
*@param i1 First of the numbers to be added
*@param i2 Second of the Numbers to be added.
*/ 
Calc (int i1, int i2)
            {
                        a = i1;
                        b = i2;
            }        
/*
*Adds Two Numbers.
*/
public int add()
            {
                        return a + b;
            }
/*
* Subtracts two numbers.
*/
public int subtract()
            {
                        return a-b;
            }

Here is the code sample for C# to achieve the same task. 

namespace registry
{
/// <summary>
/// This class acts as a utility for adding two numbers or subtracting the same.
/// </summary>
public class Calc
{
private int a;
private int b;
///<summary>
///The constructor instantiates the object of type Calc with appropriate
///variable initializations.
///<param name = "i1">First number to be added </param>
///<param name = "i2"> Second number to be added or
///subtracted.</param>
public Calc1(int i1, int i2)
{
a = i1;
b = i2;
}
///<summary>Adds two Numbers </summary>
public int add()
{
return a + b;
}
///<summary>Subtracts two numbers.</summary>
public int subtract()
{
return a-b;
}
}
}

As we see above, the code looks almost the same except for the extra braces for the name space in C#. Another one feature where they differ in the way the documentation is generated. The summary tags of C# are used for the generation of documentation in the form of XML, which could be transformed into HTML or any other markup languages with the help of XSLT. In the case of java the javadoc style comments are used to generate the HTML documentation by running the javadoc command from the command prompt. 

However when it comes to the case of advanced programming like Remote Method Invocation (Java) or Remoting (C#) & Web UI development (ASP.net or JSP) there would be major syntactical, architectural, & structural differences. 

Thus C# could be considered as an enhanced version of C, C++& Java with a large built-in library base & a rich set of built-in features which would let the developer achieve the tasks more efficiently.

Up Next
    Ebook Download
    View all
    Learn
    View all