JAVA와 C#의 코드 비교에 대한 자세한 소개
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'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 } 로그인 후 복사 |
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'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'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'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."); 로그인 후 복사 |
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'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)!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

멀티 스레딩과 비동기식의 차이점은 멀티 스레딩이 동시에 여러 스레드를 실행하는 반면, 현재 스레드를 차단하지 않고 비동기식으로 작업을 수행한다는 것입니다. 멀티 스레딩은 컴퓨팅 집약적 인 작업에 사용되며 비동기식은 사용자 상호 작용에 사용됩니다. 멀티 스레딩의 장점은 컴퓨팅 성능을 향상시키는 것이지만 비동기의 장점은 UI 스레드를 차단하지 않는 것입니다. 멀티 스레딩 또는 비동기식을 선택하는 것은 작업의 특성에 따라 다릅니다. 계산 집약적 작업은 멀티 스레딩을 사용하고 외부 리소스와 상호 작용하고 UI 응답 성을 비동기식으로 유지 해야하는 작업을 사용합니다.

Java는 초보자와 숙련된 개발자 모두가 배울 수 있는 인기 있는 프로그래밍 언어입니다. 이 튜토리얼은 기본 개념부터 시작하여 고급 주제를 통해 진행됩니다. Java Development Kit를 설치한 후 간단한 "Hello, World!" 프로그램을 작성하여 프로그래밍을 연습할 수 있습니다. 코드를 이해한 후 명령 프롬프트를 사용하여 프로그램을 컴파일하고 실행하면 "Hello, World!"가 콘솔에 출력됩니다. Java를 배우면 프로그래밍 여정이 시작되고, 숙달이 깊어짐에 따라 더 복잡한 애플리케이션을 만들 수 있습니다.

캡슐은 3 차원 기하학적 그림이며, 양쪽 끝에 실린더와 반구로 구성됩니다. 캡슐의 부피는 실린더의 부피와 양쪽 끝에 반구의 부피를 첨가하여 계산할 수 있습니다. 이 튜토리얼은 다른 방법을 사용하여 Java에서 주어진 캡슐의 부피를 계산하는 방법에 대해 논의합니다. 캡슐 볼륨 공식 캡슐 볼륨에 대한 공식은 다음과 같습니다. 캡슐 부피 = 원통형 볼륨 2 반구 볼륨 안에, R : 반구의 반경. H : 실린더의 높이 (반구 제외). 예 1 입력하다 반경 = 5 단위 높이 = 10 단위 산출 볼륨 = 1570.8 입방 단위 설명하다 공식을 사용하여 볼륨 계산 : 부피 = π × r2 × h (4

간단해진 Java: 강력한 프로그래밍을 위한 초보자 가이드 소개 Java는 모바일 애플리케이션에서 엔터프라이즈 수준 시스템에 이르기까지 모든 분야에서 사용되는 강력한 프로그래밍 언어입니다. 초보자의 경우 Java의 구문은 간단하고 이해하기 쉬우므로 프로그래밍 학습에 이상적인 선택입니다. 기본 구문 Java는 클래스 기반 객체 지향 프로그래밍 패러다임을 사용합니다. 클래스는 관련 데이터와 동작을 함께 구성하는 템플릿입니다. 다음은 간단한 Java 클래스 예입니다. publicclassPerson{privateStringname;privateintage;

Spring Boot는 강력하고 확장 가능하며 생산 가능한 Java 응용 프로그램의 생성을 단순화하여 Java 개발에 혁명을 일으킨다. Spring Ecosystem에 내재 된 "구성에 대한 협약"접근 방식은 수동 설정, Allo를 최소화합니다.

대부분의 텍스트 편집기를 사용하여 XML 파일을여십시오. 보다 직관적 인 트리 디스플레이가 필요한 경우 Oxygen XML 편집기 또는 XMLSPy와 같은 XML 편집기를 사용할 수 있습니다. 프로그램에서 XML 데이터를 처리하는 경우 프로그래밍 언어 (예 : Python) 및 XML 라이브러 (예 : XML.etree.elementtree)를 사용하여 구문 분석해야합니다.

C#.NET은 동시, 병렬 및 멀티 스레드 프로그래밍을위한 강력한 도구를 제공합니다. 1) 스레드 클래스를 사용하여 스레드를 생성하고 관리합니다. 2) 작업 클래스는 스레드 풀을 사용하여 자원 활용을 개선하기 위해 나사산을 통해 병렬 컴퓨팅을 구현합니다. 4) ASYNC/AWAIT 및 작업을 통해 병렬 컴퓨팅을 구현합니다. ASYNC/AWAIT 및 TASK. ANDAL에서 데이터를 얻고 프로세스하는 데 사용되면 5) 스레드 풀을 사용하지 않으면 스레드 풀을 사용하고 성능을 발휘합니다.
