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

Java vs. C#的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. 故障重现(内存篇2),JAVA内存不足导致频繁回收和swap引起的性能问题

    背景起因: 记起以前的另一次也是关于内存的调优分享下   有个系统平时运行非常稳定运行(没经历过大并发考验),然而在一次活动后,人数并发一上来后,系统开始卡. 我按经验开始调优,在每个关键步骤的加入如 ...

  3. Elasticsearch之java的基本操作一

    摘要   接触ElasticSearch已经有一段了.在这期间,遇到很多问题,但在最后自己的不断探索下解决了这些问题.看到网上或多或少的都有一些介绍ElasticSearch相关知识的文档,但个人觉得 ...

  4. 论:开发者信仰之“天下IT是一家“(Java .NET篇)

    比尔盖茨公认的IT界领军人物,打造了辉煌一时的PC时代. 2008年,史蒂夫鲍尔默接替了盖茨的工作,成为微软公司的总裁. 2013年他与微软做了最后的道别. 2013年以后,我才真正看到了微软的变化. ...

  5. 故障重现, JAVA进程内存不够时突然挂掉模拟

    背景,服务器上的一个JAVA服务进程突然挂掉,查看产生了崩溃日志,如下: # Set larger code cache with -XX:ReservedCodeCacheSize= # This ...

  6. 死磕内存篇 --- JAVA进程和linux内存间的大小关系

    运行个JAVA 用sleep去hold住 package org.hjb.test; public class TestOnly { public static void main(String[] ...

  7. 【小程序分享篇 一 】开发了个JAVA小程序, 用于清除内存卡或者U盘里的垃圾文件非常有用

    有一种场景, 手机内存卡空间被用光了,但又不知道哪个文件占用了太大,一个个文件夹去找又太麻烦,所以我开发了个小程序把手机所有文件(包括路径下所有层次子文件夹下的文件)进行一个排序,这样你就可以找出哪个 ...

  8. Java多线程基础学习(二)

    9. 线程安全/共享变量——同步 当多个线程用到同一个变量时,在修改值时存在同时修改的可能性,而此时该变量只能被赋值一次.这就会导致出现“线程安全”问题,这个被多个线程共用的变量称之为“共享变量”. ...

  9. Java多线程基础学习(一)

    1. 创建线程    1.1 通过构造函数:public Thread(Runnable target, String name){}  或:public Thread(Runnable target ...

  10. c#与java的区别

    经常有人问这种问题,用了些时间java之后,发现这俩玩意除了一小部分壳子长的还有能稍微凑合上,基本上没什么相似之处,可以说也就是马甲层面上的相似吧,还是比较短的马甲... 一般C#多用于业务系统的开发 ...

随机推荐

  1. Node.js学习记录

    一.NPM 使用介绍 NPM是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,常见的使用场景有以下几种: 允许用户从NPM服务器下载别人编写的第三方包到本地使用. 允许用 ...

  2. easyui datagrid 单选框 效果

    columns: [[{            field: 'oid',            title: '选择',            width: 20,            forma ...

  3. ThinkPHP 3.2.3 关联模型的使用

    关于关联模型 ThinkPHP 3.2.3 的关联模型(手册地址)一般处理关联数据表的 CURD 操作,例如关联读取.关联写入.关联删除等. 实例 博客管理模块关于博客有 4 张数据表:博客表 crm ...

  4. 图文详解MFC程序设置菜单快捷键

    原来觉得添加个快捷键就只要几分钟,上网搜索文章都写得很模糊, 只有这边文章不错. http://www.cplusplus.me/1263.html http://blog.sina.com.cn/s ...

  5. oracle:case when 语句的区间用法

    在练习case when 语句时,碰到一个例子,结果答案根本就不对,语法就通不过,开始想着是不是case 只能是一个固定的取值,毕竟例子内给的都是case是个固定的值,后来网上查了好久才发现还有区间的 ...

  6. 使用Mod_JK链接Apache和Tomcat

    There are many potential problems associated with the default configuration of mod_jk.  Let's say it ...

  7. PowerDesigner连接mysql逆向生成pdm

    常用的建模工具有:PowerDesigner和ERWin,后者已快被淘汰,但前者依然活跃.相信大家都遇到过项目组已经运营很很久,但是竟然连一个ER图都没有,今天就讲解一下PowerDesigner连接 ...

  8. Android 线程的正确使用姿势

    进程优先级(Process Priority) 线程寄宿在进程当中,线程的生命周期直接被进程所影响,而进程的存活又和其优先级直接相关.在处理进程优先级的时候,大部分人靠直觉都能知道前台进程(Foreg ...

  9. GitLab + Jenkins + Docker + Kubernetes。

    目前方案是GitLab + Jenkins + Docker + Kubernetes. 方案的工作流程如下:首先,开发人员提交代码代码提交:随后,GitLab 会自动触发Jenkins job,Je ...

  10. JS错误捕获

    try/catch/finally错误捕获 try { //一旦try中出现错误,直接跳到执行catch的内容,执行完catch的内容,代码继续执行 throw new Error('错误'); // ...