Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between Java and C++?

2025-03-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the difference between Java language and C++ language". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the difference between Java and C++?"

Java uses C and C++ syntax format, for programmers who have studied C and C++, learning Java will probably be very easy. However, if you examine many details of the Java language, you will find that Java has removed a lot of C and C++ features and added some new features. These differences include:

O there is no longer the concept of Pointer.

This is one of the main grammatical differences between Java and CCompact +. In C and C++, the flexible use of pointers will bring great convenience to programming, but its flexibility has also become a major factor leading to program instability. With the memory management strategy of C and C++, programmers must personally track the memory they applied to the system and finally confirm and return it to the system. And when using pointers, always pay attention to whether the legal memory space is exceeded, causing problems such as Segmentation Fault or General Protection Fault.

Java provides a Reference type to replace pointers. By accessing the requested memory space through references, you can ensure that you will not access the memory space that does not belong to you. At the same time, the execution system of the program can also dynamically do memory garbage collection to reclaim the de-referenced memory space to the system. This dynamic memory allocation mechanism ensures the security of memory allocation to a certain extent by sacrificing some flexibility.

O there is no longer the concept of Function.

In the Java programming language, the function, the most important part of the structured language, is eliminated. In the concept of object-oriented programming, the data of the object is the real topic, and the method of dealing with the data of the object must be attached to the object to make sense. Therefore, the concept of function is completely unnecessary. This reinforces the object-oriented development strategy.

O structure, union, and typedef are no longer used.

In fact, in C++, you can remove the custom structure types of complex data, such as structure and union in C, because the way Class is defined can do this function. The function of typedef can also be implemented by classes. Although C++ is designed to be C-compatible, these are redundant language features that have been abandoned in the Java language.

O there is no more multiple inheritance of classes (Multiple Inheritance).

In C++, multiple inheritance is a strong function, but it is also difficult to master. Eliminating multiple inheritance reduces the functionality of the Java language, but it makes Java look more concise. At the same time, Java also provides the way of interface (Interface), which can realize the function of partial multiple inheritance. The difference from multiple inheritance is that the interface does not define the content of the class method or the data in the class.

O there are no more operator overloads (Operator Overloading).

Operator overloading is seen as a feature of C++. In C++, with operator overloading, programmers can make programs look more natural by defining existing operators themselves. However, if used improperly, the readability of the whole program will be greatly affected. At the same time, the existence of this function is not necessary, and programmers can define methods in the class to achieve the same goal.

O automatic type conversion has been cancelled.

Java is a strongly type-checking programming language. For cases such as floating-point variables assigning values to integer variables, it is allowed in the syntax of C++. At most, it only gives warnings at compile time. However, in Java, compilation cannot pass unless cast is explicitly written.

O there is no preprocessor (preprocessor) function.

By using the preprocessing instructions such as # define and # include provided in CUniverse +, powerful programmers can develop a set of macro instructions that only they can understand. From the point of view of software engineering, this is very disadvantageous to the team's development of software and the maintenance of the whole software. At the same time, the precompiled program code is different from the program code seen by the programmer. If there is something wrong with the macro instruction set, the error message generated by the compiler will not be what programmers expect, which increases the difficulty of program debugging.

O canceled the goto statement.

In C++, the goto statement is no longer recommended, and goto is retained only for compatibility with C syntax. In Java, goto statements are completely discarded. At the same time, Java expands the functions of break statements and continue statements. By using break and continue, program flow is allowed to jump in multi-tier loops.

It can be said that Java programming language is a concise and effective pure object-oriented programming language. The C++ language is not as good as Java in object-oriented features because it is compatible with C (C++ is defined as a superset of C).

=

Compare C++ and Java

"as C++ programmers, we have long mastered the basic concepts of object-oriented programming, and the syntax of Java is undoubtedly very familiar. In fact, Java is derived from C++."

However, there are still some significant differences between C++ and Java. It can be said that these differences represent great advances in technology. Once we understand these differences, we will understand why Java is an excellent programming language. This appendix will introduce you to some of the important features that distinguish between Java and C++.

(1) the biggest obstacle is speed: the explained Java is about 20 times slower than C. Nothing can stop the Java language from compiling. At the time of writing this book, some quasi-real-time compilers have just emerged that can speed up significantly. Of course, we have every reason to think that there will be pure native compilers for more popular platforms, but without those compilers, there must be some problems that Java can't solve because of speed limits.

(2) like C++, Java provides two types of comments.

(3) everything must be put into a class. There are no global functions or global data. If you want to achieve functionality equivalent to a global function, consider putting the static method and static data into a class. Note that there is no such thing as structure, enumeration, or union, only "Class"!

(4) all methods are defined in the body of the class. So from the perspective of C++, it seems that all the functions are embedded, but the truth is not how (the problem of embedding is described later).

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

Class aType ()

Void aMethod () {/ * method body * /}

}

(6) there is no scope operator ":" in Java. Java does everything with periods, but you don't have to think about it, because you can only define elements in one class. Even those method definitions must be inside a class, so there is no need to specify a scope at all. One difference we noticed was the call to the static method: using ClassName.methodName (). In addition, the name of package (package) is created by periods and can be used to implement part of C++ 's "# include" function with the import keyword. For example, the following statement:

Import java.awt.*

(# include does not map directly to import, but has a similar feeling when using it. )

(7) similar to C++, Java contains a series of "Primitive type" for more efficient access. In Java, these types include boolean,char,byte,short,int,long,float and double. The sizes of all primary types are inherent and independent of the specific machine (considering migration). This will certainly have an impact on performance, depending on the machine. Type checking and requirements become more stringent in Java. For example:

■ conditional expressions can only be of type boolean (Boolean) and cannot use integers.

■ must use the result of an expression like Xray; you can't just use "X-ray" to achieve "side effects".

(8) the char (character) type uses the international 16-bit Unicode character set, so it can automatically express characters from most countries.

(9) statically referenced strings are automatically converted to String objects. Unlike C and C++, there are no separate static character array strings available.

(10) Java adds three right shift operators "> >", which is similar to the "logical" right shift operator by inserting a zero value at the end. ">" inserts symbol bits (that is, "arithmetic" shift) at the same time of the shift.

(11) although superficially similar, the Java array has a quite different structure and unique behavior than C++. There is a read-only length member that lets you know how big the array is. And once the array boundary is exceeded, the runtime 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). Array identifiers belong to first-level objects, and all of its methods usually apply to all other objects.

(12) all objects that are not of the primary type can only be created through the new command. Unlike C++, Java has no command "on the stack" to create objects that are not of the primary type. All primary types can only be created on the stack without using the new command. All major classes have their own wrapper classes, so you can create equivalent memory "heap"-based objects through new (with the exception of arrays of primary types: they can be allocated through collection initialization like C++, or use new).

(13) there is no need for prior declaration in Java. If you want to use a class or method before a definition, simply use it directly-- the compiler ensures that the appropriate definition is used. So unlike in C++, we don't encounter any problems that involve quoting in advance.

(14) Java does not have a preprocessor. To use a class from another library, simply use the import command and specify the library name. There are no macros similar to preprocessors.

(15) Java replaces namespaces with packages. Because everything is put into one class, and because it uses a mechanism called "encapsulation", it can do something similar to namespace decomposition for class names, so naming is no longer part of our consideration. The package also collects the 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) the object handle defined as a class member is automatically initialized to null. The initialization of basic class data members is reliably guaranteed in Java. If they are not explicitly initialized, they will get a default value (zero or equivalent). They can be explicitly initialized (explicitly initialized): they can be defined either within the class or in the builder. The syntax adopted is easier to understand than C++ 's and is fixed for both static and non-static members. We don't have to define how static members are stored externally, unlike C++.

(17) in Java, there are no pointers like C and C++. When you create an object with new, you get a reference (which has been called a "handle" in this book). For example:

String s = new String ("howdy")

However, C++ references must be initialized at creation time and cannot be redefined to a different location. However, Java references are not necessarily limited to where they were created. They can be defined at will according to the circumstances, which eliminates part of the need for pointers. Another reason for the heavy use of pointers in C and C++ is the ability to point to any memory location (which also makes them insecure, which is why Java does not provide this support). Pointers are often seen as an effective means of moving around in an array of base variables. Java allows us to achieve the same goal in a more secure form. The ultimate solution to the pointer problem is the "inherent method" (discussed in Appendix A). Passing pointers to methods usually doesn't cause much problem, because there are no global functions, only classes. And we can pass a reference to the object. The Java language initially claimed that it "doesn't use pointers at all!" But as many programmers ask how to work without pointers? As a result, it was later declared that "restricted pointers are used". It is a pointer that you can judge for yourself whether it is "true". But in any case, there is no pointer "arithmetic".

(18) Java provides a "Constructor" similar to C++. If you don't define one yourself, you'll 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++. Notice that the builder is not copied because all arguments are passed by reference.

(19) there is no Destructor in Java. Variables do not have a "scope" problem. The "existence time" of an object is determined by the existence time of the object, not by the garbage collector. There is a finalize () method that is a member of every class, which is somewhat similar to C++ 's "destroyer". But finalize () is called by the garbage collector and is only responsible for releasing "resources" (such as open files, sockets, ports, URL, and so on). If you want to do something in a particular location, you must create a special method and call it, not relying on finalize (). On the other hand, all objects in C++ will be destroyed (or should be), but not all objects in Java will be collected as "garbage". Since Java does not support the concept of a destroyer, you must carefully create a cleanup method when necessary. And for the underlying classes and member objects within the class, you need to explicitly call all cleanup methods.

(20) Java has a method "overload" mechanism, which works almost exactly the same as the overload of C++ function.

(21) Java does not support default arguments.

(22) there is no goto in Java. The unconditional jump mechanism it adopts is "break tag" or "continue standard", which is used to jump out of the current multiple nested loop.

(23) Java adopts a single-root hierarchical structure, so all objects inherit uniformly from the root class object. In C++, we can start a new inheritance tree anywhere, so we often end up seeing a "forest" containing a large number of trees. In Java, we have only one hierarchical structure anyway. Although this may seem like a limitation on the surface, we tend to gain more powerful capabilities because we know that each object must have at least one Object interface. C++ currently seems to be the only OO language that does not have a mandatory single-root structure.

(24) Java has no templates or other forms of parameterized types. It provides a series of collections: Vector (vector), Stack (stack), and Hashtable (hash table) to hold Object references. Using these sets, a series of our requirements can be met. But these collections are not designed for quick invocation like C++ 's Standard template Library (STL). The new collection in Java 1.2 is more complete, but still does not have the efficient use of authentic templates.

(25) "garbage collection" means that there are far fewer memory vulnerabilities in Java, but it is not entirely impossible (if an inherent method for allocating storage space is called, the garbage collector cannot track it). However, memory and resource vulnerabilities are mostly caused by improperly written finalize (), or by releasing a resource at the end of an allocated block (the "destroyer" is particularly convenient at this point). Garbage collector is a great progress on the basis of C++, making many programming problems invisible. However, it is not suitable for a few garbage collectors. But many of the advantages of the garbage collector also make this disadvantage seem negligible.

(26) Java has built-in support for multithreading. With a special Thread class, we can create a new thread by inheritance (abandoning the run () method). If the synchronized keyword is used as a type qualifier for a method, mutual exclusion occurs at the object level. Only one thread can use the synchronized method of an object at any given time. On the other hand, when a synchronized method enters, it first "locks" the object to prevent any other synchronized method from using that object again. The object will be "unlocked" only if you exit this method. Between 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 priority of the thread is the same, the "fragmentation" of time cannot be guaranteed.

Instead of controlling the declaration block as we did on C++, we put access qualifiers (public,private and protected) in the definition of each class member. If an "explicit" (explicit) qualifier is not specified, it defaults to "friendly". This means that other elements in the same package can also access it (equivalent to becoming C++ 's "friends"-friends), but not by any element outside the package. The class-- and every method within the class-- has an access qualifier that determines whether it can be "visible" outside the file. The private keyword is rarely used in Java because "friendly" access is often more useful than excluding other classes in the same package. However, in a multithreaded environment, the proper use of private is very important. The protected keyword of Java means that it can be accessed by inheritors or by other elements in the package. Notice that Java has no equivalent to C++ 's protected keyword, which means "accessible only by inheritors" (this was previously possible with "private protected", but the combination of this pair of keywords has been removed).

(28) nested classes. In C++, nesting classes helps hide names and facilitate the organization of code (but C++ 's "namespace" has made name hiding redundant). Java's concept of "encapsulation" or "packaging" is equivalent to the namespace of C++, so it is no longer an issue. Java 1.1introduces the concept of "inner class", which secretly maintains a handle to the outer class-needed to create inner class objects. This means that inner class objects may be able to access members of external class objects without any conditions-- just as if those members belong directly to inner class objects. This provides a better solution to the callback problem-C++ is solved with pointers to members.

(29) because of the inner class described earlier, there is no pointer to the member in Java.

(30) there is no inline method for Java. The Java compiler may decide to embed a method on its own, but we don't have more control over it. In Java, you can use the final keyword for a method to "recommend" embedding. However, embedding functions is only a suggestion for C++ compilers.

(31) inheritance in Java has the same effect as C++, but with a different syntax. Java uses the extends keyword to mark inheritance from a base class and the super keyword to indicate the method to be called in the base 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 methods of the parent class-- that is, one level above the hierarchy). By setting the scope of the base class in C++, we can access methods that are deeper in the hierarchy. The underlying class builder can also be called with the super keyword. As pointed out earlier, all classes will eventually inherit automatically from Object. Unlike C++, there is no clear list of builder initializers. But the compiler forces us to do all the base class initialization at the beginning of the builder body, and does not allow us to do this later on the body. By combining automatic initialization and exceptions from uninitialized object handles, the initialization of members can be 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 change the protection level of members of the underlying class. We cannot specify public,private or protected inheritance in Java, which is the same as C++. In addition, priority methods in derived classes do not reduce access to underlying class methods. For example, suppose a member belongs to public in the base class and we replace it with another method, then the method used for replacement must also belong to public (the compiler automatically checks).

(33) Java provides an interface keyword that is used to create an equivalent of an abstract base class. Populate it with abstract methods and have no data members. As a result, there is a significant difference between what is simply designed as an interface and for extensions that use the extends keyword to build on existing functionality. It's not worth using the abstract keyword to have a similar effect, because we can't create an object that belongs to that class. An abstract class can contain abstract methods (although nothing is required to be included in it), but it can also contain code for a concrete implementation. Therefore, it is limited to a single inheritance. By using it in conjunction with the interface, this scheme avoids the need for mechanisms similar to the C++ virtual foundation class.

To create a version of interface that can be "instantiated" (that is, to create an instance), you need to use the implements keyword. Its syntax is similar to that of inheritance, as follows:

Public interface Face {

Public void smile ()

}

Public class Baz extends Bar implements Face {

Public void smile () {

System.out.println ("a waRM smile")

}

}

(34) there is no virtual keyword in Java, because all non-static methods are bound to use dynamic binding. In Java, programmers don't have to decide whether to use dynamic binding or not. C++ has adopted virtual because when we make performance adjustments, we can get a small improvement in execution efficiency by omitting it (or in other words: "if you don't use it, there's no need to pay for it"). Virtual often causes a degree of confusion and achieves unpleasant results. The final keyword specifies 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 use the equivalent of C++ non-virtual calls). These optimizations are done by the compiler.

(35) Java does not provide multiple inheritance mechanism (MI), at least not like C++. Like protected, MI is a good idea on the surface, but you don't know you need it until you're really faced with a particular design problem. Because Java uses a "single root" hierarchical structure, MI is needed only in rare situations. The interface keyword helps us automate the merging of multiple interfaces.

(36) the runtime type identification function is very similar to C++. For example, to get information about 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 shape. The compiler automatically invokes the dynamic modeling mechanism and does not require additional syntax. Although it does not have the advantage of easy positioning as C++ 's "new casts", but Java will check usage and discard those "exceptions", so it will not allow bad shapes like C++.

(37) Java adopts a different exception control mechanism because the builder no longer exists. You can add a finally clause to enforce specific statements in order to do the necessary cleanup work. All exceptions in Java are inherited from the base class Throwable, so make sure that what we get is 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

}

}

(38) Java's exception specification is much better than C++ 's. After discarding an erroneous exception, instead of calling a function at run time as C++ does, the Java exception specification is checked and executed at compile time. In addition, the replaced method must follow the exception specification of the base class version of that method: they can discard specified exceptions or other exceptions derived from those exceptions. As a result, we end up with more "robust" exception control code.

(39) Java has the ability to overload methods, but does not allow operator overloading. The String class cannot concatenate different strings with the + and + = operators, and String expressions use automatic type casting, but that is a special built-in case.

(40) through prior agreement, the const problem that often occurs in C++ has been controlled in Java. We can only pass handles to the object, and the local copy will never be automatically generated for us. If you want to use a technique like C++ passing by value, you can call clone () to make a local copy of the argument (although the design of clone () is still rough-see Chapter 12). There is no copy builder that is called automatically. To create a compile-time constant value, you can code like this:

Static final int SIZE = 255,

Static final int BSIZE = 8 * SIZE

(41) due to security reasons, there is a significant difference between the programming of "application" and that of "program chip". One of the most obvious problems is that the program chip does not allow us to write to the disk, because doing so may cause programs of unknown origin downloaded from remote sites to randomly rewrite our disk. With the introduction of Java 1.1 to digital signature technology, this situation has changed. According to the digital signature, we can know exactly all the authors of a program and verify whether they have been authorized. Java 1. 2 will further enhance the capabilities of program chips.

(42) because Java may seem too restrictive in some situations, it is sometimes reluctant to use it to perform important tasks such as direct access to hardware. Java's solution to this problem is the "native method", which 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 non-portable form, but the code will then be isolated). A program chip cannot call an inherent method, only an application can.

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

(44) Java contains standard libraries for specific tasks. C++ relies on non-standard libraries provided by other vendors. These tasks include (or will soon include):

■ networking

■ database connection (via JdbC)

■ multithreading

■ distributed objects (through Rmi and Corba)

■ compression

■ business

Because these libraries are easy to use and very standard, they can greatly speed up application development.

(45) Java 1.1 includes the Java Beans standard, which creates components for use in visual programming environments. By following the same standards, visual components can be used in the development environments of all vendors. Because we do not rely on a vendor's solution for the design of visual components, the choice of components will be increased, and the performance of components can be improved. In addition, Java Beans is designed to be simple and easy for programmers to understand, while specialized component frameworks developed by different vendors require more in-depth learning.

(46) if access to the Java handle fails, an exception is discarded. This discarding test does not have to be done just before a handle is used. According to the Java design specification, it is just that 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 by the following means:

The ■ object handle is initialized to null (a keyword)

The ■ handle is sure to be checked and the exception is discarded if something goes wrong

All array visits to ■ are checked to detect boundary violations in a timely manner

■ automatic garbage collection to prevent memory vulnerabilities

■ 's clear, "fool-like" exception control mechanism

■ provides simple language support for multithreading

■ checks the bytecode of the network program chip.

At this point, I believe you have a deeper understanding of "what is the difference between Java language and C++ language". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report