首页 后端开发 C#.Net教程 JAVA与C#比较的代码详细介绍

JAVA与C#比较的代码详细介绍

Mar 03, 2017 pm 01:41 PM

JavaProgram StructureC#
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 + "!");
      }
   }
}
登录后复制

JavaCommentsC#
// Single line
/* Multiple
    line  */
/** Javadoc documentation comments */
登录后复制

// Single line
/* Multiple
    line  */
/// XML comments on a single line
/** XML comments on multiple lines */
登录后复制

JavaData TypesC#


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)
登录后复制



JavaConstantsC#
// 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;
登录后复制

JavaEnumerationsC#


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"
登录后复制



JavaOperatorsC#


Comparison
==  <  >  <=  >=  !=
Arithmetic
+  -  *  /
%  (mod)
/   (integer pision 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 pision if both operands are ints)
Math.Pow(x, y)
Assignment
=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --
Bitwise
&  |  ^   ~  <<  >>
Logical
&&  ||  &  |   ^   !
Note: && and || perform short-circuit logical evaluations
String Concatenation
+
登录后复制



JavaChoicesC#


greeting = age < 20 ? "What&#39;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&#39;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
}
登录后复制



JavaLoopsC#


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);
登录后复制



JavaArraysC#
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;
登录后复制

JavaFunctionsC#
// 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&#39;t need initializing
TestFunc(a, ref b, out c, p1, refp2);
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
登录后复制



JavaStringsC#


// 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"
登录后复制



JavaException HandlingC#


// 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
}
登录后复制



JavaNamespacesC#


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;
登录后复制



JavaClasses / InterfacesC#


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 {
   ...
}
登录后复制



JavaConstructors / DestructorsC#


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&#39;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.
  }
}
登录后复制



JavaObjectsC#


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&#39;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&#39;s type: " + obj.GetType().ToString()); 
if (obj is SuperHero) 
  Console.WriteLine("Is a SuperHero object.");
登录后复制



JavaPropertiesC#


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++;
登录后复制



JavaStructsC#


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"
登录后复制

JavaConsole I/OC#
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&#39;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());
登录后复制

JavaFile I/OC#


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#比较的代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

突破或从Java 8流返回? 突破或从Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

c#多线程和异步的区别 c#多线程和异步的区别 Apr 03, 2025 pm 02:57 PM

多线程和异步的区别在于,多线程同时执行多个线程,而异步在不阻塞当前线程的情况下执行操作。多线程用于计算密集型任务,而异步用于用户交互操作。多线程的优势是提高计算性能,异步的优势是不阻塞 UI 线程。选择多线程还是异步取决于任务性质:计算密集型任务使用多线程,与外部资源交互且需要保持 UI 响应的任务使用异步。

Java程序查找胶囊的体积 Java程序查找胶囊的体积 Feb 07, 2025 am 11:37 AM

胶囊是一种三维几何图形,由一个圆柱体和两端各一个半球体组成。胶囊的体积可以通过将圆柱体的体积和两端半球体的体积相加来计算。本教程将讨论如何使用不同的方法在Java中计算给定胶囊的体积。 胶囊体积公式 胶囊体积的公式如下: 胶囊体积 = 圆柱体体积 两个半球体体积 其中, r: 半球体的半径。 h: 圆柱体的高度(不包括半球体)。 例子 1 输入 半径 = 5 单位 高度 = 10 单位 输出 体积 = 1570.8 立方单位 解释 使用公式计算体积: 体积 = π × r2 × h (4

xml格式怎么打开 xml格式怎么打开 Apr 02, 2025 pm 09:00 PM

用大多数文本编辑器即可打开XML文件;若需更直观的树状展示,可使用 XML 编辑器,如 Oxygen XML Editor 或 XMLSpy;在程序中处理 XML 数据则需使用编程语言(如 Python)与 XML 库(如 xml.etree.ElementTree)来解析。

如何在Spring Tool Suite中运行第一个春季启动应用程序? 如何在Spring Tool Suite中运行第一个春季启动应用程序? Feb 07, 2025 pm 12:11 PM

Spring Boot简化了可靠,可扩展和生产就绪的Java应用的创建,从而彻底改变了Java开发。 它的“惯例惯例”方法(春季生态系统固有的惯例),最小化手动设置

xml如何转化为word xml如何转化为word Apr 03, 2025 am 08:15 AM

有三种将 XML 转换为 Word 的方法:使用 Microsoft Word、使用 XML 转换器或使用编程语言。

c#多线程防卡死方法 c#多线程防卡死方法 Apr 03, 2025 pm 02:54 PM

在 C# 中避免多线程 "卡死" 的方法如下:避免在 UI 线程上执行耗时操作。使用 Task 和 async/await 异步执行耗时操作。通过 Application.Current.Dispatcher.Invoke 在 UI 线程上更新 UI。使用 CancellationToken 控制任务取消。合理利用线程池,避免过度创建线程。注重代码可读性和可维护性,便于调试。在每个线程中记录日志,以方便调试。

c和c#的区别和联系有哪些 c和c#的区别和联系有哪些 Apr 03, 2025 pm 10:36 PM

C和C#虽有类似之处,但截然不同:C是面向过程、手动内存管理、平台依赖的语言,用于系统编程;C#是面向对象、垃圾回收、平台独立的语言,用于桌面、Web应用和游戏开发。

See all articles