Java (J2SE 5.0) and C# Comparison
Java (J2SE 5.0) and C# Comparison
0) and C# Comparison
This is a quick reference guide to highlight some key syntactical differences between Java and C#.
This is by no means a complete overview of either language. Hope you find this useful!
// See if an argument was passed from the command line // See if an argument was passed from the command line
if (args.length == 1) if (args.Length == 1)
name = args[0]; name = args[0];
Conversions Convertions
1
readonly int MAX_HEIGHT = 9;
Java Enumerations C#
enum Action {Start, Stop, Rewind, Forward}; enum Action {Start, Stop, Rewind, Forward};
// Special type of class enum Status {Flunk = 50, Pass = 70, Excel = 90};
enum Status {
Flunk(50), Pass(70), Excel(90); No equivalent.
private final int value;
Status(int value) { this.value = value; }
public int value() { return value; }
};
Arithmetic Arithmetic
+ - * / + - * /
% (mod) % (mod)
/ (integer division if both operands are ints) / (integer division if both operands are ints)
Math.Pow(x, y) Math.Pow(x, y)
Assignment Assignment
= += -= *= /= %= &= |= ^= <<= >>= >>>= = += -= *= /= %= &= |= ^= <<= >>= ++ --
++ --
Bitwise
Bitwise & | ^ ~ << >>
& | ^ ~ << >> >>>
Logical
Logical && || & | ^ !
&& || & | ^ !
Note: && and || perform short-circuit logical evaluations
Note: && and || perform short-circuit logical evaluations
String Concatenation
String Concatenation +
+
Java Choices C#
greeting = age < 20 ? "What's up?" : "Hello"; greeting = age < 20 ? "What's up?" : "Hello";
if (x < y) if (x < y)
System.out.println("greater"); Console.WriteLine("greater");
if (x != 100) { if (x != 100) {
x *= 5; x *= 5;
y *= 2; y *= 2;
} }
else else
z *= 6; z *= 6;
2
case 2: y++; break;
case 3: z++; break; case "blue": b++; break;
default: other++; case "green": g++; break;
} default: other++; break; // break necessary on
default
}
Java Loops C#
while (i < 10) while (i < 10)
i++; i++;
do do
i++; i++;
while (i < 10); while (i < 10);
// for loop can be used to iterate through any Collection // foreach can be used to iterate through any collection
import java.util.ArrayList; using System.Collections;
ArrayList<Object> list = new ArrayList<Object>(); ArrayList list = new ArrayList();
list.add(10); // boxing converts to instance of Integer list.Add(10);
list.add("Bisons"); list.Add("Bisons");
list.add(2.3); // boxing converts to instance of Double list.Add(2.3);
// Return single value // Return no value // Return single value // Return no value
int Add(int x, int y) { void PrintSum(int x, int y) { int Add(int x, int y) { void PrintSum(int x, int y) {
return x + y; System.out.println(x + y); return x + y; Console.WriteLine(x + y);
} } } }
int sum = Add(2, 3); PrintSum(2, 3); int sum = Add(2, 3); PrintSum(2, 3);
// Primitive types and references are always passed by value // Pass by value (default), in/out-reference (ref), and
void TestFunc(int x, Point p) { out-reference (out)
x++; void TestFunc(int x, ref int y, out int z, Point p1, ref Point p2)
p.x++; // Modifying property of the object {
p = null; // Remove local reference to object x++; y++; z = 5;
} p1.x++; // Modifying property of the object
p1 = null; // Remove local reference to object
class Point { p2 = null; // Free the object
}
3
class Point {
public int x, y; }
}
class Point {
Point p = new Point(); public int x, y;
p.x = 2; }
int a = 1;
TestFunc(a, p); Point p1 = new Point();
System.out.println(a + " " + p.x + " " + (p == null) ); // 1 3 Point p2 = new Point();
false p1.x = 2;
int a = 1, b = 1, c; // Output param doesn't need initializing
// Accept variable number of arguments TestFunc(a, ref b, out c, p1, ref p2);
int Sum(int ... nums) { Console.WriteLine("{0} {1} {2} {3} {4}",
int sum = 0; a, b, c, p1.x, p2 == null); // 1 2 5 3 True
for (int i : nums)
sum += i; // Accept variable number of arguments
return sum; int Sum(params int[] nums) {
} int sum = 0;
foreach (int i in nums)
int total = Sum(4, 3, 2, 1); // returns 10 sum += i;
return sum;
}
try { try {
y = 0; y = 0;
x = 10 / y; x = 10 / y;
} catch (Exception ex) { } catch (Exception ex) { // Variable "ex" is optional
System.out.println(ex.getMessage()); Console.WriteLine(ex.Message);
} finally { } finally {
4
} finally { } finally {
// Code that always gets executed // Code that always gets executed
} }
Java Namespaces C#
package harding.compsci.graphics; namespace Harding.Compsci.Graphics {
...
}
or
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}
import harding.compsci.graphics.Rectangle; // Import single
class // Import all class. Can't import single class.
using Harding.Compsci.Graphics;
import harding.compsci.graphics.*; // Import all classes
Java Classes / Interfaces C#
Accessibility keywords Accessibility keywords
public public
private private
protected internal
static protected
protected internal
static
// Inheritance // Inheritance
class FootballGame extends Competition { class FootballGame : Competition {
... ...
} }
~SuperHero() {
5
~SuperHero() {
// No destructors, just override the finalize method
// Destructor code to free unmanaged resources.
protected void finalize() throws Throwable {
// Implicitly creates a Finalize method.
super.finalize(); // Always call parent's finalizer
}
}
}
}
Java Objects C#
SuperHero hero = new SuperHero(); SuperHero hero = new SuperHero();
SuperHero hero2 = hero; // Both refer to same object SuperHero hero2 = hero; // Both refer to same object
hero2.setName("WormWoman"); hero2.Name = "WormWoman";
System.out.println(hero.getName()); // Prints WormWoman Console.WriteLine(hero.Name); // Prints WormWoman
hero = null; // Free the object hero = null ; // Free the object
stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints "Bob"
Console.WriteLine(stu2.name); // Prints "Sue"
Java Console I/O C#
6
java.io.DataInput in = new Console.Write("What's your name? ");
java.io.DataInputStream(System.in); string name = Console.ReadLine();
System.out.print("What is your name? "); Console.Write("How old are you? ");
String name = in.readLine(); int age = Convert.ToInt32(Console.ReadLine());
System.out.print("How old are you? "); Console.WriteLine("{0} is {1} years old.", name, age);
int age = Integer.parseInt(in.readLine()); // or
System.out.println(name + " is " + age + " years old."); Console.WriteLine(name + " is " + age + " years old.");