The main differences between C + + and Java

Source: Internet
Author: User
Main function C + +
free-floating function
int main (int argc, char* argv[])
{
    printf ("Hello, World");
}
Java
Every function must is part of a class;  The main function for a particular
//class file was invoked when Java <class> are run (so can have one
/ Main function per class--useful for writing unit tests for a class)
class HelloWorld
{public
    static void Main (String args[])
    {
        System.out.println ("Hello, World");
    }

compiling C + +
    Compile as
    g++ foo.cc-o outfile
    //Run with
    ./outfile
    
Java
    Compile classes in Foo.java to <classname>.class
    javac-Foo.java 

    //run by invoking static main <classname>
    Java <classname>
    
CommentsSame in both languages (///* * both work) Class DeclarationsAlmost the same, but Java does not require a semicolon C + +
    Class Bar {};
    
Java
    Class Bar {}
    
Method DeclarationsSame, except in Java, must always is part of the class, and may prefix with public/private/protected Constructors and DestructorsConstructor has same syntax in both (name of the Class), Java has no exact equivalent of the destructor Static member functions and variablesSame as method declarations, but Java provides static initialization blocks to initialize static variables (instead of Ting a definition in a source code file:
Class Foo 
{
    static private int x;
    Static initialization block
    {x = 5;}
}
scoping static methods and namespaces C + +If you are have a class and wish to refer to a static method, use the form Class::method.
Class MyClass
{public
    :
    static Dostuff ();
};

Now it's used like this
MyClass::d ostuff ();
JavaAll scoping in Java uses the. Again, just like accessing Fields's a class, so it's a bit more regular:
Class MyClass
{public
    static dostuff ()
    {
        //does Stuff
    }
}

//Now it's used
like this Myclass.dostuff ();
Object Declarations C + +
    On the stack
    myClass x;

    Or on the heap
    myClass *x = new MyClass;
    
Java
    Always allocated on the heap (also, always need parens for constructor)
    MyClass x = new MyClass ();
    
Accessing fields of objects C + +If you are using a Stack-based object, access its fields with a dot:
MyClass x;
X.my_field; Ok
But the arrow operator (->) to access fields of a class when working with a pointer:
MyClass x = new MyClass ();
x->my_field; Ok
JavaYou are always work with references (which are similar to pointers--see the "next section"), so your always use a dot:
MyClass x = new MyClass ();
X.my_field; Ok
References vs. Pointers C + +
    References are immutable, use pointers for more flexibility
    int bar = 7, Qux = 6;
    int& foo = bar;
    
Java
    References are mutable and store addresses only to objects; There are
    //no raw pointers
    MyClass x;
    X.foo (); Error, X is a null ' pointer '//the note '

    always use. To access a field
    
Inheritance C + +
    Class Foo:public Bar
    {...};
    
Java
    Class Foo extends Bar
    {...}
    
Protection levels (abstraction barriers) C + +
    Public:
        void foo ();
        void Bar ();
    
Java
    public void foo ();
    public void Bar ();
    
Virtual Functions C + +
    virtual int foo (); Or, non-virtually as simply int foo ();
    
Java
    Functions are virtual by default; Use final to prevent overriding
    int foo ();//or, Final int foo ();
    
Abstract Classes C + +
    Just need to include a pure virtual function
    class Bar {public:virtual void foo () = 0;};
    
Java
    Syntax allows you are explicit!
    Abstract class Bar {public abstract void foo ();}

    Or you might even want to specify a interface
    interface Bar {public void foo ();}

    And later, have a class implement the interface:
    class Chocolate implements Bar
    {public
        void foo () {/* Do something */}
    }
    
Memory ManagementRoughly the same--new allocates, but no delete in Java since it has garbage. null vs. NULL C + +
    Initialize pointer to null
    int *x = NULL;
    
Java
    The compiler'll catch the use of uninitialized references, but if I
    //need to initialize a reference so it's K Nown to is invalid, assign null
    myClass x = null;
    
BooleansJava is a bit more verbose:you must write Boolean instead of merely bool. C + +
BOOL Foo;
Java
boolean foo;
const-ness C + +
    const int x = 7;
    
Java
    Final int x = 7;
    
Throw SpecA, Java enforce throw specs at compile time--you must document if your method can throw a exception C + +
int foo () throw (IOException)
Java
int foo () throws IOException
Arrays C + +
    int x[10];
    or 
    int *x = new X[10];
    Use X, then reclaim memory
    delete[] x;
    
Java
    int[] x = new INT[10];
    Use x, memory reclaimed by the garbage collector or returned to the
    //system at the "End of" the program ' s lifetime
    
Collections and Iteration C + +Iterators are members of classes. The start of a range is <container>.begin (), and the End is <container>.end (). Advance using + + operator, and access using *.
    Vector Myvec;
    for (Vector<int>::iterator ITR = Myvec.begin ();
          ITR!= myvec.end ();
          ++ITR)
    {
        cout << *itr;
    }
    
JavaIterator is just a interface. The start of the range is <collection>.iterator, and you are check to the "If you" at the End With Itr.hasnext (). You get the next element using Itr.next () (a combination of using + + and * in C + +).
    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);
    }
    

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.