Comparison between Java and C ++, Java

Source: Internet
Author: User

Comparison between Java and C ++, Java

In fact, Java is derived from C ++.

 

There are still some significant differences between C ++ and Java. In this case, these differences represent significant technological advances. Once we understand these differences, we will understand why Java is a good programming language. This article will guide you to understand some important features used to differentiate Java and C ++.

 

(1) The biggest obstacle lies in speed: The interpreted Java is about 20 times slower than the execution speed of C. The Java language cannot be compiled in any way. Some quasi-real-time compilers have emerged, which can significantly speed up. Of course, we have reason to think that there will be pure inherent compilers suitable for more popular platforms, but without those compilers, due to speed restrictions, some problems must be solved by Java.


(2) Like C ++, Java also provides two types of annotations.

 

(3) All things must be placed into a class. No global function or global data exists. If you want to obtain functions equivalent to global functions, you can consider placing static methods and static data into a class. Note that there is no such thing as structure, enumeration, or union. Everything is only "Class )!


(4) All methods are defined in the class subject. From the perspective of C ++, it seems that all functions are embedded, but this is not the case.


(5) in Java, class definitions take almost the same form as C ++. However, there is no semicolon indicating the end. There is no class declaration in the form of class foo, only class definition.

1 class aType () 2 void aMethod () {/* method subject */} 3}

 

(6) There is no scope operator ":" in Java. Java uses the DoT number to do everything, but you don't need to consider it, because it can only define elements in one class. Even the method definitions must be within a class, so there is no need to specify the scope. One difference we noticed is the call to the static method: Use ClassName. methodName (). In addition, the package name is created with the DoT number, and part of the "# include" function of C ++ can be implemented with the import keyword. For example, the following statement:

1 import java.awt.*;

(# Include is not directly mapped to import, but it feels similar when used .)

 

(7) similar to C ++, Java contains a series of Primitive types for more efficient access. In Java, these types include boolean, char, byte, short, int, long, float, and double. The size of all master types is inherent and independent from the specific machine (considering the porting problem ). This will certainly have a certain impact on performance, depending on different machines. The type check and requirements become more demanding in Java. For example:
■ The conditional expression can only be of the boolean Type and cannot be an integer.
■ The result of an expression like X + Y must be used; the "side effect" cannot be implemented only by "X + Y ".


(8) The char (character) type uses the internationally accepted 16-bit Unicode Character Set, so it can automatically express characters in most countries.


(9) Static referenced strings are automatically converted to String objects. Unlike C and C ++, there is no independent static character array string for use.

 

(10) added three right shift operators ">>>" in Java, which are similar to the "logic" right shift operator and can insert zero values at the end. ">" Inserts the symbol bit (that is, "arithmetic" shift) at the same time as the shift ).


(11) although similar on the surface, compared with C ++, Java arrays use a rather different structure and have unique behavior. There is a read-only length Member, through which you can know the size of the array. Once the array boundary is exceeded, an exception is automatically discarded during runtime checks. All arrays are created in the memory "heap". We can allocate one array to another (just simply copy the array handle ). The array identifier belongs to the first-level object, and all its methods usually apply to all other objects.


(12) all objects not of the primary type can only be created using the new command. Unlike C ++, Java does not have the corresponding command to "create an object not of the primary type on the stack. All primary types can only be created on the stack, and the new command is not used. All major classes have their own "encapsulation" class, therefore, you can use new to create equivalent Objects Based on the memory "heap" (the primary array is an exception: they can be allocated through set initialization like C ++, or use new ).


(13) do not declare in advance in Java. To use a class or method before a definition, you just need to use it directly-the compiler will ensure that the appropriate definition is used. Therefore, unlike in C ++, we will not encounter any problems involving early reference.

 

(14) Java does not have a preprocessing machine. To use the class in another library, you only need to use the import command and specify the library name. There is no macro similar to the preprocessing machine.


(15) Java uses packages instead of namespaces. Because everything is put into a class, and a mechanism called "encapsulation" is adopted, it can perform operations similar to namespace decomposition on the class name, therefore, the naming problem is no longer included in our consideration. Data packets are collected by the component under a separate database name. We only need to simply "import" a package, and the rest of the work will be automatically completed by the compiler.


(16) The object handle defined as a class member is automatically initialized to null. The initialization of basic class data members ensures reliability in Java. If Initialization is not explicitly performed, they will get a default value (zero or equivalent ). Explicit initialization: either define them within the class or define them in the builder. The syntax used is easier to understand than the C ++ syntax, And it is fixed for static and non-static members. We do not need to define the storage mode of static members from outside, which is different from that of C ++.


(17) In Java, there are no pointers like C and C ++. When you create an object with new, a reference is obtained. For example:

1 String s = new String("howdy");

However, C ++ references must be initialized at creation and cannot be redefined to a different location. However, Java references are not limited to the creation time. They can be defined as needed, eliminating some of the pointer requirements. Another reason for using a large number of pointers in C and C ++ is to point to any memory location (which also makes them insecure, this is also the reason why Java does not provide this support ). Pointers are usually seen as an effective way to move around in an array of basic variables. Java allows us to achieve the same goal in a safer form. The ultimate solution to pointer problems is the "inherent method ". When a pointer is passed to a method, it usually does not cause too many problems, because there are no global functions and only classes. In addition, we can pass references to objects. The Java language initially claims that it "does not use pointers at all !" But as many programmers question how to work without pointers? Then I declared "using restricted Pointers ". You can determine whether it is a pointer. However, no matter what the situation is, there is no "arithmetic" pointer ".


(18) Java provides Constructor similar to C ++ ). If you do not define one, you will get a default builder. If a non-default builder is defined, the default builder will not be automatically defined for us. This is the same as C ++. Note that there is no replication builder, because all the independent variables are passed by reference.


(19) There is no Destructor in Java ). The variable does not have a "Scope" issue. The "Existence time" of an object is determined by the object's existence time, not by the garbage collector. There is a finalize () method that is a member of every class. It is similar to the "Breaker" of C ++ to some extent ". However, finalize () is called by the garbage collector and is only responsible for releasing "resources" (such as open files, sockets, ports, URLs, and so on ). To do something in a specific place, You must create a special method and call it. You cannot rely on finalize (). On the other hand, all objects in C ++ are damaged (or "should"), but not all objects in Java are collected as "garbage. Because Java does not support the concept of destructor, you must be cautious when necessary to create a clearing method. In addition, all cleanup methods must be explicitly called for basic classes and member objects in the class.


(20) Java has a method "overload" mechanism. its working principle is almost the same as that of C ++ functions.


(21) Java does not support default independent variables.


(22) No goto in Java. It adopts the "break tag" or "continue standard" unconditional jump mechanism to jump out of the current multiple nested loops.


(23) Java adopts a single hierarchical structure, so all objects are inherited from the root class objects. In C ++, we can start a new inheritance tree anywhere, so we often see a "Forest" that contains a large number of trees ". In Java, we have only one hierarchical structure. Although this seems to have caused restrictions on the surface, as we know that each Object must have at least one Object interface, we often get more powerful capabilities. C ++ currently seems to be the only OO language that does not force a single structure.


(24) Java does not have templates or other forms of parameterized types. It provides a series of collections: Vector, Stack, and Hashtable to accommodate Object references. With these collections, our series of requirements can be met. However, these collections are not designed for fast calls like the real phenomenon C ++ "Standard Template Library" (STL. The new collection in Java 1.2 is more complete, but it still does not have the efficient use of authentic templates.


(25) "Garbage Collection" means that there will be much fewer memory vulnerabilities in Java, but it is not completely impossible (if you call an inherent method for allocating buckets, the garbage collector cannot track and monitor it ). However, many memory and resource vulnerabilities are caused by improper finalize, or because a resource is released at the end of an allocated block (the "Breaker" is especially convenient at this time ). The garbage collector is a great progress on the basis of C ++, which makes many programming problems invisible. However, it is not suitable for a few spam collectors. However, the many advantages of the garbage collector make this disadvantage insignificant.


(26) Java has built-in support for multithreading. Using a Special Thread class, we can create a new Thread by inheritance (giving up the run () method ). If the synchronized keyword is used as a Type delimiter of the method, mutual exclusion occurs at the object level. At any given time, only one thread can use the synchronized Method of an object. On the other hand, after a synchronized method enters, it will first "Lock" the object to prevent any other synchronized Method from using that object again. Only after exiting this method will the object be "Unlocked ". Among threads, we are still responsible for implementing more complex synchronization mechanisms by creating our own "Monitor" class. The recursive synchronized method works properly. If the thread priority level is the same, the "slice" of the time cannot be guaranteed.

 

(27) we don't control the declared code block like C ++, but place the access qualifiers (public, private, and protected) into the definition of each class member. If no explicit (explicit) qualifier is specified, the default value is "friendly ). This means that other elements in the same package can also access it (equivalent to the "friends"-friends of C ++), but cannot be accessed by any element outside the package. Class -- and each method in the class -- has an access qualifier to determine whether it can be "visible" outside the file ". Private keywords are rarely used in Java, because "friendly" access is usually more useful than rejecting access from other classes in the same package. However, in a multi-threaded environment, the proper use of private is very important. The protected keyword in Java means that "It can be accessed by the successor or by other elements in the package ". Note that Java does not have an element equivalent to the protected keyword of C ++, and the latter means that "only the successor can access" (previously this purpose can be achieved using "private protected, however, the combination of this pair of keywords has been canceled ).


(28) Nested classes. In C ++, nesting classes helps to hide names and facilitate Code Organization (but the "namespace" of C ++ makes name hiding redundant ). The concept of "encapsulation" or "packaging" in Java is equivalent to the namespace of C ++, so it is no longer a problem. Java 1.1 introduces the concept of "internal class", which is used to keep a handle pointing to an external class secretly-when creating an internal class object. This means that internal class objects may be able to access members of external class objects without any conditions-just as those members are directly affiliated with internal class objects. In this way, a better solution is provided for the callback problem-C ++ uses pointers to Members to solve the problem.


(29) because of the internal class mentioned above, there is no pointer to the member in Java.


(30) The "inline" method does not exist in Java. The Java compiler may decide to embed a method on its own, but we do not have more control power. In Java, you can use the final keyword for a method to "recommend" embedding. However, embedded functions are only a suggestion for the C ++ compiler.


(31) Inheritance in Java has the same effect as C ++, but uses different syntaxes. Java uses the extends keyword flag to inherit from a base class, and uses the super keyword to indicate the method to be called in the base class. It has the same name as the method currently in use (however, the super keyword in Java only allows us to access the method of the parent class-that is, the upper level of the hierarchical structure ). By setting the scope of the base class in C ++, we can access methods that are located in a deep hierarchical structure. You can also use the super keyword to call the basic class builder. As mentioned earlier, all classes will be automatically inherited from the Object. Unlike C ++, there is no clear builder initialization list. However, the compiler forces us to initialize all the base classes at the beginning of the builder body, and does not allow us to perform this work in the later part of the body. By combining automatic initialization and exceptions from Uninitialized Object handles, the initialization of members can be effectively guaranteed.

1 public class Foo extends Bar {2   public Foo(String msg) {3     super(msg); // Calls base constructor4   }5   public baz(int i) { // Override6     super.baz(i); // Calls base method7   }8 }

 

(32) Inheritance in Java does not change the protection level of basic class members. We cannot specify public, private, or protected inheritance in Java, which is the same as C ++. In addition, the Priority Method in the Rule class cannot reduce access to the basic class method. For example, if a member belongs to the public class and we replace it with another method, the method used for replacement must also be public (the compiler will automatically check ).


(33) Java provides an interface keyword to create an equivalent of an abstract base class. Fill in the abstract method with no data member. In this way, there is a significant difference between the two for something that is just designed as an interface, and the extension based on the existing function using the extends keyword. It is not worth using abstract keywords to produce a similar effect, because we cannot create an object belonging to that class. An abstract class can contain abstract methods (though not required to include anything in it), but it can also contain code for specific implementation. Therefore, it is restricted to a single inheritance. Through joint use with interfaces, this solution avoids the need for some mechanisms similar to the C ++ virtual basic class. The implements keyword is used to create an interface (interface) version that can be used for "example" (that is, to create an instance. Its syntax is similar to the inherited syntax, as shown below:

1 public interface Face {2   public void smile();3 }4 public class Baz extends Bar implements Face {5   public void smile( ) {6     System.out.println("a warm smile");7   }8 }

 

(34) There is no virtual keyword in Java, because dynamic binding is required for all non-static methods. In Java, programmers do not have to decide whether to use dynamic binding. The reason why C ++ uses virtual is that we can omit it to improve the execution efficiency (or in other words: "If not, there is no need to pay for it "). Virtual often causes confusion to a certain extent, and unpleasant results are obtained. The final keyword specifies some scope for performance adjustments-It indicates to the compiler that this method cannot be replaced, so its scope may be static (and become an embedded state, therefore, use the C ++ non-virtual call equivalent method ). These optimizations are completed by the compiler.


(35) Java does not provide multiple inheritance mechanisms (MI), at least not as C ++ does. Similar to protected, MI is a good idea on the surface, but you only know that you need it when you really face a specific design problem. Because Java uses a single hierarchical structure, MI is used only in rare cases. The interface keyword will automatically Merge multiple interfaces.


(36) The type identification function is very similar to that of C ++ during runtime. For example, to obtain information related to handle X, you can use the following code:

1 X.getClass().getName();

To perform a "type security" tightening style, you can use:

1 derived d = (derived)base;

This is the same as the traditional C style. The compiler automatically calls the Dynamic Modeling Mechanism and does not require additional syntax. Although it is not as easy to locate the shape as C ++'s "new casts", Java checks usage and discards those "exceptions ", therefore, it does not allow the existence of bad shapes as C ++ does.


(37) Java adopts different exception control mechanisms because the builder does not exist at this time. You can add a finally clause to forcibly execute a specific statement for necessary clearing. All exceptions in Java are inherited from the basic class Throwable, so we can ensure that we get a general interface.

 1 public void f(Obj b) throws IOException { 2   myresource mr = b.createResource(); 3   try { 4     mr.UseResource(); 5   } catch (MyException e) { 6     // handle my exception 7   } catch (Throwable e) { 8     // handle all other exceptions 9   } finally {10     mr.dispose(); // special cleanup11   }12 }

 

(38) Java exception specifications are much better than C ++. After an error exception is discarded, instead of calling a function during runtime like C ++, the Java exception specification is checked and executed during compilation. In addition, the replaced methods must comply with the exception specification of the basic version of that method: They can discard specified exceptions or other exceptions derived from those exceptions. In this way, we finally get a more robust exception control code.


(39) Java is capable of method overload, but operator overload is not allowed. The String class cannot use the + and + = operators to connect different strings, and the String expression uses automatic type conversion, but this is a special built-in situation.


(40) through prior agreements, const problems frequently encountered in C ++ have been controlled in Java. We can only pass the handle pointing to the object, and the local copy will never be automatically generated for us. If you want to use a technology similar to C ++ passing by value, you can call clone () to generate a local copy of the independent variable (although the clone () design is still rough ). There is no automatically called replica builder at all. To create a constant value during the compilation period, it can be encoded as follows:

1 static final int SIZE = 2552 static final int BSIZE = 8 * SIZE

 

(41) for security reasons, there is a significant difference between the programming of "application" and the programming of "program piece. One of the most obvious problems is that the program chip does not allow us to write data to the disk, because this will cause programs downloaded from remote sites and whose origins are unknown to rewrite our disk. With Java 1.1's reference to digital signature technology, this situation has changed. Based on the digital signature, we can know exactly all the authors of a program piece and verify that they are authorized. Java 1.2 will further enhance the program chip capabilities.


(42) Because Java may appear too restrictive in some cases, it is sometimes reluctant to use it to execute important tasks such as direct access to hardware. Java's solution to this problem is an "inherent method" that allows us to call functions written in other languages (currently only C and C ++ are supported ). In this way, we will certainly be able to solve platform-related problems (in a form that is not portable, but that code will then be isolated ). Program slices cannot call inherent methods. Only applications can call them.


(43) Java provides built-in support for annotation documents, so source code files can also contain their own documents. Through a separate program, the document information can be extracted and reformatted into HTML. This is undoubtedly a great improvement in document management and application.


(44) Java contains some standard libraries for specific tasks. C ++ relies on some non-standard libraries provided by other vendors. These tasks include (or will soon include ):
■ Network connection
■ Database connection (through JDBC)
■ Multithreading
■ Distributed objects (through RMI and CORBA)
■ Compression
■ Commerce
Because these libraries are easy to use and very standard, they can greatly speed up application development.


(45) Java 1.1 contains the Java Beans standard, which allows you to create components used in a visual programming environment. The same standards are observed, so visual components can be used in the development environment of all vendors. Because we do not rely on a vendor's solution for visual component design, the choice of components will increase and improve the efficiency of components. In addition, the design of Java Beans is very simple and easy for programmers to understand. Specialized component frameworks developed by different vendors require more in-depth learning.


(46) if the access to the Java handle fails, an exception is discarded. This discard test does not have to be performed just before a handle is used. According to the Java design specification, exceptions must be discarded in some form. Many C ++ runtime systems can also discard exceptions caused by pointer errors.


(47) Java is generally more robust, and the method adopted is as follows:
■ The object handle is initialized to null (a keyword)
■ The handle will certainly be checked and an exception will be discarded when an error occurs.
■ All array access requests will be checked to promptly detect boundary violations
■ Automatic garbage collection to prevent memory Vulnerabilities
■ Explicit and "silly" exception Control Mechanism
■ Simple language support for Multithreading
■ Perform bytecode verification for network program slices

 

Alimail: AlanLee

Blog: http://www.cnblogs.com/AlanLee

This article is from the blog site. You are welcome to join the blog site.

 

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.