Chinaunix首页 | 论坛 | 博客
  • 博客访问: 949683
  • 博文数量: 264
  • 博客积分: 10107
  • 博客等级: 上将
  • 技术积分: 2455
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-09 16:34
文章分类

全部博文(264)

文章存档

2012年(1)

2011年(11)

2010年(128)

2009年(82)

2008年(42)

我的朋友

分类:

2009-12-17 10:27:49

Java and C# Comparison
This is a quick reference guide to highlight some key syntactical differences between Java and C#. Hope you find this useful!

Also see .

Java Comments C#
// Single line
/* Multiple
    line  */

/** Javadoc documentation comments */
// Single line
/* Multiple
    line  */

/// XML comments on a single line
/** XML comments on multiple lines */
Java Data Types C#

Primitive Types
boolean
byte
char
short, int, long
float, double


Reference Types

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

Conversions

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

// String to int
y = "456"; 
x = Integer.parseInt(y);   // x is 456

// double to int
double z = 3.5;
x = (int) z;   // x is 3  (truncates decimal)

Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
structures, enumerations

Reference Types
object    (superclass of all other classes)
string
arrays, classes, interfaces, delegates

Convertions

// int to string
int x = 123;
String y = x.ToString();  // y is "123"

// string to int
y = "456";
x = System.Convert.ToInt32(y);   // x is 456

// double to int
double z = 3.5;
x = (int) z;   // x is 3  (truncates decimal)

Java Constants C#
final double PI = 3.14;  const double PI = 3.14;
Java Enumerations C#
/* Enumerations coming in 1.5.  For now use a class to do almost the same thing. */
public class Action {
  public static final int START = 0;
  public static final int STOP = 1;
  public static final int REWIND = 2;
  public static final int FORWARD = 3;
}

int action = Action.STOP;
System.out.println(action);  // Prints "1"
enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
  Console.WriteLine((int) a);         // Prints "1"
Console.WriteLine(Status.Pass);    // Prints "Pass"
Java Operators C#

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
+

Java Console I/O C#
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 char
System.out.println(c);      // Prints 65 if user enters "A"

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);
// or
Console.WriteLine(name + " is " + age + " years old.");

int c = Console.Read();  // Read single char
Console.WriteLine(c);    // Prints 65 if user enters "A"

Java Functions C#
// Return single value
int Add(int x, int y) {
   return x + y;
}

System.out.println("2 + 3 = " + Add(2, 3));

// Return no value
void PrintSum(int x, int y) {
   System.out.println(x + y);
}

System.out.print("2 + 3 = ");
PrintSum(2, 3); 

// Primitive types and references are always passed by value
void 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




Passing variable number of arguments only in Java 1.5.

 

// Return single value
int Add(int x, int y) {
   return x + y;
}

Console.WriteLine("2 + 3 = " + Add(2, 3));

// Return no value
void PrintSum(int x, int y) {
   Console.WriteLine(x + y);
}

Console.Write("2 + 3 = ");
PrintSum(2, 3); 

// 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 arguments
int 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

Java Arrays C#
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;

Java Loops C#

while (i < 10)
  i++;

for (i = 2; i < = 10; i += 2) 
  System.out.println(i);

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

// foreach coming in Java 1.5; for now simulate using a Vector
import java.util.Vector;
Vector list = new Vector();
list.add(new Integer(10));
list.add("Bisons");
list.add(new Float(2.3));

for (int i=0; i < list.size(); i++)
  System.out.println(list.elementAt(i));

String[] names = {"Fred", "Sue", "Barney"};
for (int i=0; i < names.length; i++)
  System.out.println(names[i]);

while (i < 10)
  i++;

for (i = 2; i < = 10; i += 2)
  Console.WriteLine(i);

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

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

string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
  Console.WriteLine(s);

Java Choices C#

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, or char
  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
}

Java Strings C#

// String concatenation
String school = "Harding ";
school = school + "University";   // school is "Harding University"

// String comparison
String mascot = "Bisons";
if (mascot == "Bisons")    // Not the correct way to do string comparisons
if (mascot.equals("Bisons"))   // true
if (mascot.equalsIgnoreCase("BISONS"))   // true
if (mascot.compareTo("Bisons") == 0)   // true

System.out.println(mascot.substring(2, 5));   // Prints "son"

// 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 concatenation
string school = "Harding ";
school = school + "University";   // school is "Harding University"

// String comparison
string mascot = "Bisons";
if (mascot == "Bisons")    // true
if (mascot.Equals("Bisons"))   // true
if (mascot.ToUpper().Equals("BISONS"))   // true
if (mascot.CompareTo("Bisons") == 0)    // true

Console.WriteLine(mascot.Substring(2, 3));    // Prints "son"

// 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"

Java Exception Handling C#

// Must be in a method that is declared to throw this exception
Exception 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 ha


try
{
  y = 0;
  x = 10 / y;
} catch (Exception ex) {      // Variable "ex" is optional
  Console.WriteLine(ex.Message);
} finally {
  // Code that always gets executed
}

Java Class / Interface C#

// Inheritance
class FootballGame extends Competition {
  ...
}

// Interface definition
interface IAlarmClock {
  ...
}

// Extending an interface 
interface IAlarmClock extends IClock {
  ...
}

// Interface implementation
class WristWatch implements IAlarmClock, ITimer {
   ...
}

// Inheritance
class FootballGame : Competition {
  ...
}

// Interface definition
interface IAlarmClock {
  ...
}

// Extending an interface 
interface IAlarmClock : IClock {
  ...
}

// Interface implementation
class WristWatch : IAlarmClock, ITimer {
   ...
}

Java Namespaces C#

package harding.compsci.graphics;












import
harding.compsci.graphics.Rectangle;  // Import single class

import harding.compsci.graphics.*;   // Import all classes

namespace Harding.Compsci.Graphics {
  ...
}

or

namespace Harding {
  namespace Compsci {
    namespace Graphics {
      ...
    }
  }
}

using Harding.Compsci.Graphics;   // Import all classes

Java Constructors / Destructors C#

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.

  }
}

Java Structs C#


 

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 Properties C#

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

Page last modified: 02/03/2006 07:18:29

Copyright © 2004-2006 by Frank McCown

Permission to make photocopies or reproductions of this web page in its entirety is granted for personal or non-commercial uses as long as no money is charged.
Please send any comments or corrections to . 

阅读(587) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~