原文链接:http://www.harding.edu/fmccown/java_csharp_comparison.html

Java 程序结构 C#
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 + "!");       }    } }
Java 注释 C#
// Single line /* Multiple     line  */ /** Javadoc documentation comments */ // Single line /* Multiple     line  */ /// XML comments on a single line /** XML comments on multiple lines */
Java 数据类型 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, decimal 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 = int.Parse(y);   // or x = Convert.ToInt32(y);

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

Java 常量 C#
// 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;

Java 枚举 C#

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"

Java 操作符 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 分支语句 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, 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 }

Java 循环语句 C#

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 Collection import java.util.ArrayList; ArrayList<Object> list = new ArrayList<Object>(); list.add(10);    // boxing converts to instance of Integer list.add("Bisons"); list.add(2.3);    // boxing converts to instance of Double
for (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);

Java 数组 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 方法 C#
// Return single value int Add(int x, int y) {     return x + y;  }

int sum = Add(2, 3);

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

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

// Accept variable number of arguments int Sum(int ... nums) {   int sum = 0;   for (int i : nums)     sum += i;   return sum; }

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

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

int sum = Add(2, 3);

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

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 字符串 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"

// My birthday: Oct 12, 1973 java.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 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"

// My birthday: Oct 12, 1973 DateTime 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"

Java 异常管理 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 命名空间 C#

package harding.compsci.graphics;

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

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

namespace Harding.Compsci.Graphics {   ... }

or

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

// Import single class using Rectangle = Harding.CompSci.Graphics.Rectangle;

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

Java 类和接口 C#

Accessibility keywords  public private protected static

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

// Interface definition interface IAlarmClock {   ... }

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

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

Accessibility keywords  public private internal protected protected internal static

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

// Interface definition interface IAlarmClock {   ... }

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

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

Java 构造和析构 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 Objects C#

SuperHero hero = new SuperHero();

hero.setName("SpamMan");  hero.setPowerLevel(3); 
hero.Defend("Laura Jones"); SuperHero.Rest();  // Calling static method

SuperHero 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 method

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

Java 属性(获取器和设置器) 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++;

Java 结构类型 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 控制台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"

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

int c = Console.Read();  // Read single char Console.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/2004 Console.WriteLine("Today is " + DateTime.Now.ToShortDateString());

Java 文件I/O C#

import java.io.*;

// Character stream writing FileWriter writer = new FileWriter("c:\\myfile.txt"); writer.write("Out to file.\n"); writer.close();

// Character stream reading FileReader 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 writing FileOutputStream out = new FileOutputStream("c:\\myfile.dat"); out.write("Text data".getBytes()); out.write(123); out.close();

// Binary stream reading FileInputStream in = new FileInputStream("c:\\myfile.dat"); byte buff[] = new byte[9]; in.read(buff, 0, 9);   // Read first 9 bytes into buff String s = new String(buff); int num = in.read();   // Next is 123 in.close();

using System.IO;

// Character stream writing StreamWriter writer = File.CreateText("c:\\myfile.txt");  writer.WriteLine("Out to file.");  writer.Close();

// Character stream reading StreamReader reader = File.OpenText("c:\\myfile.txt");  string line = reader.ReadLine();  while (line != null) {   Console.WriteLine(line);    line = reader.ReadLine();  }  reader.Close();

// Binary stream writing BinaryWriter out = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));  out.Write("Text data");  out.Write(123);  out.Close();

// Binary stream reading BinaryReader in = new BinaryReader(File.OpenRead("c:\\myfile.dat"));  string s = in.ReadString();  int num = in.ReadInt32();  in.Close();

【转】Java与C#语言级比较的更多相关文章

  1. JAVA在语言级支持多线程

    进程:任务 任务并发执行是一个宏观概念,微观上是串行的. 进程的调度是有OS负责的(有的系统为独占式,有的系统为共享式,根据重要性,进程有优先级). 由OS将时间分为若干个时间片. JAVA在语言级支 ...

  2. Java替代C语言的可能性

        前不久CSDN刊登了一篇<C语言已经死了>的文章,引起了一些争论.事实上那篇文章是从Ed Burnette的博客上转载来的,原文题目是“Die, C, die!”,直译过来应该是& ...

  3. 分享:写了一个 java 调用 C语言 开发的动态库的范例

    分享:写了一个 java 调用 C语言 开发的动态库的范例 cfunction.h   代码#pragma once#ifdef __cplusplusextern "C" {#e ...

  4. atitit.java解析sql语言解析器解释器的实现

    atitit.java解析sql语言解析器解释器的实现 1. 解析sql的本质:实现一个4gl dsl编程语言的编译器 1 2. 解析sql的主要的流程,词法分析,而后进行语法分析,语义分析,构建sq ...

  5. 比较java与c语言中数字转换成字符的不同

    java java中将数字转换成字符非常方便,只要用一个"+"然后在跟一个空格行了.比如,你输入一个122 ,就会变成"122 ". import java.u ...

  6. JAVA调用C语言写的SO文件

    JAVA调用C语言写的SO文件 因为工作需要写一份SO文件,作为手机硬件IC读卡和APK交互的桥梁,也就是中间件,看了网上有说到JNI接口技术实现,这里转载了一个实例 // 用JNI实现 // 实例: ...

  7. LINQ——语言级集成查询入门指南(1)

    本文主要是对语言级集成查询或简称为LINQ做一个介绍,包括LINQ是什么,不是什么,并对它在语言特性方面做一个简短的回顾,然后举一些使用LINQ的实际例子进行说明. 语言级集成查询是什么? 在我过去写 ...

  8. 使用strace查看C语言级别的php源码

    XCACHE XCache 是一个开源的 opcode 缓存器/优化器, 这意味着他能够提高您服务器上的 PHP 性能. 他通过把编译 PHP 后的数据缓冲到共享内存从而避免重复的编译过程, 能够直接 ...

  9. TOP100summit 2017 七牛云许式伟:不用JAVA和C语言,我为什么坚持Go语言

    本文编辑:Cynthia 2009年,谷歌发布第二款开源编程语言,Go语言.8年过去了,很多初创公司早期使用Go进行开发,包括云计算巨头Docker.而Go语言在中国的普及程度还比不上JAVA和C语言 ...

随机推荐

  1. JAVA反射机制示例,读取excel数据映射到JAVA对象中

    import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileInputStream; import ja ...

  2. javascript 切换动画

    function startMove(obj, json, fn) { clearInterval(obj.timer); obj.timer = setInterval(function() { v ...

  3. eclipse中Java代码导入包,出现main.java前缀

    1.工程右击,按照下图指示的选择 2.按照下图,进行删除选中项,然后点击OK保存

  4. hdu1175连连看

    Problem Description “连连看”相信很多人都玩过.没玩过也没关系,下面我给大家介绍一下游戏规则:在一个棋盘中,放了很多的棋子.如果某两个相同的棋子,可以通过一条线连起来(这条线不能经 ...

  5. for()循环

    今天发现自己一直以来都搞错了for()循环的执行顺序.这么简单的问题一直都错了,我也是醉了. ;i>&&a[i]>a[i-];--i) { } //即 for(init_s ...

  6. git删除分支

    git branch -d branchname删除一个分支需要具备的条件: 1 如果待删除的分支没有upstream branch,那么待删除的分支需要合并到HEAD上,否则需要使用-D强制删除 2 ...

  7. 关于PS里图层样式的全局光

    勾选“使用全局光”,则各个图层样式的光源角度都会相同. 我在“内阴影”效果里勾选了“使用全局光”,然后我发现当我在“投影”效果和“斜面和浮雕”效果里选择使用全局光时,它们的光源角度自动变成120度, ...

  8. [转]Cocos2d-x建工程时避免copy文件夹和库

    原文链接:  http://www.cnblogs.com/andyque/archive/2011/09/27/2192920.html 在上一篇教程中,我们演示了如何使用VS2010来新建一个工程 ...

  9. http://codepen.io/zhou-yg/pen/NqgPmg 在线编辑器

    http://codepen.io/zhou-yg/pen/NqgPmg          在线编辑器

  10. Python变量和数据类型

    十六进制用0x前缀和0-9 a-f表示   字符串是以''或""括起来的任意文本   一个布尔值只有True和False两种值   布尔值可以用and or not运算   空值是 ...