From C + + to Java

Source: Internet
Author: User
Tags java reference java throws

C + + and Java are all claims to be object-oriented languages, although C + + is not entirely considered. Learn how C + + quickly has a general grasp of Java, which can be understood by comparison.

First of all, come on tall and look at their mission:

· C + + is designed to be used primarily as a language in the design of a system application, extending the language. For the C language, a process-based programming language designed for operational efficiency, C + + is specifically supported by the following features: support for static types of object-oriented programming, exception handling, RAII, and generics. In addition, it adds a C + + library function that contains generic containers and algorithms.
· Java was initially designed to support network computing. It relies on a virtual machine to ensure security and portability. Java contains an extensible library to provide an abstraction of a complete downlevel platform. Java is a static object-oriented language that uses syntax similar to C + +, but incompatible with it. In order to make more people more accessible, it has been designed in a completely new language.

A general look at the semantic differences between Java and C + +:

· C + + allows you to set default values for the parameters of a function/method, which Java does not provide. However, the method overloads can achieve the same effect.

· The smallest compiler unit in C + + is a function; The smallest compilation unit in Java is a class. In C + +, functions can be compiled separately. In Java, the technique of compiling and maintaining a separate method requires moving them to a superclass or subclass or using other code refactoring techniques.

· C + + allows some implicit conversions between basic types, and also allows programmers to implicitly convert rules that are related to user-defined types. In Java, only the conversion of a widening type between the basic types can be implicit; The remaining conversions require an explicit type conversion syntax.

• One consequence of this is that although the conditions of the loop in Java and C + + (if, while and the exit condition in the for) are expected to be a Boolean expression, the if (A = 5) code in Java causes a compilation error because there is no implicit narrowing conversion from integral type to Boolean. If the code is an if (a = = 5) of the wrong case then it is convenient to find this error. The current C + + compiler generally only generates a warning for this situation.

• For cases where parameters are passed to a function, C + + supports reference passing and value passing. In Java, parameters are always passed by value. In Java, however, all non-primitive types of values are simply references to objects (in C + + terminology, they are smart pointers). Objects are not used directly in Java as values, only references to objects can be manipulated directly; C + + developers who are accustomed to using objects as values directly often confuse this with reference passing.

· The Java built-in type is defined by the virtual machine in the byte width and value range; In C + +, built-in types have a minimum range of values defined, but other parts (byte widths) can be mapped to native types supported on a specific platform.

• For example, a Java character is a 16-bit Unicode character, and a string is a serial of such characters. C + + provides narrow and wide two characters, but the actual character width is related to the peace table, depending on the character set used. A string can consist of one of these two characters.

• The precision and rounding methods of floating-point numbers and their operations are platform-dependent in C + +. Java provides an optional, rigorous floating-point model that guarantees cross-platform consistency, but may result in poor runtime efficiency.

• In C + +, pointers can be manipulated directly as memory addresses. Java has no pointers-it has only object references and array references, neither of which allows direct access to memory addresses. In C + + you can construct a pointer to a pointer, whereas a Java reference can only point to an object.

• In C + +, pointers can point to functions or methods (function pointers). The equivalents in Java are references to objects or interfaces.

• Although there are objects that use stack memory allocations, C + + supports zone resource management, a technique that automates the management of memory and other system resources, which supports deterministic object destruction (deterministic object destruction). However, regional resource management is not guaranteed in C + +; it is just a design pattern, so you need to rely on the programmer to obey the relevant rules. Java uses garbage collection to support automatic memory management, but for other system resources (Windows, communication ports, threads), if the garbage collector cannot determine whether they are no longer being used, it usually needs to be explicitly released.

· The features of user-definable operator overloading for C + + are not supported in Java. The only operators that can be overloaded in Java are the "+" and "+ =" operators, which are overloaded with connection strings in strings.

· Java's standard application interface supports reflection and dynamic loading of arbitrary code.

· C + + supports both static and dynamic library connections.

· Java supports generics, whose primary purpose is to provide a type-safe container. C + + support templates that provide stronger support for generic programming.

· Both Java and C + + are basic types (also called "Built-in" types) and user-defined types (also called "composite" types). In Java, the basic type has only the semantics of the value, and the composite type has only the semantics of the reference. All values in C + + have value semantics, and you can create references to any type, allowing you to manipulate objects by reference semantics.

· C + + supports multiple inheritance of any type. In Java a class can only inherit from a single class, but a class may implement multiple interfaces (in other words, it supports multiple inheritance of types, but for implementations can only be single-inheritance (it supports multiple inheritance of types, but only Single inheritance of implementation).

· Java is explicitly differentiated for classes and interfaces. Multiple inheritance and pure virtual functions in C + + make it possible to define classes of Java-like interfaces, but there is a slight difference.

· Java has good support for multithreading in both language and standard libraries. Synchronized this Java keyword provides a simple and secure mutex to support multithreaded applications, but the synchronous (synchronized) zone can only be left in LIFO order. Java also provides a robust and complex library for higher-order multithreaded synchronizations. There is no memory model specifically defined for multithreading in C + +; But third-party libraries provide the same functionality as Java; However, the differences between these C + + libraries are large and the consistency is not good.

· C + + methods can be declared as virtual functions, and virtual functions are determined at run time based on the type of the object. The C + + method is not virtual by default. In Java, the method is virtual by default, but it can be declared as non-virtual using the final keyword.

· C + + enumerations are primitive types that support conversions and comparisons between and other integer types. Java enumerations are actually instances of classes (they extend from java.lang.enum<e>), like other classes can define constructors, data members, and methods.

After reading the above may be divorced from the actual language syntax, such as what "reflection" of the dynamic language of the characteristics of C + + is not exist, the following is a brief summary:

Main function
C + +

int main (int argc, char* argv[])
{
printf ("Hello, World");
}
Java
Each function must be part of a class, and when Java <class> Run is a particular class, the main function is called
(So you can have a main function for each class, which is useful in writing unit tests)
Class HelloWorld
{
public static void Main (String args[])
{
System.out.println ("Hello, World");
}
}

declaration of the class
Except Java is not required to use sub-exception is almost the same.
C + +
Class Bar {};
Java
Class Bar {}

Method Declaration
All the same except in Java, the method must always be part of a class and may be public/private/protected as a cosmetic

Constructors and destructors
Constructors are the same (that is, the name of the class), and Java does not have a destructor of the exact meaning

static member functions and variables
Method declarations are the same, but Java provides static initialization blocks to initialize static variables (which do not need to be declared in the source file):
Class Foo
{
static private int x;
Static initialization blocks
{x = 5;}
} The declaration of the object C + + //in the stack

MyClass x;
or in the heap.
MyClass *x = new MyClass;
Java
Always declared in the heap
MyClass x = new MyClass ();

Inheritance
C++
Class Foo:public Bar
{ ... };
Java
Class Foo extends Bar
{ ... }

Access level (abstraction barriers)
C + +

Public
void Foo ();
void Bar ();
Java
public void foo ();
public void Bar ();

Virtual Functions
C + +
virtual int foo (); Or a non-virtual function to write int foo ();
Java
The default function is the virtual function; Prevent overloading with the final keyword
int foo (); Or, Final int foo ();

Memory management
Basically the same--new to allocate, but Java has no delete because it has a garbage collector.

null vs NULL
C + +
Initializes a pointer to NULL
int *x = NULL;
Java
The compiler captures references that use uninitialized
But if you assign a null because you need to initialize a reference, this is not valid
MyClass x = null;

Boolean type
Java is a bit verbose: you have to write a Boolean rather than a bool.
C + +
BOOL Foo;
Java
boolean foo;

Constants
C + +
const int x = 7;
Java
Final int x = 7; (The final keyword modifies the method of the class to indicate that the method is not redefined by the quilt class, because the methods in Java are the default virtual)

Throw Exception
First, Java throws exceptions in the compiler-if your method might throw exceptions you must explicitly report
C + +
int foo () throw (IOException)
Java
int foo () throws IOException

Array
C + +
int x[10];
Or
int *x = new X[10];
Use X, then return the memory
Delete[] x;
Java
int[] x = new INT[10];
With X, the memory is recycled by the garbage collector or
or return it to the system at the end of the program life cycle

The

collection and iterator
C + +

Iterators are members of the class. The start of the range is < container >.begin (), and the end is < container >.end (). Use the + + operator to increment the,  with the * operator.  
Vector Myvec;
for (Vector<int>::iterator ITR = Myvec.begin ();
  ITR! = Myvec.end ();
++itr)
{
cout << *itr; The
}
Java
Iterator is just an interface. The beginning of the range is < collection >.iterator, you must use Itr.hasnext () to see if the end of the collection is reached. Use Itr.next () (a combination of the operator + + and * operations in C + +) to get the next element.  
ArrayList myarraylist = new ArrayList ();
Iterator ITR = Myarraylist.iterator ();
while (Itr.hasnext ())
{
  System.out.println (Itr.next ());
}
//or, in Java 5,
ArrayList myarraylist = new ArrayList ();
for (Object o:myarraylist) {
System.out.println (o);
   }

Abstract class
C++
You only need to include a pure virtual function
Class Bar {public:virtual void foo () = 0;};
Java
Syntax allows the display of the declaration!
Abstract class Bar {public abstract void foo ();}
Or you can also declare an interface
Interface Bar {public void foo ();}
Then let a class inherit this interface:
Class Chocolate implements Bar
{
public void Foo () {/* do something */}
}
Reference vs Pointer
C + +
References are immutable, and more flexibility is gained by using pointers
int bar = 7, Qux = 6;
int& foo = bar;
Java
The reference is mutable and only the object address is stored;
No pointer type
MyClass x;
X.foo (); Error, X is a null ' pointer '
Note that you always have to use. To access the domain, which means no
Notes
The two languages are the same (//and/* */can be used)

From C + + to Java

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.