Java is based on C++
The syntax of the two languages is nearly identical
Java excludes features of C++ that threaten security or contribute to "dangerous" programming. C++ features not found in Java include friend functions, operator overloading, and the use of pointer arithmetic.
Java expands on C++ by adding features or requirements that enhance security and eliminate common programming mistakes. Some of the major improvements are as follows:
All Java programs must be object oriented. This makes them easier to build and maintain.
Java is designed for international programming. It can represent all the world's currency formats, time and date formats, and all the symbols found in every character set.
Java manages memory more efficiently and automatically than C++. This makes programs easier to run on small platforms and improves security.
Java provides default class constructors to initialize data members. This simplifies programming.
Java automatically handles data conversion during calculations and when passing parameters to methods.
Javadoc comments improve documentation and are accessible to .html files
Java has improved exception handling patterned after the C++ model
Java provides a rapidly expanding set of packaged code
Some warnings for C++ programmers about to learn Java
Due to subtle differences, a programmer working with both languages on a daily basis can get them confused
The Sun certification exam intentionally tries to trap C++ programmers who are new to Java
Java identifiers
Java data types
Java has fewer standard data types (primitives) than C++ and most are essentially the same as their C++ counterpart (such as short, int, long, float, and double). They are always the same regardless of platform.
Java has a boolean data type (rather than the bool data type of C++)
Java has a byte data type (an 8 bit storage area that can hold a small integer value in the range -128 to 127). This is equivalent to the signed char data type of C++.
The char data type in Java is a 16 bit storage area that can hold a single Unicode character. Unicode is a standardized code for representing symbols used in all the world's character sets. For example, upper case 'A' is assigned the Unicode bit pattern: 0000 0000 0100 0001
In Java, all numeric data is signed. The unsigned variations available in C++ (such as unsigned int) are not allowed.
Java has a String class for handling string data (similar to the C++ String class but with many differences)
Java variables
The syntax for declaring Java variables is exactly the same as in C++
By convention, Java programmers begin variable names with a lower case letter to distinguish them from class names
A floating-point literal in Java is automatically double unless you append f or F to the end of its value. This is a common source of a compile error when attempting to initialize a variable of type float. For example,
float shippingCharge = 6.25;
will not compile. This statement results in an error because the literal is double and the variable is float. The Java compiler is concerned about loss of data. To fix the error, the following can be coded:
float shippingCharge = 6.25f;
Java constants
Java does not recognize symbolic constants (#define), the const reserved word, or enumerated constants (enum) as used in C++
final double TAX_RATE = .06;
declares a double constant named TAX_RATE and assigns it a value of .06 (or 6%).
Writing to the system output device (the console)
In Java, there is no cout object and the insertion operator (<<) of C++ is not recognized. The system output device, however, is already open and may be referenced by the identifier System.out where out is a public reference to a PrintStream object defined within the System class.
println is a public method of PrintStream objects that accepts a string parameter and copies it to the output device.
Reading from the system input device (the keyboard)
Java does not have a cin object and does not recognize the C++ extraction operator ( >> ).
Reading anything but byte data from the keyboard is complicated in Java. To support application developers, a simple keyboard input scheme can be built, such as my Keyboard class. It uses pre-written Java classes and methods, particularly those in the java.io package, to handle keyboard input. For information on using the class, click here.
Arithmetic oprations
Conversions
Are performed automatically in Java when mixed numeric types appear within an expression. Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss. This is known as a "widening" conversion. The order of conversion (from narrowest to widest) is as follows:
byte | short char \
/
int | long | float | double
Casts
Are essentially the same as in C++. The general syntax is
(data-type) expression
Comparisons and logical operations
The comparison and logical operators of C++ are fully supported in Java
In Java, a comparison always evaluates to a boolean value and not an int as in C++
Java provides an ^ (XOR) operator that will be true only if two boolean expressions have different values
Java provides & and | (AND and OR) operators that are similar to && and || but that force the evaluation of the two operands. They don't short-circuit.
Java provides operators for combining comparison and assignment. They are &= (AND equals), |= (OR equals), and ^= (XOR equals).
Bitwise operations
Java supports the & (AND), | (OR), and ^ (XOR) operators of C++ for performing logical operations on the bits of integer variables
Java supports the << (left shift) and >> (right shift) operators of C++ for shifting the bits of integer variables
Java provides an additional >>> (unsigned right shift) operator which always inserts a zero bit in the left-most position (the sign bit)
All bitwise operators can be combined with assignment (&=, |=, ^=, <<=, >>=, and >>>=)
Example:
// Variables for holding two integers.
int first;
int second;
// Prompt for and read the two integers.
System.out.print("First integer: ");
first = Keyboard.readInt();
System.out.print("Second integer: ");
second = Keyboard.readInt();
// Display the results of various bitwise operations.
System.out.println("\n\t" + first + " & " + second + " = " +
(first & second));
System.out.println("\t" + first + " | " + second + " = " +
(first | second));
System.out.println("\t" + first + " ^ " + second + " = " +
(first ^ second));
System.out.println("\t" + first + " << " + second + " = " +
(first << second));
System.out.println("\t" + first + " >> " + second + " = " +
(first >> second));
System.out.println("\t" + first + " >>> " + second + " = " +
(first >>> second));Note: If a shift value greater than 31 is specified, only the right-most 5 bits of the shift factor will be used for shifting. In other words, a shift factor of 32 is the same as a shift factor of 0.
Decision handling
Java supports if and if-else statements based upon the value of a boolean expression
The switch statement in Java is essentially the same as its C++ counterpart
Looping
Java is essentially the same as C++ by fully supporting for, while, and do-while statements
Java uses the break and continue statements in much the same way as C++
Example:
// Variable for loop control.
char again;
// Variables for holding fahrenheit and celsius temperatures.
double tempF;
double tempC;
// This is the main processing loop. It converts one fahrenheit
// temperature and asks the user if they want to convert another.
do {
// Prompt for and read the fahrenheit temperature.
System.out.print("Enter the fahrenheit temperature (nn.n): ");
tempF = Keyboard.readDouble();
// Convert to celsius and display the result.
tempC = 5 * (tempF - 32) / 9;
System.out.println("Celsius equivalent is " + tempC);
// Ask the user if they want to convert another temperature and
// read their reply.
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
} while (again == 'Y' || again == 'y'); // Loop as required.
Defining a method
A method in Java is defined much like a function in C++. The syntax is nearly the same.
Java methods require no prototype (the compiler is smarter). You can even code a call before the definition of the method being called.
All methods must be defined within a class but may not be defined within another method
"Class" methods are defined using the static keyword. They are associated with the class itself and not an object (instance) of the class.
Unlike C++ (which assigns an unpredictable value), method local ("automatic") variables in Java are not initialized. This is a common cause of compile errors.
Example:
// This method converts a fahrenheit temperature to celsius.
public static double fToC(double oldTemp) {
double newTemp = 5 * (oldTemp - 32) / 9;
return newTemp;
}Notes:
Because the method is public, it may be called from outside the class.
Because the method is static, it may be called without instantiating an object of the class.
The fToC method expects a double parameter representing the fahrenheit temperature and returns a double representing the celsius temperature.
The variable newTemp is local to the method and may not be accessed from outside the method. Unlike C++ which permits the redefinition and hiding of variables within nested code, Java will not allow the variable to be redefined elsewhere in the method or in nested statement blocks.
Calling a method
identifier(arguments)
where the identifier is the name of the method. If the method is in a different class, the class name must be coded as a qualifier. For example,
System.out.println("Celsius equivalent is " + Utility.fToC(tempF));
calls the method named fToC in a class named Utility and passes it the value of the variable tempF. The result is converted to a string and appended to the string literal before displaying on the console.
In Java, you must match the number and order of arguments as specified in the method header. If corresponding data types don't match, automatic conversion is attempted. Some work (such as int to double) and some do not (such as double to int).