Java for the C++ Programmer
This list of items is intended to help a C++ programmer transition
to Java. It does not intend to in anyway be a tutorial or guide to
the language, just a set of pointers to things that would be
particularly helpful to a C++ programmer to know as they represent
various key (ok, sometimes minor) differences between the
languages.
- All numbers are signed. Well, except for
char
.
- Variables of a class type are always references.
-
In C++ we would think of them as pointers but without ever
using the
->
notation. Java uses the "dot
operator".
-
All objects are on the heap. There is no such
thing as having a local object on the
stack. Reference variables are on the stack, but the
objects are on the heap.
- Arrays are objects, too, so they only exist on the heap.
-
Java uses
null
instead
of NULL
. ( null
is referred to as a
"literal" in Java. In Java terminology it is
not a keyword. This distinction also holds for the
literals true
and false
.) I only
mentioned this as it may come up on a certification exam, not
one of mine.
-
Local variables must be assigned before they are used or it is
a compilation error.
-
To run a program, main must have a String[] parameter. It should
be written as:
public static void main(String[] args) { /* code goes here */ }
const
-
There is no
const
. Well, actually there is a
keyword const
, but it isn't actually used in
the language.
-
The keyword
final
used with variables /
parameters is similar but not quite the same.
-
A final primitive variable is constant, at least after
it first gets assigned to. The assigment/initialization
does not have to be where the variable is defined.
-
Making a reference variables final in Javais like making
a pointer const in C++:
Thing* const p; // p must always point to the same object.
- You cannot do anything equivalent to the following in Java:
const Thing* p; // The object that p points to can not have its fields modified throug p
- The idea of marking a method as const does not have a counterpart in Java. Since objects can't be marked constant, there is not the same need to make methods promise to treat them as constant.
- operators
- Operators cannot be overloaded.
- Well, they did "overload" the
+
and +=
operators for the string class to mean concatenate, but they did that in the language itself. You aren't allowed to overload anything else.
=
- For reference variables, the assignment operator only copies the reference, not the object.
==
- does not mean "equal",
- it means "identical" as in being the same object (i.e., at the same memory location).
- You use or overload the
equals
method (inherited from Object
) if you want to control the definiiton of equality.
- If you do override
equals()
, you should also override hashcode()
.
- Because you often do need to provide an order for your class, there is the
Comparable
interface with requires the compareTo
method.
- Output
- Since you can't overload the output operator (in fact there is no output operator), Java has a method toString (inherited from Object) that is generally overriden when you want a represent an object as a string. This is used most commonly for building up a string to output.
true
and false
print out that way automatically.
enum
constants
- Creating an enum in Java works the same:
enum Fruit {APPLE, BANANA, ORANGE, PEAR};
- However enum constants are not just (typically small) ints as in C++.
- enum defines a kind of class and the constants are instances of the class.
- Methods
toString()
returns a string version. For the constant Fruit.APPLE
, it would be "APPLE". This allows the printing of an enum constant to display as something intelligent, unlike C++ which can only show a number.
ordinal()
returns the small int you would have expected from C++, with the first constant having the ordinal value of zero and each one going up one from there.
static method Enum.valueOf(Suit, "APPLE")
returns Suit.APPLE
. .
if
/ while
/ etc.
- When a
boolean
(not bool) is expected, it must in fact be a boolean expression. No conversions from any other types, including int
or reference.
break
/ continue
can specify a label to "go to".
- Constructors
- Java literature (e.g. The Java Programming Language) uses the term "no-arg constructor" where C++ folk would say "default constructor". If Java literature refers to a default constructor, they mean the system provided no-arg constructor. However a number or authors in the Java community (e.g., Eckel and Horstmann) continue to use the phrase "default constructor" in the same was as it is used in C++. Be careful when you are reading!
- member variables can be initialized explicitly where they are defined, or in "initialization blocks". These initializations take place before the constructor starts.
- No initialization lists!
- To invoke the parent class's constructor (there can only be one parent class) call it explicity in your constructor's body using the keyword
super
for the name of the parent's constructor. As in C++, if you don't then the parent's "no-arg" constructor is called.
- Since member variables are either primitive or references, they don't have to invoke constructors for other classes.
- member variables will automatically be initialized to zero,
false
or null
as appropriate.
- Warning: You can write a method with the same name as the class that is not a constructor. If it has a return type, even
void
, then it is not a constructor. This can be a source of subtle bugs.
- Java does not have default parameter values, so overloaded constructors tend to call each other, using the keyword
this
for the name of the constructor.
- Copy constructor:
- Unlike C++, there is no language support for a copy constructor.
- So, note, there is no copy constructor provided in Java by default as there is in C++.
- Instead, the class
Object
provides a method called clone
and Java programmers are "encouraged" to follow appropriate conventions (similar to what you would do in a C++ copy constructor) for overriding the clone
method if it is desired. This involves, at the least, implementing the Cloneable
interface.
- Separate Compilation
-
You do not separate the definition of a class from the
definitions of its methods. There are no header files and
hence no
#include
's. Note
that import
is really doing a different job. And
because there is no #include
, there is also no
need for "include guards".
- All methods are defined inside their class.
-
Unlike in C++, placing a method definiton inside the class in
Java does not also act as a request to the compiler to inline
the method.
-
The compiler will make up its own mind as to what can/should
be inlined, such as methods marked
final
(meaning
that they can not be overridden).
- Garbage collection
-
means never having to call
delete
. (In fact there
is not delete.) But it still may be a good idea to set your
reference variable to null
, especially if you
have several of them, as in an array.
-
finalize
is not the same thing as a
destructor. In fact you probably don't want to write a
finalizer at any point in the near future.
-
If you do write a finalizer, it is your
responsibility to make it
call
super.finalize()
just before you
finish. In C++ destructors call their parent's destructor
automatically, but in Java finalizers do not.
- Inheritance
-
All classes derive from the class
Object
, which
is the default parent class if no inheritance is
indicated.
- Abstract classes
-
C++ has "pure virtual" methods. The equivalent
in Java is marking the method with the
keyword
abstract
.
-
A class is abstract in Java if-and-only-if the class
itself is marked with the
keyword
abstract
.
-
A class has to be marked abstract if it has any abstract
methods, but it can still be abstract even if it
doesn't have any abstract methods. It just has to be
marked abstract in order to be abstract.
- No multiple inheritance.
-
Except you can inherit from both a class and one
or more interfaces. All methods in interfaces are
implicitly abstract and they have no non-static member
variables.
-
protected access is less safe in Java than it is in
C++. In Java protected includes package access.
-
The keywords
goto
and const
are just
there to help the compiler catch C/C++ programmer errors. These
keywords do not do anything in Java.
- Parameters
-
You must provide the name of a parameter in Java. In
C++ it is allowed to leave off a parameter's name if you are
not going to refer to it. This is not allowed in Java.
- Access permissions
- There are four: public, private, protected and the default "package".
- The default, package access, means that any code in your package can access the method / field.
- protected is an extension of package. It also allows any class that inherits from your class to access the method / field, even if it is not in the same package.
- The order of the access permissions from most restrictive to least is: private, package, protected and public.
- Access persmissions are applied to each member separately, not to whole groups.
- Strings
- Strings in Java are held in the class called
String
. Note the capital S.
- Strings are immustable. This means that you cannot change any of the characters in a String.
- That doesn't mean that you can't change what a String variable refers to. The following is ok:
String s = "Felix the Cat";
s = "Heathcliffe";
- operators
- The + operator concatenates two strings together creating a new string.
- methods
subtring(int start, int stop)
. Like C++'s substr
, but second argument is the position of the first character in the string not to include, unlike C++ where the second argument is the length of the desired substring.
- Use the method
equals()
instead of ==
to compare strings.
- Use the method
compareTo
instead of the comparison operators (<, <=, >, >=).
- Use the method
charAt(int index)
instead of the []
operator
- Mutable strings. Java provides the class
StringBuilder
- Exceptions
- No "
catch (...)
". Instead all thrown objects derive from Throwable
, so we can use that as the umbrella type, if we want to ensure that anything thrown is caught. Generally catching Exception
is better than catching Throwable
because Throwable
also represents things that an application program can't really do anything about (i.e., the class Error
and its descendants).
- Compilation error if you put a more general catch clause before a more specific one.
- The only things that can be thrown are objects whose class is an instanceof
Throwable
. Actually, you shouldn't inherit directly from Throwable
, instead you should inherit from Exception
or one of its subclasses.
- Any exception class that is an instanceof
Exception
but is not an instanceof RuntimeException
is called a "checked" exception.
throws
clause, aka exception specification.
- A method whose code might throw a checked exception must either catch the exception or declare it with a throws clause.
- Unlike C++ where the compiler is allowed to ignore a throws clause, in Java with a checked exception that is not caught, the throws clause is mandatory.
- Java has a finally clause.
- Runs whether or not an exception was thrown.
- Only thing that can prevent it from running is if the try or catch block exits.
- It can only come after any catch clauses.
- If there is a finally clause then there do not have to be any catch clauses.
- Static members. C++ uses the scope qualification operator
::
where Java uses the member selection operator . (aka dot-operator).
- C++:
Math::PI
- Java:
Math.PI
- STL and Java Collections Framework
- STL algorithms work on half-open ranges. These are defined by iterators, or anything that behaves like an iterator, such as a pointer into an array. Java's algorthms instead, work on entire "collections". So, instead of passing in a range, you might pass a List.
- one [minor] impact is that in Java you can't sort / search / etc. a portion of a collection. No, I never had occasion to do that in C++.
Maintained by John Sterling: jsterling@poly.edu. Last updated
June 28, 2008
Please send me any corrections, additions or other comments regarding this document.