Java and C# Comparison
This is a quick reference guide to highlight some key syntactical differences between Java and C#. This is not a complete overview of either language. Hope you find this useful! Also see .
| |||||
package hello;public class HelloWorld { public static void main(String[] args) { String name = "Java"; // See if an argument was passed from the command line if (args.length == 1) name = args[0]; System.out.println("Hello, " + name + "!"); }} | using System; namespace Hello { public class HelloWorld { public static void Main(string[] args) { string name = "C#"; // See if an argument was passed from the command line if (args.Length == 1) name = args[0]; Console.WriteLine("Hello, " + name + "!"); } }} | ||||
| |||||
// Single line/* Multiple line *//** Javadoc documentation comments */ | // Single line/* Multiple line *//// XML comments on a single line/** XML comments on multiple lines */ | ||||
| |||||
Primitive Typesbooleanbytecharshort, int, longfloat, double Reference TypesObject (superclass of all other classes)Stringarrays, classes, interfaces Conversions // int to String int x = 123; String y = Integer.toString(x); // y is "123" // String to inty = "456"; x = Integer.parseInt(y); // x is 456 // double to intdouble z = 3.5; x = (int) z; // x is 3 (truncates decimal) | Value Typesboolbyte, sbytecharshort, ushort, int, uint, long, ulongfloat, double, decimalstructures, enumerations Reference Typesobject (superclass of all other classes)stringarrays, classes, interfaces, delegates Convertions // int to string int x = 123; String y = x.ToString(); // y is "123" // string to inty = "456"; x = int.Parse(y); // or x = Convert.ToInt32(y); // double to intdouble z = 3.5; x = (int) z; // x is 3 (truncates decimal) | ||||
| |||||
// May be initialized in a constructor final double PI = 3.14; | const double PI = 3.14; // Can be set to a const or a variable. May be initialized in a constructor. readonly int MAX_HEIGHT = 9; | ||||
| |||||
enum Action {Start, Stop, Rewind, Forward}; // Special type of class enum Status { Flunk(50), Pass(70), Excel(90); private final int value; Status(int value) { this.value = value; } public int value() { return value; } }; Action a = Action.Stop; if (a != Action.Start) System.out.println(a); // Prints "Stop"Status s = Status.Pass;System.out.println(s.value()); // Prints "70" | enum Action {Start, Stop, Rewind, Forward}; enum Status {Flunk = 50, Pass = 70, Excel = 90}; No equivalent.Action a = Action.Stop;if (a != Action.Start) Console.WriteLine(a); // Prints "Stop" Status s = Status.Pass; Console.WriteLine((int) s); // Prints "70" | ||||
| |||||
Comparison== < > <= >= != Arithmetic+ - * /% (mod)/ (integer division if both operands are ints)Math.Pow(x, y) Assignment= += -= *= /= %= &= |= ^= <<= >>= >>>= ++ -- Bitwise& | ^ ~ << >> >>> Logical&& || & | ^ ! Note: && and || perform short-circuit logical evaluations String Concatenation+ | Comparison== < > <= >= != Arithmetic+ - * /% (mod)/ (integer division if both operands are ints)Math.Pow(x, y) Assignment= += -= *= /= %= &= |= ^= <<= >>= ++ -- Bitwise& | ^ ~ << >> Logical&& || & | ^ ! Note: && and || perform short-circuit logical evaluations String Concatenation+ | ||||
| |||||
greeting = age < 20 ? "What's up?" : "Hello"; if (x < y) System.out.println("greater");if (x != 100) { x *= 5; y *= 2; } else z *= 6;int selection = 2; switch (selection) { // Must be byte, short, int, char, or enum case 1: x++; // Falls through to next case if no break case 2: y++; break; case 3: z++; break; default: other++;} | greeting = age < 20 ? "What's up?" : "Hello"; if (x < y) Console.WriteLine("greater");if (x != 100) { x *= 5; y *= 2; } else z *= 6;string color = "red";switch (color) { // Can be any predefined type case "red": r++; break; // break is mandatory; no fall-through case "blue": b++; break; case "green": g++; break; default: other++; break; // break necessary on default} | ||||
| |||||
while (i < 10) i++;for (i = 2; i <= 10; i += 2) System.out.println(i);do i++; while (i < 10);for (int i : numArray) // foreach construct sum += i; // for loop can be used to iterate through any Collectionimport java.util.ArrayList;ArrayList<Object> list = new ArrayList<Object>();list.add(10); // boxing converts to instance of Integerlist.add("Bisons");list.add(2.3); // boxing converts to instance of Doublefor (Object o : list) System.out.println(o); | while (i < 10) i++;for (i = 2; i <= 10; i += 2) Console.WriteLine(i);do i++; while (i < 10);foreach (int i in numArray) sum += i;// foreach can be used to iterate through any collection using System.Collections;ArrayList list = new ArrayList();list.Add(10);list.Add("Bisons");list.Add(2.3);foreach (Object o in list) Console.WriteLine(o); | ||||
| |||||
int nums[] = {1, 2, 3}; or int[] nums = {1, 2, 3};for (int i = 0; i < nums.length; i++) System.out.println(nums[i]);String names[] = new String[5];names[0] = "David";float twoD[][] = new float[rows][cols];twoD[2][0] = 4.5; int[][] jagged = new int[5][]; jagged[0] = new int[5]; jagged[1] = new int[2]; jagged[2] = new int[3]; jagged[0][4] = 5; | int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++) Console.WriteLine(nums[i]);string[] names = new string[5];names[0] = "David";float[,] twoD = new float[rows, cols];twoD[2,0] = 4.5f; int[][] jagged = new int[3][] { new int[5], new int[2], new int[3] }; jagged[0][4] = 5; | ||||
| |||||
// Primitive types and references are always passed by valuevoid TestFunc(int x, Point p) { x++; p.x++; // Modifying property of the object p = null; // Remove local reference to object } class Point { public int x, y; }Point p = new Point(); p.x = 2; int a = 1; TestFunc(a, p);System.out.println(a + " " + p.x + " " + (p == null) ); // 1 3 false// Accept variable number of argumentsint Sum(int ... nums) { int sum = 0; for (int i : nums) sum += i; return sum;} int total = Sum(4, 3, 2, 1); // returns 10 |
// Pass by value (default), in/out-reference (ref), and out-reference (out) void TestFunc(int x, ref int y, out int z, Point p1, ref Point p2) { x++; y++; z = 5; p1.x++; // Modifying property of the object p1 = null; // Remove local reference to object p2 = null; // Free the object } class Point { public int x, y; }Point p1 = new Point(); Point p2 = new Point(); p1.x = 2; int a = 1, b = 1, c; // Output param doesn't need initializing TestFunc(a, ref b, out c, p1, ref p2); Console.WriteLine("{0} {1} {2} {3} {4}", a, b, c, p1.x, p2 == null); // 1 2 5 3 True// Accept variable number of argumentsint Sum(params int[] nums) { int sum = 0; foreach (int i in nums) sum += i; return sum;} int total = Sum(4, 3, 2, 1); // returns 10 | ||||
| |||||
// String concatenationString school = "Harding "; school = school + "University"; // school is "Harding University" // String comparisonString mascot = "Bisons"; if (mascot == "Bisons") // Not the correct way to do string comparisonsif (mascot.equals("Bisons")) // trueif (mascot.equalsIgnoreCase("BISONS")) // trueif (mascot.compareTo("Bisons") == 0) // true System.out.println(mascot.substring(2, 5)); // Prints "son" // My birthday: Oct 12, 1973java.util.Calendar c = new java.util.GregorianCalendar(1973, 10, 12);String s = String.format("My birthday: %1$tb %1$te, %1$tY", c); // Mutable string StringBuffer buffer = new StringBuffer("two "); buffer.append("three "); buffer.insert(0, "one "); buffer.replace(4, 7, "TWO"); System.out.println(buffer); // Prints "one TWO three" | // String concatenationstring school = "Harding "; school = school + "University"; // school is "Harding University" // String comparisonstring mascot = "Bisons"; if (mascot == "Bisons") // trueif (mascot.Equals("Bisons")) // trueif (mascot.ToUpper().Equals("BISONS")) // trueif (mascot.CompareTo("Bisons") == 0) // true Console.WriteLine(mascot.Substring(2, 3)); // Prints "son" // My birthday: Oct 12, 1973DateTime dt = new DateTime(1973, 10, 12);string s = "My birthday: " + dt.ToString("MMM dd, yyyy"); // Mutable string System.Text.StringBuilder buffer = new System.Text.StringBuilder("two "); buffer.Append("three "); buffer.Insert(0, "one "); buffer.Replace("two", "TWO"); Console.WriteLine(buffer); // Prints "one TWO three" | ||||
| |||||
// Must be in a method that is declared to throw this exceptionException ex = new Exception("Something is really wrong."); throw ex; try { y = 0; x = 10 / y;} catch (Exception ex) { System.out.println(ex.getMessage()); } finally { // Code that always gets executed} | Exception up = new Exception("Something is really wrong."); throw up; // ha hatry { y = 0; x = 10 / y;} catch (Exception ex) { // Variable "ex" is optional Console.WriteLine(ex.Message); } finally { // Code that always gets executed} | ||||
| |||||
package harding.compsci.graphics; // Import single classimport harding.compsci.graphics.Rectangle;// Import all classesimport harding.compsci.graphics.*; | namespace Harding.Compsci.Graphics { ...}or namespace Harding { namespace Compsci { namespace Graphics { ... } }}// Import single classusing Rectangle = Harding.CompSci.Graphics.Rectangle; // Import all classusing Harding.Compsci.Graphics; | ||||
| |||||
Accessibility keywords publicprivateprotectedstatic // Inheritanceclass FootballGame extends Competition { ...} // Interface definitioninterface IAlarmClock { ...} // Extending an interface interface IAlarmClock extends IClock { ...} // Interface implementationclass WristWatch implements IAlarmClock, ITimer { ...} | Accessibility keywords publicprivateinternalprotectedprotected internalstatic // Inheritanceclass FootballGame : Competition { ...} // Interface definitioninterface IAlarmClock { ...} // Extending an interface interface IAlarmClock : IClock { ...} // Interface implementationclass WristWatch : IAlarmClock, ITimer { ...} | ||||
| |||||
class SuperHero { private int mPowerLevel;public SuperHero() { mPowerLevel = 0; }public SuperHero(int powerLevel) { this.mPowerLevel= powerLevel; }// No destructors, just override the finalize method protected void finalize() throws Throwable { super.finalize(); // Always call parent's finalizer }} | class SuperHero { private int mPowerLevel; public SuperHero() { mPowerLevel = 0; } public SuperHero(int powerLevel) { this.mPowerLevel= powerLevel; } ~SuperHero() { // Destructor code to free unmanaged resources. // Implicitly creates a Finalize method. }} | ||||
| |||||
SuperHero hero = new SuperHero(); hero.setName("SpamMan"); hero.setPowerLevel(3); hero.Defend("Laura Jones");SuperHero.Rest(); // Calling static methodSuperHero hero2 = hero; // Both refer to same object hero2.setName("WormWoman"); System.out.println(hero.getName()); // Prints WormWoman hero = null; // Free the object if (hero == null) hero = new SuperHero();Object obj = new SuperHero(); System.out.println("object's type: " + obj.getClass().toString()); if (obj instanceof SuperHero) System.out.println("Is a SuperHero object."); | SuperHero hero = new SuperHero(); hero.Name = "SpamMan"; hero.PowerLevel = 3;hero.Defend("Laura Jones"); SuperHero.Rest(); // Calling static methodSuperHero hero2 = hero; // Both refer to same object hero2.Name = "WormWoman"; Console.WriteLine(hero.Name); // Prints WormWoman hero = null ; // Free the object if (hero == null) hero = new SuperHero();Object obj = new SuperHero(); Console.WriteLine("object's type: " + obj.GetType().ToString()); if (obj is SuperHero) Console.WriteLine("Is a SuperHero object."); | ||||
| |||||
private int mSize; public int getSize() { return mSize; } public void setSize(int value) { if (value < 0) mSize = 0; else mSize = value; } int s = shoe.getSize();shoe.setSize(s+1); | private int mSize; public int Size { get { return mSize; } set { if (value < 0) mSize = 0; else mSize = value; } }shoe.Size++; | ||||
| |||||
No structs in Java. | struct StudentRecord { public string name; public float gpa; 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.io.DataInput in = new java.io.DataInputStream(System.in);System.out.print("What is your name? ");String name = in.readLine();System.out.print("How old are you? ");int age = Integer.parseInt(in.readLine());System.out.println(name + " is " + age + " years old."); int c = System.in.read(); // Read single charSystem.out.println(c); // Prints 65 if user enters "A" // The studio costs $499.00 for 3 months.System.out.printf("The %s costs $%.2f for %d months.%n", "studio", 499.0, 3); // Today is 06/25/04System.out.printf("Today is %tD\n", new java.util.Date()); | Console.Write("What's your name? ");string name = Console.ReadLine();Console.Write("How old are you? ");int age = Convert.ToInt32(Console.ReadLine());Console.WriteLine("{0} is {1} years old.", name, age);// orConsole.WriteLine(name + " is " + age + " years old."); int c = Console.Read(); // Read single charConsole.WriteLine(c); // Prints 65 if user enters "A" // The studio costs $499.00 for 3 months.Console.WriteLine("The {0} costs {1:C} for {2} months.\n", "studio", 499.0, 3); // Today is 06/25/2004Console.WriteLine("Today is " + DateTime.Now.ToShortDateString()); | ||||
| |||||
import java.io.*; // Character stream writingFileWriter writer = new FileWriter("c:\\myfile.txt");writer.write("Out to file.\n");writer.close(); // Character stream readingFileReader reader = new FileReader("c:\\myfile.txt");BufferedReader br = new BufferedReader(reader);String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } reader.close(); // Binary stream writingFileOutputStream out = new FileOutputStream("c:\\myfile.dat");out.write("Text data".getBytes());out.write(123);out.close(); // Binary stream readingFileInputStream in = new FileInputStream("c:\\myfile.dat");byte buff[] = new byte[9];in.read(buff, 0, 9); // Read first 9 bytes into buffString s = new String(buff);int num = in.read(); // Next is 123in.close(); | using System.IO; // Character stream writingStreamWriter writer = File.CreateText("c:\\myfile.txt"); writer.WriteLine("Out to file."); writer.Close(); // Character stream readingStreamReader reader = File.OpenText("c:\\myfile.txt"); string line = reader.ReadLine(); while (line != null) { Console.WriteLine(line); line = reader.ReadLine(); } reader.Close(); // Binary stream writingBinaryWriter out = new BinaryWriter(File.OpenWrite("c:\\myfile.dat")); out.Write("Text data"); out.Write(123); out.Close(); // Binary stream readingBinaryReader in = new BinaryReader(File.OpenRead("c:\\myfile.dat")); string s = in.ReadString(); int num = in.ReadInt32(); in.Close(); |
Page last modified: 02/01/2011 06:45:24
This work is licensed under a . Please send any corrections or comments to .