C # vs Java

Source: Internet
Author: User
C # (c-sharp) is Microsoft's new programming language and is hailed as "the first component-oriented language in the C/C ++ family ". However, no matter what it claims, many people think that C # is more like a Java clone, or Microsoft is used to replace Java products. Is that true?

The comparison results in this article show that C # is not just as simple as a Java compatriot. If you are a Java developer and want to learn C # Or learn more about C #, you must invest the first 10 minutes in this article.

I. C #, C ++, and Java

The C # language specification is compiled by Microsoft's Anders hejlsberg and Scott wiltamuth. In the current Microsoft hype, C #, C ++, and Java are always interesting. Considering the public opinion trend of the current IT media, if you have long known that C # is closer to Java rather than C ++, it is not a big fuss. For the readers who just joined the discussion, table 1 below lets you make your own judgment. Obviously, the conclusion should be: Although Java and C # Are Not twins, the main characteristics of C # are closer to Java rather than C ++.

 
 
Table 1: Compare the most important functions of C #, C ++, and Java
 

 
Function
C #
C ++
Java
 

 
Inheritance
A single class can be inherited and multiple interfaces can be implemented.
Allow inheritance from multiple classes
A single class can be inherited and multiple interfaces can be implemented.
 

 
Interface implementation
Using the "interface" keyword
Using abstract classes
Using the "interface" keyword
 

 
Memory Management
Managed by the runtime environment, using the Garbage Collector
Manual management required
Managed by the runtime environment, using the Garbage Collector
 

 
Pointer
Yes, but it is only supported in the infrequent access mode. Usually replace pointer with reference
Supported, a very common function.
Not supported at all. Replace it with reference.
 

 
Form of source code compilation
. Net intermediate language (IL)
Executable code
Bytecode
 

 
Single public base class
Yes
No
Yes
 

 
Exception Handling
Exception Handling
Error returned
Exception Handling.
 

 
 

After learning about the important language functions summarized in Table 1, read on to learn about some important differences between C # and Java.

Ii. Comparison of language specifications

2.1. Simple data type

Primitive is called the value type in C #. C # has more predefined simple data types than Java. For example, C # has a unit, that is, an unsigned integer. Table 2 lists all the predefined Data Types of C:

 
 
Table 2: value types in C #
 

 
Type
Description
 

 
Object
All types of final base classes
 

 
String
String type. A string is a sequence of Unicode characters.
 

 
Sbyte
8-bit signed integer
 

 
Short
16-bit signed integer
 

 
Int
32-bit signed integer
 

 
Long
64-bit signed integer
 

 
Byte
8-bit unsigned integer
 

 
Ushort
16-bit unsigned integer
 

 
Uint
32-bit unsigned integer
 

 
Ulong
64-bit unsigned integer
 

 
Float
Single-precision floating point number type
 

 
Double
Double-precision floating point number type
 

 
Bool
Boolean Type; bool value: true or false
 

 
Char
Character type; a char value is a Unicode Character
 

 
Decimal
High-Precision decimal type with 28-digit valid numbers
 

 
 

2.2. Constant

Forget the static final modifier in Java. In C #, constants can be declared using the const keyword.

 
 
Public const int x = 55;
 

 
 

In addition, the C # designer adds the readonly keyword. If the constant value is not determined during compilation, you can use the readonly keyword. The readonly field can only be set through the initiatoror the constructor of the class.

2.3 Public class entry point

In Java, the entry point of a public class is a public static method named main. The parameter of the main method is a string object array, which has no return value. In C #, the main method becomes the public static method main (uppercase m). The parameter of the main method is also a String object array, and there is no return value, as shown in the following prototype declaration:

 
 
Public static void main (string [] ARGs)
 

 
 

However, the main method of C # is not limited to this. If you do not pass any parameters to the main method, you can use an overloaded version of the above main method, that is, the version without the parameter list. That is to say, the following main method is also a valid entry point:

 
 
Public static void main ()
 

 
 

In addition, if you think it is necessary, the main method can return an int. For example, the main method in the following code returns 1:

 
 
Using system;

Public class Hello {

Public static int main (){

Console. writeline ("done ");

Return 1;

}

}
 

 
 

In contrast, it is illegal to reload the main method in Java.

2.4 switch statement

In Java, the switch statement can only process integers. But the switch statement in C # is different, and it can also process character variables. Consider using the switch statement to process the C # code of string variables:

 
 
Using system;

Public class Hello {

Public static void main (string [] ARGs ){

Switch (ARGs [0]) {

Case "boss ":

Console. writeline ("good morning! We are ready to help you at any time! ");

Break;

Case "employee ":

Console. writeline ("good morning! You can get started! ");

Break;

Default:

Console. writeline ("good morning! Good luck! ");

Break;

}

}

}
 

 
 

Unlike the switch in Java, the switch statement in C # requires that each case block provide a break statement at the end of the block, or use goto to switch to other case labels in the switch.

2.5 foreach statement

The foreach statement enumerates each element in the set and executes a code block for each element in the set. See the following example.

 
 
Using system;

Public class Hello {

Public static void main (string [] ARGs ){

Foreach (string ARG in ARGs)

Console. writeline (ARG );

}

}

 
 

 
 

If you specify a parameter when running the execution file, such as "Hello Peter Kevin Richard", the output of the program will be the following lines of text:

 
 
Peter

Kevin

Richard
 

 
 

2.6. C # None >>> Shift Operator

C # supports unsigned variable types such as uint and ulong. Therefore, in C #, the right shift operator (">") has different processing methods for the unsigned and signed variable types (such as int and long. Remove uint and ulong to the right, discard the low position, and set the high position of the empty output to zero. For int and long variables, the ">" operator discards the low position. At the same time, only when the value of a variable is positive, ">" sets the high position of the empty output to zero. If ">" is a negative number, the high position of the empty output is set to 1.

There is no unsigned variable type in Java. Therefore, we use the ">>>" operator to introduce a negative number when shifting the right; otherwise, we use the ">>" operator.

2.7. Goto keywords

Java does not use the goto keyword. In C #, Goto allows you to switch to the specified tag. However, C # treats Goto With a very cautious attitude. For example, it does not allow goto to be transferred to the inside of the statement block. In Java, you can replace the Goto in C # With the break or continue of the label-containing statement.

2.8 declare an array

In Java, the array declaration method is very flexible. In fact, many declaration methods are legal. For example, the following lines of code are equivalent:

 
 
Int [] x = {0, 1, 2, 3 };

Int X [] = {0, 1, 2, 3 };
 

 
 

However, in C #, only the first line of code is valid. [] cannot be placed after the variable name.

2.9. Package

In C #, a package is called a namespace. The keyword for introducing the namespace into the C # program is "using ". For example
System; "This statement introduces the system namespace.

However, unlike Java, C # allows you to specify an alias for a namespace or a class in a namespace:

 
 
Using theconsole = system. Console;

Public class Hello {

Public static void main (){

Theconsole. writeline ("use alias ");

}

}
 

 
 

In terms of concept, Java packages are similar to. Net namespaces. However, the two are implemented in different ways. In Java, the package name is also an actual entity, which determines the directory structure of the. Java file. In C #, the physical package and logical name are completely separated. That is to say, the namespace name does not affect the physical packaging method. In C #, each source code file can belong to multiple namespaces and can accommodate multiple public classes.

The entity in. NET is called assembly ). Each Assembly contains a manifest structure. Manifest lists the files contained in an assembly, controls which types and resources are exposed outside the assembly, and maps references to these types and resources to files containing these types and resources. An assembly is self-contained. An assembly can be placed within a single file or divided into multiple files .. This encapsulation mechanism of net solves the problems faced by DLL files, that is, the notorious DLL
Hell problems.

2.10 default package

In Java, the Java. lang package is the default package, which is automatically included without explicit import. For example, to output some text to the console, you can use the following code:

 
 
System. Out. println ("Hello world from Java ");
 

 
 

The default package does not exist in C. To output text to the console, use the writeline method of the console object in the system namespace. However, you must explicitly import all classes. The Code is as follows:

 
 
Using system;

Public class Hello {

Public static void main (){

Console. writeline ("Hello world from C #");

}

}
 

 
 

2.11 object-oriented

Both Java and C # are fully object-oriented languages. These two languages are close to each other in terms of the three principles of object-oriented programming.

Inheritance: both languages support a single inheritance of classes, but classes can implement multiple interfaces. All classes are inherited from a common base class.

Encapsulation and visibility: whether in Java or C #, you can determine whether class members are visible. In addition to the internal access modifier of C #, the visibility mechanisms of the two are very similar.

Polymorphism: both Java and C # support some forms of polymorphism, And the implementation methods are very similar.

2.12. Accessibility

Each member of the class has a specific type of accessibility. The access modifier in C # basically corresponds to the access modifier in Java, but there is an extra internal. In short, C # has five types of accessibility:

Public: Members can access any code.

Protected: A member can only be accessed from a derived class.

Internal: members can only access from within the same assembly.

Protected internal: A member can only be accessed from a derived class in the same assembly.

PRIVATE: members can only be accessed within the current class.

2.13. derived class

In Java, we use the keyword "extends" to implement inheritance. C # uses C ++ class-derived syntax. For example, the following code shows how to derive a parent class control to create a new class button:

 
 
Public class button: Control {..}
 

 
 

2.14. Final class

Because the final keyword does not exist in C #, if you want a class to be no longer derived, you can use the sealed keyword, as shown in the following example:

 
 
Sealed class finalclass {..}
 

 
 

2.15 Interface

The interface concept is very similar in C # and Java. The key word of an interface is interface. An interface can expand one or more other interfaces. By convention, the interface name starts with the uppercase letter "I. The following code is an example of the C # interface, which is exactly the same as the interface in Java:

 
 
Interface ishape {void draw ();}
 

 
 

The syntax of the extension interface is the same as that of the extension class. For example, the ishctangularshape interface in the following example extends the ishape interface (that is, the irectangularshape interface is derived from the ishape interface ).

 
 
Interface irectangularshape: ishape {int getwidth ();
}
 

 
 

If you derive from two or more interfaces, the names of the parent interfaces are separated by commas, as shown in the following code:

 
 
Interface inewinterface: iparent1, iparent2 {}
 

 
 

However, unlike Java, interfaces in C # cannot contain fields ).

In addition, in C #, all methods in the interface are public methods by default. In Java, a method declaration can carry a public modifier (even if this is not necessary), but in C #, explicitly specifying a public modifier for an interface method is invalid. For example, the following C # interface will generate a compilation error.

 
 
Interface ishape {public void draw ();}
 

 
 

2.16. Is and as operators

The is Operator in C # is the same as the instanceof operator in Java. Both of them can be used to test whether the instance of an object belongs to a specific type. In Java, there is no operator equivalent to the as operator in C. The as operator is very similar to the is operator, but it is more aggressive: If the type is correct, the as operator will try to convert the referenced object to the target type; otherwise, it sets the variable reference to null.

To understand the as operator correctly, consider the use of the is operator in the following example. This example contains an ishape interface and two rectangle and circle classes that implement the ishape interface.

 
 
Using system;

Interface ishape {

Void draw ();

}

Public class rectangle: ishape {

Public void draw (){

}

Public int getwidth (){

Return 6;

}

}

Public class circle: ishape {

Public void draw (){

}

Public int getradius (){

Return 5;

}

}

Public class letsdraw {

Public static void main (string [] ARGs ){

Ishape shape = NULL;

If (ARGs [0] = "rectangle "){

Shape = new rectangle ();

}

Else if (ARGs [0] = "circle "){

Shape = new circle ();

}

If (shape is rectangle ){

Rectangle rectangle = (rectangle) shape;

Console. writeline ("width:" + rectangle. getwidth ());

}

If (shape is circle ){

Circle = (circle) shape;

Console. writeline ("radius:" + circle. getradius ());

}

}

}

 
 

 
 

After the code is compiled, you can enter "rectangle" or "circle" as the parameter of the main method. If the user inputs "circle", the shape is instantiated into a circle type object. If the user inputs "rectangle ", shape is instantiated as a rectangle object. Then, the program uses the is operator to test the shape variable type. If the shape is a rectangle, the shape is converted into a rectangle object. We call its getwidth method. If the shape is a circle, the shape is converted into a circle object. We call its getradius method.

If the as operator is used, the above Code can be changed to the following form:

 
 
Using system;

Interface ishape {

Void draw ();

}

Public class rectangle: ishape {

Public void draw (){

}

Public int getwidth (){

Return 6;

}

}

Public class circle: ishape {

Public void draw (){

}

Public int getradius (){

Return 5;

}

}

Public class letsdraw {

Public static void main (string [] ARGs ){

Ishape shape = NULL;

If (ARGs [0] = "rectangle "){

Shape = new rectangle ();

}

Else if (ARGs [0] = "circle "){

Shape = new circle ();

}

Rectangle rectangle = shape as rectangle;

If (rectangle! = NULL ){

Console. writeline ("width:" + rectangle. getwidth ());

}

Else {

Circle = shape as circle;

If (circle! = NULL)

Console. writeline ("radius:" + circle. getradius ());

}

}

}

 
 

 
 

In the bold part of the code above, we use the as operator to convert shape to a rectangle object without testing the shape object type. If a shape is a rectangle, the shape is converted to a rectangle object and saved to the rectangle variable. Then, we call its getwidth method. If this conversion fails, we will try again. This time, the shape is converted to a circle type object and saved to the Circle variable. If shape is indeed a circle object, circle references a circle object. We call its getradius method.

2.17 Database

C # does not have its own class library. However, C # shares the. NET class library. Of course, the. NET class library can also be used in other. NET languages, such as VB. NET or JScript. net. It is worth mentioning that the stringbuilder class is a supplement to the string class. The stringbuilder class is very similar to the stringbuffer class of Java.

2.18. Garbage Collection

C ++ has made us realize how inefficient and time-consuming manual memory management is. When you create an object in C ++, you must manually remove the object. The more complex the code is, the more difficult the task is. Java uses the Garbage Collector to solve this problem. The Garbage Collector collects unused objects and releases the memory. C # also uses this method. It should be said that if you are also developing a new OOP language, it is a natural choice to follow this path. C # still retains the manual memory management method of C ++, which is suitable for use in extremely important scenarios of speed, which is not allowed in Java.

2.19 Exception Handling

If you hear that C # uses an exception handling mechanism similar to Java, you will not be surprised, right? In C #, all exceptions are derived from an exception class (sounds familiar ?) In addition, as in Java, you are also familiar with try and catch statements. The exception class belongs to. net.
Part of the system namespace.

Iii. functions not available in Java

C # was born after the maturity of Java. Therefore, it is not surprising that C # has some excellent functions that Java (currently) does not yet have.

3.1 enumerator

The Enumerator is a collection of related constants. Specifically, the enum Type Declaration defines a type name for a group of associated symbolic constants. For example, you can create an enumerator named fruit (fruit) and use it as a variable value type, in this way, the possible value range of the variable is limited to the value that appears in the enumerator.

 
 
Public class demo {

Public Enum fruit {

Apple, banana, cherry, durian

}

Public void process (fruit ){

Switch (fruit ){

Case fruit. Apple:

...

Break;

Case fruit. Banana:

...

Break;

Case fruit. Cherry:

...

Break;

Case fruit. durian:

...

Break;

}

}

}

 
 

 
 

In the process method in the above example, although you can use int as the type of myvar variable, after using the enumerator fruit, the value range of the variable is limited to the values of Applet, banana, cherry, and durian. Compared with int, Enum is more readable and self-explanatory.

3.2 Structure

The structure (struct) is similar to the class. However, a class is created in the heap as a reference type, and a structure is a value type, which is stored in the stack or embedded. Therefore, as long as you use it with caution, the structure is faster than the class. The structure can implement interfaces and have Members like a class, but the structure does not support inheritance.

However, replacing classes with structures may cause heavy losses. This is because the structure is passed as a value. Because the value is copied to a new location, passing a "Obese" structure requires a large overhead. For a class, you only need to pass its reference when passing it.

The following is a structure example. Note that it is very similar to a class. If you replace the word "struct" with "class", you will get a class.

 
 
Struct point {

Public int X, Y;

Public point (int x, int y ){

This. x = X;

This. Y = y;

}

}

 
 

 
 

3.3 attributes

In addition to fields, the C # class can also have properties ). An attribute is a name feature associated with a class or object. Attribute is a natural extension of the domain-both are class members with types and names. However, unlike a domain, an attribute does not represent a storage location. On the contrary, an attribute has an accessor, which defines the code that must be executed when reading or writing attribute values. Therefore, attributes provide a mechanism to associate actions with read and write object attribute values, and allow attribute values to be calculated.

In C #, attributes are defined using the attribute declaration syntax. The first part of the attribute declaration syntax is very similar to the domain declaration. The second part includes a set process and/or a get process. For example, in the following example, the propertydemo class defines a prop attribute.

 
 
Public class propertydemo {

Private string prop;

Public String prop {

Get {

Return prop;

}

Set {

Prop = value;

}

}

}

 
 

 
 

If the property allows both reading and writing, such as the prop attribute of the propertydemo class, it has both get and set access processes. When we read the attribute value, the get access process is called; when we write the attribute value, the Set access process is called. In the set access process, the new attribute value is given in an implicit value parameter.

Attributes can be read and written in the same way as the method used to read and write fields. For example, the following code instantiates a propertydemo class and then writes and reads its prop attribute.

 
 
Propertydemo Pd = new propertydemo ();

PD. Prop = "123"; // set

String S = Pd. Prop; // get

 
 

 
 

3.4 PASS Parameters of simple data type in Reference Mode

In Java, when you pass a simple data type value as a parameter to a method, the parameter is always passed as a value -- that is, the system creates a copy of the parameter value for the called method. In C #, you can use a reference to pass a simple data type value. At this point, the called method will directly use the value passed to it-that is, if the parameter value is modified within the called method, the original variable value will also change.

When passing values in C # as a reference, we use the ref keyword. For example, if you compile and run the following code, you will see output result 16 on the console. Note how the I value is changed after being passed to processnumber.

 
 
Using system;

Public class passbyreference {

Public static void main (string [] ARGs ){

Int I = 8;

Processnumber (Ref I );

Console. writeline (I );

}

Public static void processnumber (ref Int J ){

J = 16;

}

}

 
 

 
 

In C #, there is also a keyword out that allows parameter passing by reference, which is similar to ref. However, when using out, the variables passed as parameters do not have to have known values before being passed. In the preceding example, if the integer I is not initialized before being passed to the processnumber method, the code will fail. If you replace ref with out, you can pass an uninitialized value, as shown in the following modified example.

 
 
Using system;

Public class passbyreference {

Public static void main (string [] ARGs ){

Int I;

Processnumber (Out I );

Console. writeline (I );

}

Public static void processnumber (Out Int J ){

J = 16;

}

}

 
 

 
 

After modification, although the I value is not initialized before being passed to the processnumber method, the passbyreference class can be smoothly compiled.

3.5. C # reserved pointer

For developers who feel that they can use pointers just right and are willing to perform manual memory management, in C, they can still use the "old" pointer that is neither secure nor easy to use to improve program performance. C # provides the ability to support "unsafe" (unsafe) Code. This code can directly operate on pointers and "fix" objects to temporarily prevent the garbage collector from moving objects. From the developer's or user's perspective, this support for "insecure" code is actually a security function. The "insecure" code must be explicitly marked with the keyword "unsafe", so developers cannot use the "insecure" code unintentionally. At the same time, the C # compiler works with the execution engine to ensure that "insecure" Code cannot be disguised as secure code.

 
 
Using system;

Class usepointer {

Unsafe static void pointerdemo (byte [] ARR ){

.

.

}

}

 
 

 
 

The Unsafe code in C # is suitable for use in the following scenarios: when the speed is extremely important, or when the object needs to interact with existing software (such as COM object or dll c code.

3.6 proxy

The proxy (delegate) can be seen as a function pointer in C ++ or other languages. However, unlike function pointers, the proxies in C # Are object-oriented, type-safe, and reliable. In addition, the function pointer can only be used to reference static functions, but the proxy can reference both static methods and instance methods. The proxy is used to encapsulate callable methods. You can write a method in the class and create a proxy on the method. Then the proxy can be passed to the second method. In this way, the second method can call the first method.

The proxy is a reference type derived from the public base class system. Delegate. There are three steps to define and use a proxy: declare, create an instance, and call. The proxy uses delegate to declare the syntax. For example, a proxy that does not need parameters and does not return values can be declared using the following code:

 
 
Delegate void thedelegate ();
 

 
 

The syntax for creating a proxy instance is to use the new keyword and reference an instance or class method. This method must meet the characteristics specified by the proxy. Once a proxy instance is created, you can call it by calling the method syntax.

3.7. Packaging and unpackaging

In object-oriented programming languages, we usually use objects. However, to increase the speed, C # also provides simple data types. Therefore, the C # program contains both a large number of objects and a large number of values. In this environment, it is always unavoidable to allow the two to work collaboratively. You must have a way to allow the reference and value to communicate.

In the C # And. Net runtime environments, this "communication" problem is solved through boxing and unboxing. Packaging is a process that makes the value type look like a reference type. When a value type (simple data type) is used for a requirement or an object that can be used, the packaging operation is automatically performed. To wrap a value-type value, assign an object instance and copy the value-type value to the object instance.

The action to unwrap is opposite to the action to unwrap. It converts a reference type to a value type. The unwrapped procedure includes checking and confirming that the object instance is indeed a packaged value of the given value-type, and then copying the value from the object instance.

Java handles this problem in a slightly different way. Java provides a class package for each simple data type. For example, use the integer class to encapsulate the int type and the byte class to encapsulate the byte type.

[Conclusion] This article compares C # and Java. These two languages are very similar. However, C # is a Java clone. Object-oriented and intermediate languages are nothing new. If you want to design a new object-oriented language that must run in a managed security environment, won't you come up with something similar to C?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.