c# 与 java 语法异同

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 VB.NET and C# Comparison.

Program Structure 
Comments 
Data Types 
Constants 
Enumerations 
Operators
Choices 
Loops 
Arrays 
Functions 
Strings
Exception Handling 
Namespaces 
Classes / Interfaces 
Constructors / Destructors 
Objects
Properties 
Structs 
Console I/O 
File I/O 
Java Program Structure 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 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, 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 Constants 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 Enumerations 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 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 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, 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 Loops 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 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 Functions 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 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"

// 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 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 Namespaces 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 Classes / Interfaces 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 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 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 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++;

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

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

Page last modified: 02/01/2011 06:45:24


This work is licensed under a Creative Commons License.

Please send any corrections or comments to [email protected].

Home

时间: 2024-12-26 01:06:26

c# 与 java 语法异同的相关文章

eclipse使用与java语法规则

eclipse的使用 1.运行点击"三角图标"或右键Run As运行2.3. java语法规范 1.括号要成对出现2.每句代码应该有分号结束3.java语法区分大小写4.一个文件只能写一个带有public的class声明,还必须和文件名一致.一个文件中不可以有多个带有public的修饰符号5.名称写的时候不要包含关键字和非法字符(字母和下划线开头可以,也可以用数字结尾)6.java代码的语法全部都是半角符号7.学会规范的写代码. 写代码的好习惯: 1.常按保存,写完一句或几句就按一次C

Java语法基础

Java语法基础 1.  关键字 某些单词对编译器有着特殊的含义,并且不能作为标示符使用,全部是小写字母 Java语言关键字 abstract boolean break byte case catch char class try do default continue double else extends assert final finally float for If implement import instanceof int interface long native new g

深入理解java虚拟机(十二) Java 语法糖背后的真相

语法糖(Syntactic Sugar),也叫糖衣语法,是英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语.指的是,在计算机语言中添加某种语法,这些语法糖虽然不会对语言的功能产生任何影响,却能使程序员更方便的使用语言开发程序,同时增强程序代码的可读性,避免出错的机会.但是如果只是大量添加和使用语法糖,却不去了解他,容易产生过度依赖,从而无法看清语法糖的糖衣背后,程序代码的真实面目. 总而言之,语法糖可以看做是编译器实现的一些"小把戏",这些"小

java语法糖

语法糖 Java语法糖系列,所以首先讲讲什么是语法糖.语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的字节码或者特定的方式对这些语法做一些处理,开发者就可以直接方便地使用了.这些语法糖虽然不会提供实质性的功能改进,但是它们或能提高性能.或能提升语法的严谨性.或能减少编码出错的机会.Java提供给了用户大量的语法糖,比如泛型.自动装箱.自动拆箱.foreach循环.变长参数.内部类.枚举类.断言(assert)等 断言(as

程序员带你学习安卓开发,十天快速入-对比C#学习java语法

关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 如果你真想学习,请评论学过的每篇文章,记录学习的痕迹. 请把所有教程文章中所提及的代码,最少敲写三遍,达到熟悉的效果. 上次课程:.程序员带你学习安卓开发,十天快速入门-开发工具配置学习讲的是java环境的配置以及as安装工具的安装. 其中有网友@鹅鹅鹅_说道,其实jdk的环境变量配置,不用配置的那么麻烦了.当前的jdk版本只要设置一个变量javahome就可以了,其他的可以不需要配置.在这里提一下.

java语法基础一

Java语法基础一 Java代码基本格式 Java中所有程序代码都必须存在于一个类中,用class关键字定义类,在class之前可以有一些修饰符.格式如下: 修饰符 class 类名 { 程序代码 } 注:1.Java是严格区分大小写的. 2.Java程序中一句连续的字符串不能分开在两行中写. Java程序的注释 Java里的注释有三种类型: 1.单行注释 在注释内容前面加“//”,格式为: 代码; //注释内容 2.多行注释 以斜杠加星号开头,以星号加斜杠结尾. 3.文档注释 以斜杠加两个星号

java语法

Comparable<T>中,对于返回,尽量不要使用value1 - value2,万一value1是很大的正数,value2是很大的负数,那么容易造成溢出 Comparable接口中,经常有T extends Comparable<? super T>的,该怎么理解 Orange extends Comparable<Fruit> and Fruit super Orange 就是继承这个接口的类,可以用Collections.sort之类的的generic方法来比较

Java 语法 索引 ----- 主函数 (Main)

public class MyApp { public static void main(String[] args) { System.out.print("Hello World"); } } Java 语法 索引 ----- 主函数 (Main),布布扣,bubuko.com

Java 语法 索引 ----- 变量-----数据类型

数据类型 类型 bits/byte 范围 默认值 byte 8/1 -128 +127 0 short 16/2 -32,768+32,767 0 int 32/4 -2,147,483,648 = -231+2,147,483,647 = 231-1 0 long 64/8 -9,223,372,036,854,775,808 = -263+9,223,372,036,854,775,807 = 263-1 0L float 32/4 1.40129846432481707e-45  = 2-