java vs csharp
TRANSCRIPT
-
7/31/2019 Java vs Csharp
1/45
Java vs C#
Getting started code
Java
Java is a strongly-typed object-oriented languagedeveloped by SUN.
class Hello{
public static void
main(String[] args) {System.out.println("hello
, world");}
}//you must save the file with.java extension//from command line to compile it>javac Hello.java//generate a Hello.class file andrun it>java Hellohello, world
C#
C# is a strongly-typed object-orientedlanguagedeveloped by Microsoft.
class Hello{
static void Main() {
System.Console.WriteLine("hello, world");
}}//by convention, save the file with.cs extension//from command line to compile it>csc Hello.cs//generate a Hello.exe file and run it>Hellohello, world
Java vs C#
Keywords & Reserved Words
Java
52abstract do ifpackage synchronizedboolean double implementsprivate thisbreak else import
C#
77abstract as basebool breakbyte case catchchar checkedclass const continue
-
7/31/2019 Java vs Csharp
2/45
protected throwbyte extends instanceofpublic throwscase false intreturn transientcatch final interface
short truechar finally longstatic tryclass float nativestrictfp voidconst for newsuper volatilecontinue goto nullswitch whiledefault assert
C# doesn't haveassert boolean extendsfinal implementsinstanceof native packagestrictfp supersynchronized throwstrainsient
decimal defaultdelegate do doubleelse enumevent explicit externfalse finallyfixed float for
foreach gotoif implicit inint interfaceinternal is locklong namespacenew null objectoperator outoverride params privateprotected publicreadonly ref returnsbyte sealedshort sizeof stackallocstatic stringstruct switch this
throw truetry typeof uintulong uncheckedunsafe ushort usingvirtual voidvolatile while
Java doesn't haveas base boolchecked decimaldelegate enum eventexplicit externfixed foreach implicit
int internalis lock namespaceobject operatorout override paramsreadonly refsbyte sealed sizeofstackalloc stringstruct typeof uintulong uncheckedunsafe ushort usingvirtual
Java vs C#
Types
-
7/31/2019 Java vs Csharp
3/45
Java
type:
primitive typesreference types
numeric-type:integral typesfloating-point types
integral-type:byteshortintlongchar
floating-point-type:floatdouble
reference-type:class typesinterface typesarray types
Primitive types(8)booleanbytecharshortintlongfloatdouble
C#
type:
value typesreference types
numeric-type:integral typesfloating-point typesdecimal
integral-type:sbytebyteshortushortintuintlongulongchar
floating-point-type:floatdouble
reference-type:class typesinterface typesarray typesdelegate types
Predefined types orsystem-provided types:
objectstringsbyteshortintlongbyteushortuintulongfloatdoubleboolchardecimal
NOTE: value types include simple types,enum types and struct types.
-
7/31/2019 Java vs Csharp
4/45
Java vs C#
Access Modifiers
Java
public
Access not limitedprotected
Access limited to the packageor
subclass in a different package(no access modifier)
Access limited to the packageprivate
Access limited to thecontaining type
C#
public
Access not limitedprotected
Access limited to the containingclass or
types derived from the containingclass
protected internalAccess limited to this program ortypes derived from the containing
class(no access modifier)
by default it is privateinternal
Access limited to this programprivate
Access limited to the containingtype
Application Startup
Java
Only one:public static void main(String[] args){...}
C#
One of these:static void Main() {...}static void Main(string[] args)
{...}static int Main() {...}static int Main(string[] args){...}
-
7/31/2019 Java vs Csharp
5/45
Array Type
Java
int [,,] array = new int [3, 4,
5];//illegalint [1,1,1] = 5;//illegalint [][][] array = new int [3][4][5]; // okint [1][1][1] = 5;
class Test{
public static voidmain(String[] args) {
int[] a1; //single-dimensional array of int
int[][] a2; // 2-
dimensional array of intint[][][] a3; // 3-
dimensional array of intint[][] j2; //
"jagged" array: array of (arrayof int)
int[][][] j3; // arrayof (array of (array of int))
}}
class Test{
public static voidmain(String[] args) {int[] a1 = new int[] {1,
2, 3};int[][] a2 = new int[][]
{{1, 2, 3}, {4, 5, 6}};int[][][] a3 = new
int[10][20][30];int[][] j2 = new int[3]
[];j2[0] = new int[] {1, 2,
3};j2[1] = new int[] {1, 2,
3, 4, 5, 6};
j2[2] = new int[] {1, 2,3, 4, 5, 6, 7, 8, 9};
}}
class Test{
public static voidmain(String[] args) {
C#
int [,,] array = new int [3, 4, 5]; //
creates 1 arrayint [1,1,1] = 5;int [][][] array = new int [3][4][5]; // creates 1+3+12=16 arraysint [1][1][1] = 5;
class Test{
static void Main() {int[] a1; // single-
dimensional array of intint[,] a2; // 2-dimensional
array of int
int[,,] a3; // 3-dimensionalarray of int
int[][] j2; // "jagged"array: array of (array of int)
int[][][] j3; // array of(array of (array of int))
}}
class Test{
static void Main() {int[] a1 = new int[] {1, 2,
3}; int[,] a2 = new int[,] {{1, 2,3}, {4, 5, 6}};
int[,,] a3 = new int[10, 20,30];
int[][] j2 = new int[3][];j2[0] = new int[] {1, 2, 3};j2[1] = new int[] {1, 2, 3, 4,
5, 6};j2[2] = new int[] {1, 2, 3, 4,
5, 6, 7, 8, 9};}
}
class Test{
static void Main() {int[] arr = new int[5];for (int i = 0; i
Pre-processing directivesNone
C#
{ } [ ]( ) . , : ;+ - * / % & |^ ! ~
= < > ? ++ -- &&|| >== != = += -=*= /= %= &=|= ^= = ->C# doesn't have operator >>>
Pre-processing directives#
-
7/31/2019 Java vs Csharp
30/45
Out Parameters
Java
Java doesn't have out parameters.You can achieve C#'s functionalityby wrapping a primitiveto a class, or using an array tohold multiple returned values,and then call back that value viapass by reference.
class Test {
static void divide(int a, intb, int result, int remainder) {result = a / b;remainder = a % b;System.out.println(a +"/"+
b + " = "+ result +" r " + remainder);
}public static void
main(String[] args) {for (int i = 1; i < 10; i+
+)for (int j = 1; j < 10;
j++) {
int ans = 0, r = 0;divide(i, j, ans,
r);}
}}
class Test{
static void SplitPath(Stringpath, String dir, String name) {
int i = path.length();while (i > 0) {
char ch =path.charAt(i-1);
if (ch == '\\' || ch =='/' || ch == ':') break;
i--;}dir = path.substring(0, i);name = path.substring(i);
System.out.println(dir);
C#
C# provides the out keyword, whichindicates that you may pass inuninitialized variables and theywill be passed by reference.Note the calling method should markout keyword either.
class Test {
static void Divide(int a, intb, out int result, out intremainder) {
result = a / b;remainder = a % b;
}static void Main() {
for (int i = 1; i < 10; i++)
for (int j = 1; j < 10;j++) {
int ans, r;Divide(i, j, out
ans, out r);
Console.WriteLine("{0} / {1} = {2}r{3}", i, j, ans,r);
}}
}
using System;class Test{
static void SplitPath(stringpath, out string dir, out string
name) {int i = path.Length;while (i > 0) {
char ch = path[i - 1];if (ch == '\\' || ch ==
'/' || ch == ':') break;i--;
}dir = path.Substring(0, i);
-
7/31/2019 Java vs Csharp
31/45
System.out.println(name);}public static void
main(String[] args) {String dir="", name ="";SplitPath("c:\\Windows\\Sys
tem\\hello.txt", dir, name);}}
prints:c:\Windows\System\hello.txt
Thanks for Peter's suggestion. He suggests touse an array as one of possible solutions in
Java to replace outparameter feature in C#.
name = path.Substring(i);}static void Main() {
string dir, name;//like aplace holder
SplitPath("c:\\Windows\\Sys
tem\\hello.txt", out dir, outname);Console.WriteLine(dir);//ca
ll backConsole.WriteLine(name);
}}prints:
c:\Windows\System\hello.txt
Override
Java
class A{
public void F() {System.out.println("A.F");
}public void G() {
System.out.println("A.G");}
}class B extends A{
public void F() {System.out.println("B.F");
}public void G() {
System.out.println("B.G");}}class Test{
public static voidmain(String[] args) {
B b = new B();A a = b;
C#
using System;class A
{public void F() {
Console.WriteLine("A.F");}public virtual void G() {
Console.WriteLine("A.G");}
}class B: A{
new public void F() {Console.WriteLine("B.F");
}
public override void G() {Console.WriteLine("B.G");}
}class Test{
static void Main() {B b = new B();A a = b;
-
7/31/2019 Java vs Csharp
32/45
a.F();b.F();a.G();b.G();
}}
the output:B.FB.FB.GB.G
class A{
public void F() {System.out.println("A.F");
}}class B extends A{
public void F() {System.out.println("B.F");
}}class C extends B{
public void F() {System.out.println("C.F");
}}class D extends C{
public void F() {System.out.println("D.F");
}}class Test{
public static voidmain(String[] args) {
D d = new D();A a = new B();B b = new B();C c = d;a.F();b.F();c.F();d.F();
}}
the output:B.FB.FD.F
a.F();b.F();a.G();b.G();
}}
the output:A.FB.FB.GB.G
using System;class A{
public virtual void F() {Console.WriteLine("A.F");
}}class B: A{
public override void F() {Console.WriteLine("B.F");
}}class C: B{
new public virtual void F() {Console.WriteLine("C.F");
}}class D: C{
public override void F() {Console.WriteLine("D.F");
}}class Test{
static void Main() {D d = new D();A a = d;B b = d;C c = d;a.F();b.F();c.F();d.F();
}}the output:
B.FB.FD.FD.F
-
7/31/2019 Java vs Csharp
33/45
D.F
override modifierYou cannot override to be moreprivateclass A
{public void F() {}
}class B extends A{ public void F() {}//cannot beprivate}class C extends B{
public void F() {}}You can hide B.F by controllingruntime type
override modifierclass A{
public virtual void F() {}}class B: A
{ new private void F() {} // HidesA.F within B}class C: B{
public override void F() {} //Ok, overrides A.F}
Parameter Array
Java
Java doesn't have such feature.
public class Test{
public static void main (String[]args) {
System.out.println(add (newint[] {1,2,3,4}));
}
public static int add (int[]array) {
int sum = 0;for(int i = 0; i