Basic Java-C++ Connection

Basic Syntax

Basic Types

For the most part Java and c++ share the same base syntax. The controll structures if-else, while, do, for and switch have the same syntax and semantics as they do in c++. Variables are declared in functions (and classes) in the same way they are declared in c++, the class name followed by the variable name. The primitive types for Java are:

A variable of one of these types may be declared and initialized in exactly the same way you would in c++. Strings are also provided in Java, but they are more complicated than those in c++. You will learn about them during week 3. Finally, a variable created for any user defined class must be initialized using new. So a variable x of MyClass type would be initailize by:

     MyClass x = new MyClass(   here you could have parameters for initialization  ) 

Classes and Functions

The structure of the classes is similar to c++, but there are some significant differences. First all functions must be associated with a class. This means you will find the function main declared in a class if that class represents an application. In addition, all classes and functions must have their access specified explicitly. That is rather than declaring sections of a class public, private or protected, you will declare the class, each of its member variables and functions with these designations. If you fail to specify the level of access of an item it will be visible only to classes in the same package. A package is a group of related classes.

First Example

Click here to see a simple Java program.