Thursday, February 10, 2011

Main Method

The entry point of both C# and Java programs is a main method. There is a superficial difference in that the Main method in C# begins with an uppercase "M" (as do all .NET Framework method names, by convention) while the main method in Java begins with a lowercase "m" (as do all Java method names, by convention). The declaration for the main method is otherwise the same in both cases except for the fact that parameter to the Main() method in C# can have a void parameter.
C# Code
using System;

class A{

public static void Main(String[] args){

Console.WriteLine("Hello World");

}
}

Java Code
class B{

public static void main(String[] args){

System.out.println("Hello World");

}
}
It is typically recommended that one creates a main method for each class in an application to test the functionality of that class besides whatever main method actually drives the application. For instance it is possible to have two classes, A and B, which both contain main methods. In Java, since a class is the unit of compilation then all one has to do is invoke the specific class one wants run via the command line to run its main method. In C# one can get the same effect by compiling the application with the /main switch to specify which main should be used as the starting point of the application when the executable is created. Using test mains in combination with conditional compilation via preprocessor directives is a powerful testing technique.

Java Example
C:\CodeSample> javac A.java B.java

C:\CodeSample> java A
Hello World from class A

C:\CodeSample> java B
Hello World from class B

C# Example
C:\CodeSample> csc /main:A /out:example.exe A.cs B.cs

C:\CodeSample> example.exe
Hello World from class A

C:\CodeSample> csc /main:B /out:example.exe A.cs B.cs

C:\CodeSample> example.exe
Hello World from class B
So in Java's favor, one doesn't have to recompile to change which main is used by the application while a recompile is needed in a C# application. However, On the other hand, Java doesn't support conditional compilation, so the main method will be part of even your released classes.

No comments:

Post a Comment