Java vs C#

Java C#
j2ee .NET Platform Architecture
Java code cycle .NET code cycle
Java Virtual Maschine (JVM) Common Language Runtime (CLR)
Java Runtime Environment (JRE) .NET Framework
Java bytecode Microsoft Intermediate Language (MSIL), Common Intermediate Language (CIL) lati
Java Foundation Classes (JFC) .NET Framework Class Library (FCL)
Java 2 Software Development Kit (J2SDK), Java 2 Standard Edition (J2SE) .NET
Java 2 Enterprise Edition (J2EE) .NET
Java Web Services .NET My Services
Java 2 Micro Edition (J2ME) .NET Compact Framework
Swing .NET Forms
-
Common Type System (CTS), Common Language System (CLS)
Code Access Security (CAS)
Java Archive (JAR) Assembly (ocx, dll, exe), Global Assembly Cache (GAC)
C# Language
javac -cp alibrary.jar MyClass.java
java MyClass
javap
csc /reference:alibrary.dll MyClass.cs
MyClass
cordbg
or dbgclr
super
import
package
final
base
using
namespace
const, sealed
static imports (Java 1.5)
import static java.lang.System.out;
class SayHello {
  public static void main(String[] args) {
    out.println("Hello "+"World!");
  }
}
namespaces
using System;  // or MySystem = System; alias
class SayHello {
  public static void Main() {
    Console.WriteLine("Hello "+"World!");
  }
}
Object.equals()
Object.finalize()
Object.toString()
Object.Equals()
Object.Finalize()
Object.ToString()
//This is a single line comment. //This is a single line comment.
/* This is a
 * multiline comment.
 */
/* This is a
 * multiline comment.
 */
/**
 * This is a javadoc (HTML) comment.
 * @param
 * @return
 * @see
 * @throws
 * @author
 * @version
 * @since
 * @deprecated
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
javadoc
///
/// This is XML Documentation comment.
/// <param>, <paramref>
/// <returns>
/// <see>, <seealso>
/// <exception>
///
///
///
///
/// <c>
/// <code>
/// <example>
/// <include>
/// <list>
/// <para>
/// <permission>
/// <remarks>
/// <summary>
/// <value>
///
csc /doc:MyComments.xml
Language Fundamentals
public static void main(String[] args) {
   new MyApp();
}
static void Main(string[] args) {
   Application.Run(new MyApp());
}
static void Main() { ... }
static int Main() { ... return (1); }
static int Main(string[] args) { ... return (0)};
System.out.println();
System.in.read();
System.Console.WriteLine();
System.Console.Read();
import static java.lang.System.out;
class SayHello {
  public static void main(String[] args) {
   
for (String arg : args)                // Java 1.5
       out.printf("Hello %s!%n" + arg);
  }
}
using System;
class SayHello {
  public static void Main() {
    foreach (string arg in args)
       Console.WriteLine("Hello {0}", arg);
  }
}
Data Types
String string
boolean, Boolean bool, Boolean
byte, Byte
byte, Byte sbyte, SByte
char, Char char, Char
decimal, Decimal
double, Double double, Double
float, Float float, Float
int, Integer int, Int32
long, Long long, Int64
short, Short short, Int16
uint, UInt32
ulong, UInt64
ushort, UInt16
Access Modifiers
internal (access limited to local project)
private private
protected protected
protected internal (access limited to class or local project)
package
public public
Operators and Operator precedence
>>>
operator precedence
Preprocessor Directives
Preprocessor Directive Definition
#define Defines a symbol
#undef Undefines a symbol
#if Begins a conditional directive
#elif Creates a compound conditional directive
#else Creates a compound conditional directive
#endif Specifies the end of a conditional directive
#error Generates an error at a specific place in your code
#warning Generates a warning at a specific place in your code
#region Specifies a block of code for outlining
#endregion Specifies the end of an outlining region
#line Modifies the line number shown for errors and warnings
                
Data Structures
String()
String(byte[] bytes)
String(byte[] bytes, int offset, int length)
String(char[] value)
String(char[] value, int offset, int count)
String(String s)
String( char Ch, int Count)
String( char[] CharArray)
String( char[], int Start, int Count)
String.Copy()  // instead of String(String s)
String.length() String.Length()
String.charAt(int index) String.[int index]  // Indexer
String.concat(String str) String.Concat(String str)
String.compareTo (String str) String.Compare (String strA, String strB, bool ignoreCase)
String.split(String regex) String.Split(char[] sep)
String.Join()
String.toLower() String.ToLower()
String.toUpper() String.ToUpper()
String.trim() String.Trim()
String stringLiteral = "C:\\Java programs" String stringLiteral = "C:\\C# programs";
String verbatimStringLiteral = @"C:\C# programs";
StringBuffer (thread-safe, mutable sequence of characters)
StringBuilder (mutable sequence of characters)
StringBuilder
StringBuffer.capacity() StringBuffer.Capacity()
StringBuffer.charAt(int index) StringBuffer.[int index]  // Indexer
StringBuffer.length() StringBuffer.Length()
StringBuffer.append(String str) StringBuffer.Append(String str)
StringBuffer.insert(int offset, String str) StringBuffer.Insert(int offset, String str)
StringBuffer.delete(int start, int end) StringBuffer.Remove(int startIndex, int length)
StringBuffer.replace(int start, int end, String str) StringBuffer.Replace(String substring, String Replacement)
StringBuffer.toString() StringBuffer.ToString()
System.util.regex  // Java 1.5 System.Text.RegularExpressions
Pattern            // Java 1.5
Pattern pattern = Pattern.compile(p);   // p is a pattern e.g. "X..."
Regex
Matcher            // Java 1.5
Matcher matcher = pattern.matcher(string);
if (matcher.matches()) { ... }   // matches whole string
while (matcher.find()) { ... }   // matches part of the string   
MatchCollection
Pattern.matches(String pattern, String string);
boolean b = Pattern.matches("a*b","aaaaab");   
MatchCollection patternMatches = Regex.Matches("aaaaab","a*b",RegexOptions.IgnoreCase);
String.matches(String pattern);
Data flow
if (condition) { ...
} else if (condition) { ...
} else { ...
}
if (condition) { ...
} else if (condition) { ...
} else { ...
}
int i = 1;
switch (i) {
  case 0: System.out.println("System.in"); break;
  case 1: System.out.println("System.out"); break;
  case 2: System.out.println("System.err"); break;
  case 3:
  case 4:
  case 5: System.out.println("To be defined"); break;
  default: System.out.println("Error"); break;
}
int i = 1;
switch (i) {
  case 0: System.out.println("System.in"); break;
  case 1: System.out.println("System.out"); break;
  case 2: System.out.println("System.err"); break;
  case 3: goto 4;
  case 4: goto 5;
  case 5: System.out.println("To be defined"); break;
  default: System.out.println("Error"); break;
}
String testString = "Test";
switch (testString) {
   case "Hello": System.Console.WriteLine("The string says Hello.");
                 break;
   case "Test": System.Console.WriteLine("The string says Test"); break;
   default: System.Console.WriteLine("The string is unknown"); break;
}
switch parameters can be of type: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or enum
boolean noMoreRecords = false;
while (!noMoreRecords) {
  noMoreRecords = readRecord();
}
bool noMoreRecords = false;
while (!noMoreRecords) {
  noMoreRecords = ReadRecord();
}
boolean noMoreRecords;
do {
  noMoreRecords = readRecord();
} while(!noMoreRecords);
bool noMoreRecords;
do {
  noMoreRecords = ReadRecord();
} while(!noMoreRecords);
for (int x = 0; x < 31; x++) {
  System.out.printf("January %d", (x + 1));
}
for (int x = 0; x < 31; x++) {
  System.Console.WriteLine("January {0}", x + 1);
}
for (String arg : args)                // Java 1.5
  System.out.printf("Hello %s!%n", arg);
foreach (string arg in args)
   System.Console.WriteLine("Hello {0}", arg);
Arrays and Collections
Array.get(Object array, int index) Array.[int index]  // Indexer
array.length() Array.Length()
Array.Rank()
Array.getLength(Object array) Array.GetLength(int dimension)
Arrays.binarySearch(Object[] array, Object value) Array.BinarySearch(Array array, Object value)
Array.GetLowerBound()
Array.GetUpperBound()
Arrays.sort(Object[] array) Array.Sort(Array array)
varargs params
Object-oriented Programming - Encapsulation, Inheritance and polymorphism
public class Manager extends Employee {

  public Manager (String name, float salary, String dept) {
    super(name, salary);
    ...
  } 
 ...
}
public class Manager : Employee {

  public Manager (String name, float salary, String dept) :
    base (name, salary)
{
    ...
  } 

 ...
}
class A {
  public void foo() {    
   ...                    
  }
}
class B extends A {
  public void foo() {   // implementation of an overriden method
   ...
   super.foo();         // call base class method
  }
}

Java uses the type (or class) of the object, not the type of the reference, to select  which
overriden method to invoke. All Java methods are essentially considered to be virtual. No equivalent to new keyword.
class A {
  public virtual void Foo() {     // this method has differerent 
   ...                            // implementations in derived classes
  }
  public virtual void Bar() {
   ...
  }
}
class B : A {
  public override void Foo() {    // implementation of an overriden    

   ...
                           // method
   base.Foo();                    // call base class method
  }
  public new void Bar() {         // hide parent's class Bar() method
   ...                            // prevents polymorphism, no        
 
}                               // override
}
final void foo() { ... } sealed void foo() { ... }
Java supports 4 kinds of inner or nested classes:
  • top level nested classes (static classes declared inside another class)
  • member classes (classes declared inside another class)
  • local classes (classes declared inside the body of a method)
  • anonymous classes (used and declared in the same statement)
C# supports only 1 kind of inner or nested classes:
  • top level nested (or static) inner classes
public class Outer {
  public int x ;
  public int y ;
  public class Inner {
    public int x ;
    public int z ;
    public void InnerFoo() {
      // Do something here.
    }
  }
  public void OuterFoo() {
    // Do something here.
  }
}
// From code within Outer
Inner i = new Inner() ;    
// From all other locations in code
Outer.Inner oi = new Outer.Inner() ;
interface IPlayer {
  void plays();
}
class TennisPlayer extends Professional implements IPlayer {
  void plays() {
  ...
  }
}
interface IPlayer {
  void Plays();
}
// base class must come first
class TennisPlayer : Professional, IPlayer { 
  virtual void Plays() {
  ...
  }                                   
}
if (a instanceof A) { ... if (a is A) { ...
- A a = new B();
B b = a as B;  // test whether object a is of a particular type 
               //
and cast it to that type
-
Explicit interface implementation and implementation hiding
interface IA {
   void Foo();
}
interface IB {
   void Foo();
}
class C : IA, IB {
   void Foo() { ... }       // use either a common method for all
                            // interfaces
   void IA.Foo() { ... }    // or explicit implementation
   void IB.Foo() { ... }
}
Other features
class Circle {
  private double radius {
 
  public void setRadius (double radius) {
     if (radius > 0.0)  
       this.radius = radius;
  }
  public double getRadius () {
       return radius;
  }
}

public class CircleTester {
   public static void main() {
     Circle c = new Circle();
     c.setRadius(20);
     System.out.println("Radius = " + c.getRadius());
   }
}
Properties
class Circle {
  public double Radius {
    set {
       if (value > 0.0)
         Radius = value;
    }
    get {
       return Radius;
    }
  }
}

public class CircleTester {
   public static void Main() {
     Circle c = new Circle();
     c.Radius = 20;
     Console.WriteLine("Radius = {0}", c.Radius);
   }
public readonly double Radius; // can only be initialized in costructor
// cannot be modified from outside constructor
Enumeration


Creator: John N. Kostaras, Last modified: 17/02/2008
Source: "C# for Java Programmers", by Bagnall et. al., Syngress, 2002.
1