0% found this document useful (0 votes)
36 views

Java (J2SE 5.0) and C# Comparison

This document provides a quick reference to compare some key syntactical differences between Java and C#. It highlights differences in program structure, comments, data types, constants, enumerations, operators, choices, and more. The summary provides essential information about the purpose and content of the document in a concise manner.

Uploaded by

sam1_ra9059
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Java (J2SE 5.0) and C# Comparison

This document provides a quick reference to compare some key syntactical differences between Java and C#. It highlights differences in program structure, comments, data types, constants, enumerations, operators, choices, and more. The summary provides essential information about the purpose and content of the document in a concise manner.

Uploaded by

sam1_ra9059
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Java (J2SE 5.

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!

Java Program Structure C#


using System;
package hello;
namespace Hello {
public class HelloWorld { public class HelloWorld {
public static void main(String[] args) { public static void Main(string[] args) {
String name = "Java"; string name = "C#";

// 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];

System.out.println("Hello, " + name + "!"); Console.WriteLine("Hello, " + name + "!");


} }
} }
}
Java Comments C#
// Single line
// Single line
/* Multiple
/* Multiple
line */
line */
/// XML comments on a single line
/** Javadoc documentation comments */
/** XML comments on multiple lines */
Java Data Types C#
Primitive Types Value Types
boolean bool
byte byte, sbyte
char char
short, int, long short, ushort, int, uint, long, ulong
float, double float, double, decimal
structures, enumerations

Reference Types Reference Types


Object (superclass of all other classes) object (superclass of all other classes)
String string
arrays, classes, interfaces arrays, classes, interfaces, delegates

Conversions Convertions

// int to String // int to string


int x = 123; int x = 123;
String y = Integer.toString(x); // y is "123" String y = x.ToString(); // y is "123"

// String to int // string to int


y = "456"; y = "456";
x = Integer.parseInt(y); // x is 456 x = int.Parse(y); // or x = Convert.ToInt32(y);

// double to int // double to int


double z = 3.5; double z = 3.5;
x = (int) z; // x is 3 (truncates decimal) x = (int) z; // x is 3 (truncates decimal)
Java Constants C#
// May be initialized in a constructor const double PI = 3.14;
final double PI = 3.14;
// Can be set to a const or a variable. May be initialized in a
constructor.
readonly int MAX_HEIGHT = 9;

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; }
};

Action a = Action.Stop; Action a = Action.Stop;


if (a != Action.Start) if (a != Action.Start)
System.out.println(a); // Prints "Stop" Console.WriteLine(a); // Prints "Stop"

Status s = Status.Pass; Status s = Status.Pass;


System.out.println(s.value()); // Prints "70" Console.WriteLine((int) s); // Prints "70"
Java Operators C#
Comparison Comparison
== < > <= >= != == < > <= >= !=

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;

int selection = 2; string color = "red";


switch (selection) { // Must be byte, short, int, char, or switch (color) { // Can be any predefined
enum type
case 1: x++; // Falls through to next case if no break case "red": r++; break; // break is mandatory; no
case 2: y++; break; fall-through
case "blue": b++; break;

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++;

for (i = 2; i <= 10; i += 2) for (i = 2; i <= 10; i += 2)


System.out.println(i); Console.WriteLine(i);

do do
i++; i++;
while (i < 10); while (i < 10);

for (int i : numArray) // foreach construct foreach (int i in numArray)


sum += i; sum += i;

// 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);

for (Object o : list) foreach (Object o in list)


System.out.println(o); Console.WriteLine(o);
Java Arrays C#
int nums[] = {1, 2, 3}; or int[] nums = {1, 2, 3}; int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) for (int i = 0; i < nums.Length; i++)
System.out.println(nums[i]); Console.WriteLine(nums[i]);

String names[] = new String[5]; string[] names = new string[5];


names[0] = "David"; names[0] = "David";

float twoD[][] = new float[rows][cols]; float[,] twoD = new float[rows, cols];


twoD[2][0] = 4.5; twoD[2,0] = 4.5f;

int[][] jagged = new int[5][]; int[][] jagged = new int[3][] {


jagged[0] = new int[5]; new int[5], new int[2], new int[3] };
jagged[1] = new int[2]; jagged[0][4] = 5;
jagged[2] = new int[3];
jagged[0][4] = 5;
Java Functions C#

// 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;
}

int total = Sum(4, 3, 2, 1); // returns 10


Java Strings C#
// String concatenation // String concatenation
String school = "Harding "; string school = "Harding ";
school = school + "University"; // school is "Harding school = school + "University"; // school is "Harding
University" University"

// String comparison // String comparison


String mascot = "Bisons"; string mascot = "Bisons";
if (mascot == "Bisons") // Not the correct way to do string if (mascot == "Bisons") // true
comparisons if (mascot.Equals("Bisons")) // true
if (mascot.equals("Bisons")) // true if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.equalsIgnoreCase("BISONS")) // true if (mascot.CompareTo("Bisons") == 0) // true
if (mascot.compareTo("Bisons") == 0) // true
Console.WriteLine(mascot.Substring(2, 3)); // Prints "son"
System.out.println(mascot.substring(2, 5)); // Prints "son"
// My birthday: Oct 12, 1973
// My birthday: Oct 12, 1973 DateTime dt = new DateTime(1973, 10, 12);
java.util.Calendar c = new java.util.GregorianCalendar(1973, string s = "My birthday: " + dt.ToString("MMM dd, yyyy");
10, 12);
String s = String.format("My birthday: %1$tb %1$te, %1$tY", // Mutable string
c); System.Text.StringBuilder buffer = new
System.Text.StringBuilder("two ");
// Mutable string buffer.Append("three ");
StringBuffer buffer = new StringBuffer("two "); buffer.Insert(0, "one ");
buffer.append("three "); buffer.Replace("two", "TWO");
buffer.insert(0, "one "); Console.WriteLine(buffer); // Prints "one TWO three"
buffer.replace(4, 7, "TWO");
System.out.println(buffer); // Prints "one TWO three"
Java Exception Handling C#
// Must be in a method that is declared to throw this exception Exception up = new Exception("Something is really wrong.");
Exception ex = new Exception("Something is really wrong."); throw up; // ha ha
throw ex;

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 {
... ...
} }

// Interface definition // Interface definition


interface IAlarmClock { interface IAlarmClock {
... ...
} }

// Extending an interface // Extending an interface


interface IAlarmClock extends IClock { interface IAlarmClock : IClock {
... ...
} }

// Interface implementation // Interface implementation


class WristWatch implements IAlarmClock, ITimer { class WristWatch : IAlarmClock, ITimer {
... ...
} }

Java Constructors / Destructors C#


class SuperHero { class SuperHero {
private int mPowerLevel; private int mPowerLevel;

public SuperHero() { public SuperHero() {


mPowerLevel = 0; mPowerLevel = 0;
} }

public SuperHero(int powerLevel) { public SuperHero(int powerLevel) {


this.mPowerLevel= powerLevel; this.mPowerLevel= powerLevel;
} }

~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();

hero.setName("SpamMan"); hero.Name = "SpamMan";


hero.setPowerLevel(3); hero.PowerLevel = 3;

hero.Defend("Laura Jones"); hero.Defend("Laura Jones");


SuperHero.Rest(); // Calling static method SuperHero.Rest(); // Calling static method

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

if (hero == null) if (hero == null)


hero = new SuperHero(); hero = new SuperHero();

Object obj = new SuperHero(); Object obj = new SuperHero();


System.out.println("object's type: " + Console.WriteLine("object's type: " +
obj.getClass().toString()); obj.GetType().ToString());
if (obj instanceof SuperHero) if (obj is SuperHero)
System.out.println("Is a SuperHero object."); Console.WriteLine("Is a SuperHero object.");
Java Properties C#
private int mSize; private int mSize;

public int getSize() { return mSize; } public int Size {


public void setSize(int value) { get { return mSize; }
if (value < 0) set {
mSize = 0; if (value < 0)
else mSize = 0;
mSize = value; else
} mSize = value;
}
}
int s = shoe.getSize();
shoe.setSize(s+1); shoe.Size++;
Java Structs C#
struct StudentRecord {
public string name;
public float gpa;

No structs in Java. public StudentRecord(string name, float gpa) {


this.name = name;
this.gpa = gpa;
}
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);


StudentRecord stu2 = stu;

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.");

int c = Console.Read(); // Read single char


int c = System.in.read(); // Read single char Console.WriteLine(c); // Prints 65 if user enters "A"
System.out.println(c); // Prints 65 if user enters "A"
// The studio costs $499.00 for 3 months.
// The studio costs $499.00 for 3 months. Console.WriteLine("The {0} costs {1:C} for {2} months.\n",
System.out.printf("The %s costs $%.2f for %d months.%n", "studio", 499.0, 3);
"studio", 499.0, 3);
// Today is 06/25/2004
// Today is 06/25/04 Console.WriteLine("Today is " +
System.out.printf("Today is %tD\n", new java.util.Date()); DateTime.Now.ToShortDateString());
Java File I/O C#
import java.io.*; using System.IO;

// Character stream writing // Character stream writing


FileWriter writer = new FileWriter("c:\\myfile.txt"); StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.write("Out to file.\n"); writer.WriteLine("Out to file.");
writer.close(); writer.Close();

// Character stream reading // Character stream reading


FileReader reader = new FileReader("c:\\myfile.txt"); StreamReader reader = File.OpenText("c:\\myfile.txt");
BufferedReader br = new BufferedReader(reader); string line = reader.ReadLine();
String line = br.readLine(); while (line != null) {
while (line != null) { Console.WriteLine(line);
System.out.println(line); line = reader.ReadLine();
line = br.readLine(); }
} reader.Close();
reader.close();

// Binary stream writing // Binary stream writing


FileOutputStream out = new BinaryWriter out = new
FileOutputStream("c:\\myfile.dat"); BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
out.write("Text data".getBytes()); out.Write("Text data");
out.write(123); out.Write(123);
out.close(); out.Close();

// Binary stream reading // Binary stream reading


FileInputStream in = new FileInputStream("c:\\myfile.dat"); BinaryReader in = new
byte buff[] = new byte[9]; BinaryReader(File.OpenRead("c:\\myfile.dat"));
in.read(buff, 0, 9); // Read first 9 bytes into buff string s = in.ReadString();
String s = new String(buff); int num = in.ReadInt32();
int num = in.read(); // Next is 123 in.Close();
in.close();

You might also like