Comparison of Java and C + +

Source: Internet
Author: User
Tags throwable

Comparison of Java and C + +(1) The biggest hurdle is speed: The interpreted Java is about 20 times times slower than C's execution speed. No matter what, the Java language cannot be prevented from compiling. When writing this book, there have just been some quasi-real-time compilers that can speed up significantly. Of course, we have every reason to think that there will be a purely intrinsic compiler for more popular platforms, but without those compilers, there must be some problems that Java cannot solve due to speed constraints.
(2) As with C + +, Java also provides two types of annotations.
(3) Everything must be placed in a class. There is no global function or global data. If you want to get the function equivalent to the global function, consider placing the static method and the static data in a class. Note that there is no such thing as structure, enumeration, or union, and everything is only "class"!
(4) All methods are defined in the body of the class. So in the eyes of C + +, it seems that all functions are embedded, but the truth is not how (embedded issues are described later).
(5) in Java, class definitions take the form of almost the same as C + +. But there is no sign to end the semicolon. There is no class Foo in this form, only class definitions.
Class Atype ()
void Amethod () {/* Method body */}
}
(6) There is no scope scope operator "::" in Java. Java uses the dot to do everything, but it doesn't have to be considered, because elements can only be defined in a class. Even those method definitions must be inside a class, so it is not necessary to specify scope scopes at all. One of the differences we noticed is the call to the static method: Use Classname.methodname (). In addition, the name of the package is built with the dot number and can be used to implement part of the C + + "#include" function with the Import keyword. For example, the following statement:
Import java.awt.*;
(#include are not directly mapped to import, but have a similar feeling when used.) )
(7) similar to C + +, Java contains a series of "main types" (Primitive type) for more efficient access. In Java, these types include Boolean,char,byte, short, int,long, float, and double. The size of all the main types is intrinsic and irrelevant to the specific machine (considering the porting problem). This is sure to have a certain impact on performance, depending on the different machines. Checks and requirements for types become more demanding in Java. For example:
The conditional expression can only be a Boolean (Boolean) type and cannot be used as an integer.
You must use the result of an expression such as x+y, and you cannot use only "x+y" to achieve "side effects".
(8) char (character) type uses the international universal 16-bit Unicode character set, so it can automatically express the characters of most countries.
(9) A statically referenced string is automatically converted to a string object. Unlike C and C + +, there is no separate string of static character arrays to use.
Java adds three right shift operator ">>>" with the function similar to the "logical" right shift operator, which inserts 0 values at the very end. ">>" inserts the symbol bit (that is, the "arithmetic" shift) at the same time as the shift.
(11) Although superficially similar, Java arrays use a rather different structure than C + + and have unique behavior. There is a read-only length member through which you know how large the array is. And once the array bounds are exceeded, the run-time check automatically discards an exception. All arrays are created in the memory heap, and we can assign one array to another (simply copy the array handle). An array identifier belongs to the first-level object, and all of its methods generally apply to all other objects.
(12) For all objects that are not of the main type, they can only be created with the new command. Unlike C + +, Java does not have a corresponding command to create an object on the stack that does not belong to the main type. All primary types can only be created on the stack without using the new command. All major classes have their own "wrapper" class, so it is possible to create an equivalent, memory-based object with new (the main type array is an exception: they can be allocated as C + + through collection initialization, or use new).
In Java, there is no need to declare in advance. If you want to use a class or method before the definition, just use it directly-the compiler will ensure that the appropriate definition is used. So unlike in C + +, we don't run into any issues that involve early reference.
Java does not have a preprocessing machine. To use another class in the library, simply use the Import command and specify the library name. There is no macro similar to a preprocessing machine.
Java uses packages instead of namespaces. Because all things are placed in a class, and because of a mechanism called "encapsulation", it can be similar to the namespace decomposition of the class name operation, so the problem of naming no longer into our consideration. The package also collects components of the library under a single library name. We simply "import" a package, and the rest of the work is done automatically by the compiler.
(16) An object handle that is defined as a member of a class is automatically initialized to null. Initialization of basic class data members is reliably guaranteed in Java. If they are not explicitly initialized, they will get a default value (0 or equivalent). They can be explicitly initialized (explicitly initialized): either define them within the class or define them in the builder. The syntax used is easier to understand than the C + + syntax and is fixed for both static and non-static members. We do not have to define the storage method of static members externally, which is different from C + +.
(17) In Java, there are no pointers like C and C + +. When you create an object with new, you get a reference (this book has always referred to it as a "handle"). For example:
string s = new String ("Howdy");
However, C + + references must be initialized at the time of creation and cannot be redefined to a different location. However, Java references are not necessarily limited to where they were created. They can be arbitrarily defined according to the circumstances, which eliminates some of the need for pointers. Another reason for the large number of pointers in C and C + + is to be able to point to any memory location (which in turn makes them unsafe, which is why Java does not provide this support). Pointers are often seen as an effective means of moving around in an array of basic variables. Java allows us to achieve the same goal in a more secure form. The ultimate way to solve pointer problems is "intrinsic methods" (discussed in Appendix A). When you pass pointers to methods, there is usually no problem because there are no global functions at this time, only classes. And we can pass a reference to the object. The Java language began by claiming that it was "completely without pointers!" "But as many programmers are questioning how no pointers work?" Subsequently, it was declared that "the use of restricted pointers". You can judge for yourself whether it is a pointer or not. However, there is no pointer "arithmetic" in any case.
Java provides a "builder" (Constructor) similar to C + +. If you do not define one yourself, you will get a default builder. If you define a non-default builder, the default builder is not automatically defined for us. This is the same as C + +. Note that there is no copy builder, because all arguments are passed by reference.
() There is no "destructor" in Java. There is no "scope" problem with the variable. The "Time to exist" of an object is determined by the time the object exists, not by the garbage collector. There is a finalize () method that is a member of each class, which in some way resembles the C + + "sabotage". But 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 location, you must create a special method and call it, and you cannot rely on finalize (). On the other hand, all objects in C + + will be destroyed (or "should"), but not all objects in Java will be collected as "garbage". Since Java does not support the concept of a sabotage, it is important to create a cleanup method when necessary. And for the underlying classes and member objects within the class, you need to explicitly call all the cleanup methods.
Java has a method "overload" mechanism, which works almost identically to the overload of C + + functions.
Java does not support default arguments.
() There is no goto in Java. The unconditional jump mechanism it takes is "break label" or "continue standard", which is used to jump out of the current multiple nesting loops.
Java employs a single-radical hierarchical structure, so all objects are inherited from the root class object uniformly. In C + +, we can start a new inheritance tree anywhere, so we end up seeing "a forest" with lots of trees. In Java, we have only one hierarchical structure in any case. Although this appears to be a constraint, it is often possible to gain more power because we know that each object must have at least one object interface. C + + currently appears to be the only OO language that does not enforce a single root structure.
Java does not have templates or other forms of parameterized types. It provides a collection of vectors (vector), stack (stacks), and Hashtable (hash table) to accommodate the Object reference. With these collections, our range of requirements can be met. However, these collections are not designed to be a fast call to the real phenomenon C + + "Standard Template Library" (STL). The new collections in Java 1.2 appear to be more complete, but still do not have the efficient use of authentic templates.
(25) "garbage collection" means that there will be much less memory leaks in Java, but it is not entirely impossible (the garbage collector cannot track it if it calls an intrinsic method for allocating storage space). However, memory vulnerabilities and resource vulnerabilities are mostly due to poorly written finalize () or due to the release of a resource at the end of an allocated block ("the" "sabotage" is particularly handy at this point). Garbage collector is a kind of great progress on the basis of C + +, which makes many programming problems disappear in the invisible. However, it is not suitable for the few garbage collector forces that are not caught up in the problem. But the many advantages of the garbage collector also make this shortcoming seem insignificant.
Java has built-in support for multithreading. With a special thread class, we can create a new thread by inheriting (discarding the Run () method). If you use the synchronized (synchronous) keyword as a type limiter for a method, the 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, when a synchronized method enters, it first "locks" the object and prevents any other synchronized methods from using that object. The object will be "unlocked" only if this method is exited. Between threads, we are still responsible for implementing a more complex synchronization mechanism by creating your own "monitor" class. The recursive synchronized method can function normally. If the thread has the same priority level, the time "sub-
The film "cannot be guaranteed.
(27) Instead of controlling the declaration code block like C + +, we place the access qualifier (public, private, and protected) into the definition of each class member. If an explicit (explicit) qualifier is not specified, the default is "friendly" (friendly). This means that other elements in the same package can also access it (equivalent to being a C + + "Friends"-friend), but not accessible by any element outside the package. Class-and every method within a class-has an access qualifier that determines whether it can be "visible" outside of the file. Private keywords are often rarely used in Java because "friendly" access compared to the exclusion of access to other classes within the same package
usually more useful. However, in a multi-threaded environment, the proper use of private is very important. The protected keyword for Java means "can be accessed by inheritors or accessed by other elements within the package." Note that Java does not have elements that are equivalent to C + + 's protected keyword, which means "only inherited access" (previously available "private protected" for this purpose, but the combination of these two keywords has been canceled).
(28) Nested classes. In C + +, nesting of classes helps to hide names and facilitates the organization of the Code (but the C + + "namespace" has made the name hidden redundant). Java's "encapsulation" or "packaging" concept is equivalent to the C + + namespace, so it is no longer a problem. Java 1.1 introduces the concept of "inner class", which secretly maintains a handle to an external class--needed when creating an inner class object. This means that an inner class object might be able to access members of an external class object without any conditions-as if those members were directly subordinate to the inner class object. This provides a better solution to the callback problem--c++ is addressed with pointers to members.
(29) There is no pointer to a member in Java because of the kind of inner class described earlier.
There is no embedded (inline) method in Java. The Java compiler might decide to embed a method in its own right, but we don't have much control over it. In Java, you can use the final keyword for a method, which is recommended for embedding. However, embedding functions are only a recommendation for C + + compilers.
Inheritance in Java has the same effect as C + +, but with a different syntax. 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 underlying class, which has the same name as the method we are currently in (however, the Super keyword in Java only allows us to access the method of the parent class-- i.e. the upper level of the hierarchy). By setting the scope of the underlying class in C + +, we can access the methods that are located in the deeper part of the hierarchy. You can also call the base class Builder with the Super keyword. As noted earlier, all classes will eventually inherit from Object automatically. Unlike C + +, there is no explicit builder initialization list. But the compiler forces us to do all of the underlying class initialization at the beginning of the builder body and does not allow us to do this in the later part of the body. By combining automatic initialization and exceptions from uninitialized object handles, the initialization of the member is effectively guaranteed.
public class Foo extends Bar {
Public Foo (String msg) {
Super (MSG); Calls Base Constructor
}
public Baz (int i) {//Override
Super.baz (i); Calls base method
}
}
(+) Inheritance in Java does not alter the level of protection of the underlying class members. We cannot specify public, private, or protected inheritance in Java, which is the same as C + +. In addition, the precedence method in a derived class does not reduce access to the underlying class method. For example, if a member is public in the underlying class and we replace it with another method, then the method used for substitution must also be public (the compiler will check it automatically).
Java provides a interface keyword that is useful for creating an equivalent of an abstract base class. The abstract method is populated and there are no data members. In this way, there is a noticeable difference between what is designed to be an interface, and the expansion of the extends keyword on the basis of existing functionality. It's not worth having a similar effect with the abstract keyword, because we can't create an object that belongs to that class. An abstract (abstract) class can contain an abstract method (although it is not required to contain anything in it), but it can also contain code for specific implementations. Therefore, it is limited to a single inheritance. By using it in conjunction with the interface, this scenario avoids the need for some mechanism similar to the C + + virtual base class. To create a version of Interface (interface) that can be "instantiated" (that is, create an instance), use the Implements keyword. Its syntax is similar to the inherited syntax, as follows:
Public interface Face {
public void smile ();
}
public class Baz extends Bar implements face {
public void Smile () {
System.out.println ("A Warm Smile");
}
}
There is no virtual keyword in Java because all non-static methods are bound to use dynamic bindings. In Java, programmers do not have to decide for themselves whether to use dynamic binding. C + + uses virtual because we can tweak performance by omitting it to get a small boost in execution efficiency (or in other words: "If not, there's no need to pay for it"). Virtual often creates some degree of confusion and results in unpleasant outcomes. The final keyword provides some scope for performance tuning-it indicates to the compiler that this method cannot be replaced, so its scope may be statically constrained (and embedded, so the equivalence of C + + non-virtual calls). These optimizations are done by the compiler.
Java does not provide multiple inheritance mechanisms (MI), at least not the same as C + +. Like protected, MI is a good idea on the surface, but only when you really face a particular design problem do you know that you need it. Because Java uses a "single-root" hierarchy, MI is only needed for very few occasions. The interface keyword will help us automate the merging of multiple interfaces.
(36) The type identification function of the run period is very similar to C + +. For example, to get information about the handle X, you can use the following code:
X.getclass (). GetName ();
For a "type-safe" compact styling, you can use:
Derived d = (derived) base;
This is the same as the old style C styling. The compiler automatically calls the dynamic styling mechanism, without requiring the use of additional syntax. Although it does not have the advantage of easy-to-locate styling like the "new casts" of C + +, Java checks usage and discards those "exceptions", so it does not allow bad styling to exist like C + +.
(PNS) Java takes a different exception control mechanism because the builder does not already exist at this time. You can add a finally clause to force a specific statement to perform the necessary cleanup work. All exceptions in Java are inherited from the underlying class throwable, so make sure we get a generic interface.
public void F (OBJ b) throws IOException {
MyResource Mr = B.createresource ();
try {
Mr. Useresource ();
} catch (MyException e) {
Handle my exception
} catch (Throwable e) {
Handle all other exceptions
} finally {
Mr.dispose (); Special cleanup
}
}
Java's exception specification is much better than C + +. After discarding an incorrect exception, instead of calling a function during runtime like C + +, the Java exception specification is checked and executed during compilation. In addition, the superseded method must adhere to the exception specification for the underlying class version of the method: they can discard the specified exception or other exceptions derived from those exceptions. In this way, we end up with a more "robust" exception control code.
Java has the ability to overload the method, but does not allow operator overloading. The string class cannot concatenate different strings with the + and + = operators, and the string expression uses an automatic type conversion, but that is a special built-in situation.
(40) The const problem frequently appearing in C + + has been controlled in Java by prior agreement. We can only pass a handle to the object, and the local copy will never be generated automatically for us. If you want to use a technique like C + + by value, call Clone () to generate a local copy of the argument
Builder. To create a compile-time constant value, you can encode as follows:
static final int SIZE = 255
static final int bsize = 8 * SIZE
(41) For security reasons, there is a significant difference between the programming of the "Application" and the programming of the "program piece". One of the most obvious problems is that the patch does not allow us to write to the disk, because doing so would cause the unknown program to be downloaded from the remote site to rewrite our disk. This has improved with Java 1.1 's reference to digital signature technology. Based on a digital signature, we know exactly what the author of a piece of the program is and verify that they are authorized. Java 1.2 will further enhance the capabilities of the tablet.
(42) Because Java may appear to be too restrictive on some occasions, it is sometimes reluctant to use it to perform important tasks such as direct access to hardware. Java's solution to this problem is an "intrinsic method" that allows us to invoke functions written in other languages (only C and C + + are currently supported). In this way, we will certainly be able to solve the platform-related problems (in a non-portable form, but those code will then be isolated). The patch cannot invoke the intrinsic method, only the application can.
Java provides built-in support for annotation documents, so source files can also contain their own documents. Through a separate program, these document information can be extracted and reformatted into HTML. This is undoubtedly a great advance in document management and application.
Java contains a number of standard libraries for accomplishing specific tasks. C + + relies on some non-standard libraries provided by other vendors. These tasks include (or will soon include):
Connected Network
Database connection (via JDBC)
Multithreaded
Distributed objects (via RMI and CORBA)
Compression
Trade
Because these libraries are easy to use and very standard, they can greatly speed up application development.
Java 1.1 contains the Java Beans Standard, which creates components that are used in a visual programming environment. Due to the same standards, visual components can be used in all vendors ' development environments. Because we do not rely on a vendor's solution for visual component design, the choice of components is increased and the performance of the components is increased. In addition, the Java Beans is designed to be easy for programmers to understand, while specialized component frameworks developed by different vendors require more in-depth learning.
(46) If access to a Java handle fails, an exception is discarded. This discard test does not have to happen just before the use of a handle. According to the Java design specification, only that the exception must be discarded in some way. Many C + + runtime systems can also discard exceptions that are caused by a pointer error.
Java is generally more robust, and the means to do this are as follows:
Object handle initialized to null (a keyword)
The handle is definitely checked, and the exception is discarded on error
All array accesses will be checked to detect boundary violations in a timely manner
Automatic garbage collection to prevent memory leaks
A clear, "fool-type" anomaly control mechanism
Provides simple language support for multithreading
Byte-code verification of Network program slices

Comparison of Java and 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.