_ | | __ ___ ____ _ _ | |/ _` \ \ / / _` | | |_| | (_| |\ V / (_| | \___/ \__,_| \_/ \__,_| As Different From C++ ~~~~~~~~~~~~~~~~~~~~~ Everything has to be in a class; class static variables are used in place of globals. Main is also a member of the class, and the class of which it is a member is specified on the command line to run the program. Operators Because Java does not have unsigned types, it instead has a special unsigned-right-shift operator, >>>, which uses 0 extension instead of sign extension. "instanceof" is a built-in operator. synchronized (expression) {block} For threads. expression must be an object or an array, and is the thing that is locked while executing the block. assert boolean_assertion : optional_error_code Will not run the condition in optimized mode, so avoid side effects. Foreach There is a python-like iterator introduced in Java 1.5, java.lang.Iterable, on the Iterator<> interface. It looks like: for (declaration : expression) body Exceptions ~~~~~~~~~~ All sublcasses of java.lang.Throwable by convention. java.lang.Error By convention, but not by mandate, this is reserved for the JVM and users do not implement more of them. Generally they cannot usefully be caught. java.lang.Exception All subclasses are checked unless they are subclasses of java.lang.RuntimeException Conceptually, "checked exceptions" must be either handled by the caller or explicitly declared as being passed on. They are part of the API, and creating checked exceptions creates a burden on the caller to be aware of them and explicitly handle them in some way. Use them only when it is reasonable for the caller to be able to do something other than propagate them or abort. Standard Types ~~~~~~~~~~~~~~ Remember there are no unsigned types, and that chars are 16 bits because everything is based on unicode. Only built-in types are values; everything else is a reference (some people will say that in function calls "the reference is passed by value", which is technically true but arguably misleading). All assignment, therefore, just points references. Copies are made with clone(), inherited from java.lang.Object, which might throw CloneNotSupportedException. Also, the return value has to be cast (why? shouldn't that be fixed with covariant return types?). clone() is a shallow copy, and there is no built-in deep copy. Comparisons are also of references by default, which is sort of useless. Use the .equals() member function, which will provide the same semantics as == when it is not overridden. There is a basic type Class; you can get the class object corresponding to a class from "classname.class". "Widening" and "narrowing" conversions do not refer to storage space, but rather the range of allowable types. "Widening" means converting to a superclass; "narrowing" converting to a subclass. The latter requires explicit casts. Primitive Types: Starting in Java 1.5, there are implicit casts (called "boxing" and "unboxing") between the primitive type and the object wrapper. char Character byte Byte short Short int Integer long Long float Float double Double boolean Boolean void Void As of 1.5, there are also enums. They're not likc C enums which are represented as integers; the enum is a type, and each possible value is an instance of the type, so they're really object-oriented enums. They are subclasses of java.lang.Enum, but cannot be produced with the usual extension syntax. They provide toString() and valueOf() to convert back and forth from a string representation of their text names. Normally they are callsed Classname.VALUE, except in switch statements, where the Classname *must* be omitted. java.util.EnumMap and EnumSet are optimized for enum types. For more flexibility, it is possible to define one's own fields, methods, and constructors on enum types, which can associate additional data. Enums may implement interfaces and may have anonymous value-specific bodies. The constructor and instance initializers may not use the static fields of the type, because they have not been constructed yet. Arrays: Arrays, even of builtin types which are not objects, are objects and inherit from java.lang.Object. Unlike in C, the brackets generally go after the type, not the variable. The C-like syntax is supported for compatibility, but is discouraged. Arrays can be initialized with elements in {}. All accesses are overrun checked at runtime. .length is not a function. As of 1.5, arrays are iterables. Copy arrays with .clone() or System.arraycopy(). There are more functions in java.util.Arrays, such as equals(), since the built-in .equals() is just ==, which is probably wrong. Multidimensional arrays are arrays of arrays. Packages ~~~~~~~~ java.lang is always implicitly imported. java, javax, and sun are all controlled by sunw. For others, it is recommended to use a domain name you control in reverse order. On-demand import is done with "import foo.bar.*" You can disambiguate at importation time if there is a conflict by then explicitly importing one of the ones with the same name. All overloaded functions with the same name are imported, and there is no conflict in importing the same name from multiple places if the signatures don't match. Static members are importable as of 1.5. Classes ~~~~~~~ @annotation modifiers CLASS name EXTENDS name IMPLEMENTS name, name2, ... Available modifiers are: public No other access control; public or blank abstract Required if any methods are abstract final Cannot be extended strictfp As for methods, applied to all. If not otherwise specified, top-level classes are "package" access. The only alternative you can specify is "public". There are four levels of access control applied to all class members: Keyword public protected (blank) private Access Level Public Protected Package Private Defining Class yes yes yes yes Same Package yes yes yes no Subclass yes yes no no Non-Subclass yes no no no Construction: Constructors have the name of the class and no return time. You can invoke a different constructor by using this() as a function call, but only as the first statement in a constructor.To call the superclass constructor, use super() with appropriate arguments and the same restrictions. If you do not call it, the call is inserted for you. If there is no constructor with no arguments, your constructor will not compile. Class members (both instance and static) are initialized to a default value; stack variables are not. Explicit class initialization can be specified with a "static { } " block in the class. This method is called "clinit" in the output. Similarly, as an alternative to a constructor, instance initialization is simply an unnamed block in the class. They exist to support anonymous inner classes, which cannot have a constructor because they have no name, and are generally not used otherwise. Destruction works badly. finalize() is called at garbage collection time, which is unpredictable. It does not automatically call the superclass' finalize. If B extends A, with overridden function F, and you're making a B, and you call F() from A's constructor, you get B's version of F, not A's. This is opposite C++. Nested Classes: member classes may have all types of access, including private and protected. static member classes are basically the same as top-level classes, but in a different namespace. instances of nonstatic member classes are always associated with an instance of the containing class. This can be used with callbacks to work around the fact that there are no function or member pointers in java. To access members of the containing class, use the syntax ClassName.membername. To support this, no member class can have the same name as a containing class or package. Local classes are defined within a block of code. Anonymous classes are a subset of these and are expressions, not statements, so they can be constructed in functional calls and so forth. Local classes cannot have access control modifiers and cannot be static, and can use only final variables of its enclosing class, because the class could outlast its enclosing method. There is debate about whether they qualify as "real" closures. anonymous classes get constructed like this new class-or-interface-name (args) {body} The class or interface name is that of the class being extended, so it would be Object if you're not extending anything. There is no constructor that can take arguments, so they are implicitly passed to the superclass, and cannot be given in the case that an interface is being extended. Interfaces ~~~~~~~~~~ Java's response to multiple inheritance. Interfaces are always public, contain only public functions, and contain no implementation code. A common practice is to create an interface, and then offer an abstract class that partially implements the interface, so the user may choose whichever is more convenient. "marker interfaces" are empty. They convey one bit of information by being present. It is possible to import constants through an interface, and is used in some of the java libraries, but is not recommend practice because it goes against the principle of an interface being public. Functions ~~~~~~~~~ Functions can exist only as members of classes. main() is always a static void function, and takes String[] as an argument. The following modifiers exist: abstract has no body; not instantiable final cannot be overridden or hidden native means it is a call to C/C++ library public, protected, private static class method strictfp no optimizations on floating point synchronized wraps entire function in a lock Functions in derived classes may have covariant return types as of Java 1.5. There is no need to indicate that functions should have dynamic dispatch, as with C++'s "virtual" keyword. Instead, use "final" to indicate functions which should *not* have it. In Java, private functions do NOT exhibit polymorphic behavior. If B extends A, and they both have a private function F, A's functions do *not* call B's version of F as they would if it were a public or protected function. In C++, private functions are not a special case like this. To get the superclass's version of the function, user super.func(). For overridden functions (as opposed to hidden), there is no easy way to explicitly invoke versions further up the chain than the superclass. A weak form of varargs kind of exists, of the form "Type... name". It is implicitly translated into an array. Data Fields ~~~~~~~~~~~ There are no global variables; use static class members. Magic variables: this super The following modifiers exist: public, protected, private static associated with class, not instance final cannot be changed once initialized transient does not need serialization volatile do not cache in register (as in C) To refer to a superclass's version of a variable that has been hidden, user super.name or ((SuperClass) this).name for classes that are further up the heirarchy, since you can't do super.super.name. Generics ~~~~~~~~ Generics look like templates, but behave somewhat differently. They can be used without a type specified, in which case they are called "raw". There are no implicit casts based on paramterization type, so you can't cast a List to List, even though you can cast Character to Integer (everything is a reference, so if you did that, you could modify the original List by adding things of the wrong type). It is not permissible to create arrays of parameterized types. To indicate an unknown type in an argument, use ?. However, you then can't perform any operations that do not exist for all types that are allowed in the wildcard, You can put constraints on the ? by saying "? extends Type [& Type2]", which then allows you to perform all operations which are guaranteed to be present based on this constraint. You say "extends", not "implements", even if it's an interface. The other direction is given as "? super Type". Upper-bounded collections are effectively read-only. With a lower-bounded collection, it is possible to write the most restrictive type; reads will return Object. The convention for writing generics is to use a single capital letter for the type. If you have to explicitly give the type of a method, it is given after the period and before the method name: foo.baz() However, unlike in C++ templates, the Java compiler is also willing to infer based on return type, so this is not necessary as often as one might think. Generic information is not available anymore at runtime. One consequence of this is that no subclass of Throwable may be made generic. It is generally not permitted to implement two different parameterizations of the same interface - i.e., one cannot be Comparable and also Comparable. Annotations ~~~~~~~~~~~ Annotations can store any key/value pairs, but are not used in any way by the JVM (what about reflections?). Some are processed by the compiler, some are processed by tests, and so forth. Reference ~~~~~~~~~ java.lang.Object: The base of all objects. Inheritance from this is implied if nothing is specified as being extended. protected Object clone() boolen equals(Object o) protected void finalize() Class getClass() int hashCode() void notify() void notifyAll() String toString() void wait(), void wait(long timeout), void wait(long timeout, int nano) http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html vi: set tw=70: