Friday, 30 July 2010

Output or write on Standard output in java

print
double x=5;
System.out.print(x);

println
This will print the item and put the cursor in new line.
System.out.println(x);

printf
System.out.printf("Hello, %s. Next year, you'll be %d", name, age);

write
System.out.write(x);
It is simpler to use print and println than write.

You can see formatting output in java here.

Wednesday, 28 July 2010

Strings in java

Conceptually, Java strings are sequences of Unicode characters. For example, the string "Java\u2122" consists of the five Unicode characters J, a, v, a, and ™. Java does not have a built-in string type. Instead, the standard Java library contains a predefined class called, naturally enough, String. Each quoted string is an instance of the String class:

String e = ""; // an empty string
String greeting = "Hello";

Length
The length method yields the number of code units required for a given string in the UTF-16 encoding. For example:

String greeting = "Hello";
int n = greeting.length(); // is 5.


To get the true length, that is, the number of code points, call

int cpCount = greeting.codePointCount(0, greeting.length());


The call s.charAt(n) returns the code unit at position n, where n is between 0 and s.length() – 1. For example,

char first = greeting.charAt(0); // first is 'H'
char last = greeting.charAt(4); // last is 'o'

To get at the ith code point, use the statements

int index = greeting.offsetByCodePoints(0, i);
int cp = greeting.codePointAt(index);


NOTE
Java counts the code units in strings in a peculiar fashion: the first code unit in a string has position 0. This convention originated in C, where there was a technical reason for counting positions starting at 0. That reason has long gone away and only the nuisance remains. However, so many programmers are used to this convention that the Java designers decided to keep it.

Why are we making a fuss about code units? Consider the sentence is the set of integers

The character requires two code units in the UTF-16 encoding. Calling
char ch = sentence.charAt(1)

doesn't return a space but the second code unit of . To avoid this problem, you should not use the char type. It is too low-level.

If your code traverses a string, and you want to look at each code point in turn, use these statements:

int cp = sentence.codePointAt(i);
if (Character.isSupplementaryCodePoint(cp)) i += 2;
else i++;

Fortunately, the codePointAt method can tell whether a code unit is the first or second half of a supplementary character, and it returns the right result either way. That is, you can move backwards with the following statements:

i--;
int cp = sentence.codePointAt(i);
if (Character.isSupplementaryCodePoint(cp)) i--;

Substrings
You extract a substring from a larger string with the substring method of the String class. For example,

String greeting = "Hello";
String s = greeting.substring(0, 3);

creates a string consisting of the characters "Hel".

The second parameter of substring is the first code unit that you do not want to copy. In our case, we want to copy the code units in positions 0, 1, and 2 (from position 0 to position 2 inclusive). As substring counts it, this means from position 0 inclusive to position 3 exclusive.

There is one advantage to the way substring works: Computing the number of code units in the substring is easy. The string s.substring(a, b) always has b - a code units. For example, the substring "Hel" has 3 – 0 = 3 code units.

String Editing
The String class gives no methods that let you change a character in an existing string. If you want to turn greeting into "Help!", you cannot directly change the last positions of greeting into 'p' and '!'. If you are a C programmer, this will make you feel pretty helpless. How are you going to modify the string? In Java, it is quite easy: concatenate the substring that you want to keep with the characters that you want to replace.

greeting = greeting.substring(0, 3) + "p!";

This declaration changes the current value of the greeting variable to "Help!".

Because you cannot change the individual characters in a Java string, the documentation refers to the objects of the String class as being immutable. Just as the number 3 is always 3, the string "Hello" will always contain the code unit sequence describing the characters H, e, l, l, o. You cannot change these values. You can, as you just saw however, change the contents of the string variable greeting and make it refer to a different string, just as you can make a numeric variable currently holding the value 3 hold the value 4.

Isn't that a lot less efficient? It would seem simpler to change the code units than to build up a whole new string from scratch. Well, yes and no. Indeed, it isn't efficient to generate a new string that holds the concatenation of "Hel" and "p!". But immutable strings have one great advantage: the compiler can arrange that strings are shared.

To understand how this works, think of the various strings as sitting in a common pool. String variables then point to locations in the pool. If you copy a string variable, both the original and the copy share the same characters. Overall, the designers of Java decided that the efficiency of sharing outweighs the inefficiency of string editing by extracting substrings and concatenating.

Look at your own programs; we suspect that most of the time, you don't change strings—you just compare them. Of course, in some cases, direct manipulation of strings is more efficient. (One example is assembling strings from individual characters that come from a file or the keyboard.) For these situations, Java provides a separate StringBuilder class that we describe in Chapter 12. If you are not concerned with the efficiency of string handling, you can ignore StringBuilder and just use String.

Java vs Cpp
C programmers generally are bewildered when they see Java strings for the first time because they think of strings as arrays of characters:

char greeting[] = "Hello";


That is the wrong analogy: a Java string is roughly analogous to a char* pointer,

char* greeting = "Hello";

When you replace greeting with another string, the Java code does roughly the following:

char* temp = malloc(6);
strncpy(temp, greeting, 3);
strncpy(temp + 3, "p!", 3);
greeting = temp;

Sure, now greeting points to the string "Help!". And even the most hardened C programmer must admit that the Java syntax is more pleasant than a sequence of strncpy calls. But what if we make another assignment to greeting?

greeting = "Howdy";

Don't we have a memory leak? After all, the original string was allocated on the heap. Fortunately, Java does automatic garbage collection. If a block of memory is no longer needed, it will eventually be recycled.

If you are a C++ programmer and use the string class defined by ANSI C++, you will be much more comfortable with the Java String type. C++ string objects also perform automatic allocation and deallocation of memory. The memory management is performed explicitly by constructors, assignment operators, and destructors. However, C++ strings are mutable—you can modify individual characters in a string.

Concatenation
Java, like most programming languages, allows you to use the + sign to join (concatenate) two strings.

String expletive = "Expletive";
String PG13 = "deleted";
String message = expletive + PG13;

The above code sets the variable message to the string "Expletivedeleted". (Note the lack of a space between the words: the + sign joins two strings in the order received, exactly as they are given.)

When you concatenate a string with a value that is not a string, the latter is converted to a string. (As you see in Chapter 5, every Java object can be converted to a string.) For example:

int age = 13;
String rating = "PG" + age;

sets rating to the string "PG13".

This feature is commonly used in output statements. For example,

System.out.println("The answer is " + answer);

is perfectly acceptable and will print what one would want (and with the correct spacing because of the space after the word is).

Testing Strings for Equality
To test whether two strings are equal, use the equals method. The expression

s.equals(t)

returns TRue if the strings s and t are equal, false otherwise. Note that s and t can be string variables or string constants. For example, the expression

"Hello".equals(greeting)

is perfectly legal. To test whether two strings are identical except for the upper/lowercase letter distinction, use the equalsIgnoreCase method.

"Hello".equalsIgnoreCase("hello")

Do not use the == operator to test whether two strings are equal! It only determines whether or not the strings are stored in the same location. Sure, if strings are in the same location, they must be equal. But it is entirely possible to store multiple copies of identical strings in different places.

String greeting = "Hello"; //initialize greeting to a string
if (greeting == "Hello") . . .
// probably true
if (greeting.substring(0, 3) == "Hel") . . .
// probably false

If the virtual machine would always arrange for equal strings to be shared, then you could use the == operator for testing equality. But only string constants are shared, not strings that are the result of operations like + or substring. Therefore, never use == to compare strings lest you end up with a program with the worst kind of bug—an intermittent one that seems to occur randomly.

Difference from cpp
If you are used to the C++ string class, you have to be particularly careful about equality testing. The C++ string class does overload the == operator to test for equality of the string contents. It is perhaps unfortunate that Java goes out of its way to give strings the same "look and feel" as numeric values but then makes strings behave like pointers for equality testing. The language designers could have redefined == for strings, just as they made a special arrangement for +. Oh well, every language has its share of inconsistencies.

C programmers never use == to compare strings but use strcmp instead. The Java method compareTo is the exact analog to strcmp. You can use

if (greeting.compareTo("Hello") == 0) . . .

but it seems clearer to use equals instead.

The String class in Java contains more than 50 methods. A surprisingly large number of them are sufficiently useful so that we can imagine using them frequently. The following API note summarizes the ones we found most useful.

NOTE
You will find these API notes throughout the book to help you understand the Java Application Programming Interface (API). Each API note starts with the name of a class such as java.lang.String—the significance of the so-called package name java.lang is explained in Chapter 4. The class name is followed by the names, explanations, and parameter descriptions of one or more methods.

We typically do not list all methods of a particular class but instead select those that are most commonly used, and describe them in a concise form. For a full listing, consult the on-line documentation.

We also list the version number in which a particular class was introduced. If a method has been added later, it has a separate version number.

Command-Line Parameters in java

Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings, namely, the arguments specified on the command line.
For example, consider this program:

public class Message
{
public static void main(String[] args)
{
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + a[i]);
System.out.println("!");
}
}


If the program is called as


java Message -g cruel world

then the args array has the following contents:

args[0]: "-g"

args[1]: "cruel"

args[2]: "world"

The program prints the message

Goodbye, cruel world!

Differing from cpp
In the main method of a Java program, the name of the program is not stored in the args array. For example, when you start up a program as



java Message -h world
from the command line, then args[0] will be "-h" and not "Message" or "java".
While in c++ program name is also stored


Datatypes, variables and arrays in java

Variables

Variables are temporary data holders. Variable names are identifiers. Variables are declared with a datatype. Java is a strongly typed language as the variable can only take a value that matches its declared type. This enforces good programming practice and reduces errors considerably. When variables are declared they may or may not be assigned or take on a value (initialized). Examples of each of the primitive datatypes available in Java are as follows:

byte x,y,z;             /* 08bits long, not assigned, multiple declaration */
short numberOfChildren; /* 16bits long */
int counter;            /* 32bits long */
long WorldPopulation;   /* 64bits long */

float pi;               /* 32bit single precision */
double avagadroNumber;  /* 64bit double precision */
boolean signal_flag;    /* true or false only */
char c;                 /* 16bit single Unicode character */

Constant variables
Variables can be made constant or read only by prepending the modifier final to the declaration. Java convention uses all uppercase for final variable names.

Local Variables
Local variables (also known as automatic variables) are declared in methods and in code blocks. The automatic variables are not automatically initialized.
A java programmer should explicitly initialize them before first use. These are automatically destroyed when they go out of scope.

Field Variables and Local Variables Field variables are variables that are declared as members of classes. Local variables, also referred to as automatic variables, are declared relative to (or local to) a method or constructor. <

Automatic Initialization Note
Field variables and the elements of arrays are automatically initialized to default values. Local variables are not automatically initialized. Failure to initialize a local variable results in a compilation error.

Primary or primitive data types in java


There are 4 primary classes of primary data types in java
Integers
Floats
Boolean
Characters
 There are eight primitive types in Java. Four of them are integer types; two are floating-point number types; one is the character type char, used for code units in the Unicode encoding schem; last 1 is boolean.

Default Values for various data types.

Inheritance in java

Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An example of where this could be useful is with an employee records system. You could create a generic employee class with states and actions that are common to all employees. Then more specific classes could be defined for salaried, commissioned and hourly employees. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.

The Object class is the highest superclass (ie. root class) of Java. All other classes are subclasses (children or descendants) inherited from the Object class. The Object class includes methods such as:
clone()equals()copy(Object src)finalize() getClass()
hashCode()notify() notifyAll()toString()wait()

Inheritance in Java
Java uses the extends keyword to set the relationship between a parent class and a child class. For example using our Box class from notes about class :

public class GraphicsBox extends Box
 
The GraphicsBox class assumes or inherits all the properties of the Box class and can now add its own properties and methods as well as override existing methods. Overriding means creating a new set of method statements for the same method signature (name, number of parameters and parameter types). For example:
// define position locations
    private int left, top;
// override a superclass method
    public int displayVolume()
    {
      System.out.println(length*width*height);
      System.out.println("Location: "+left+", "+top);
    }

When extending a class constructor you can reuse the superclass constructor and overridden superclass methods by using the reserved word super. Note that this reference must come first in the subclass constructor. The reserved word this is used to distinguish between the object's property and the passed in parameter.
   GraphicsBox(l,w,h,left,top)
    {
      super (l,w,h);
      this.left=left;
      this.top=top;
    }
    public void showObj()
    {    System.out.println(super.showObj()+"more stuff here");
     }

The reserved word this can also be used to reference private constructors which are useful in initializing properties.
Special Note:You cannot override final methods, methods in final classes, private methods or static methods.

See Further

Inheritance : cpp vs java
Using super in java
Multilevel inheritance : Calling order of Constructors
Abstract classes
Interfaces in java
Multiple inheritance in java
Inheritance among interfaces in java
Multiple inheritance in java
Abstract classes : cpp vs java
Abstract classes vs Interfaces
Abstract-Interface or skeletal implementations
Various interfaces
Preventing inheritance

Final keyword in java

A java variable can be declared using the keyword final. Then the final variable can be assigned only once. You cannot be modify it afterwards. However it can be used in different contexts.

Following are the places where final can be used:

  1. variables: a final variable can be set once and only once.
    blank final variable - A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it.
  2. fields: a final field can also be set only once, by the constructor of the class which defines it.
  3. methods: a final method cannot be overridden nor hidden.
    final parameters - values of the parameters cannot be changed after initialization.
  4. classes: a final class cannot be extended or inherited.

Other effects of final:

  • Java local classes can only reference local variables and parameters that are declared as final.
  • A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.

Notice how using final is an entirely negative act. The final keyword works by subtracting, limiting default language mechanisms: the ability to override a method, to set a variable or a field. The motivations behind using final fall into three broad categories: correctness, robustness, and finally performance. Seeing them 1 by one.

Final Variables

Final variables come in handy in mostly three situations: 

a) Declare Constants

Coupled with static, final is used to flag constants. This usage is well-known to all Java programmers, so I won't expand much on it. It is useful to know that the value of a field declared constant in that manner will be computed statically if possible, at compile-time.
private static final int ERROR_CODE = 1 + 3 * 4 / 2;
public static final String ERROR_MESSAGE = "An error
occurred with code="
+ ERROR_CODE;

The compiler will compute the value for ERROR_CODE, concatenate the string equivalent of the result, and assign the resulting String to ERROR_MESSAGE.


b) Final Parameters

The following sample declares final parameters:




public void doSomething(final int i, final int j){
// ...
}
final is used here to ensure the two indexes i and j won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style.
Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden.


c) Anonymous Local Classes

The third situation involving final variables is actually mandated by language semantics. In that situation, the Java compiler won't let you use a variable unless it is declared final. This situation arises with closures, also known as anonymous local classes. Local classes can only reference local variables and parameters that are declared final.





public void doSomething(int i, int j){
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};//note the semicolon here
}

The reason for this restriction becomes apparent if we shed some light on how local classes are implemented. An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.


2. Final Fields

A final field can be assigned once and only once, and must be initialized by every constructor of the class that declares it. It is also possible to assign the field directly, in the same statement where it is defined. This simply reflects the fact that such shortcut assignments are compiled into a synthetic constructor. E.g. both the following code samples are correct and strictly equivalent; the first is preferred for being shorter. Initializing outside constructor body

public class MyClass{
//initializing hereitself
private final int i = 2;
}

Initialising in constructor body



public class MyClass{
private final int i;
public MyClass()
{
i = 2;
}
}


3. Using final to Prevent Method Overriding



While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:


class A {

final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {

void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}

Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to
do so, a compile-time error will result.

Methods declared as final can sometimes provide a performance enhancement: The compiler is free to inline calls to them because it “knows” they will not be overridden by a subclass. When a small final method is called, often the Java compiler can copy the bytecode for the subroutine directly inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a method call. Inlining is only an option with final methods. Normally, Java resolves calls to methods dynamically, at run
time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding.



4. Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}


As the comments imply, it is illegal for B to inherit A since A is declared as final.


CPP vs Java on Final – Controversy


‘final’ should not be called as constants. Because when an array is declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifcations. In general context constants will not allow to modify. In C++, an array declared as const will not allow the above scenario but java allows. So java’s final is not the general constant used across in computer languages.

A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static final.

Definition as per java language specification (third edition) – 4.12.4 is “A final variable may only be assigned to once.”(§4.1.2). See notes on final w.r.t Java memory model here -


Java language specification tries to redefine the meaning of constant in the following way!
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).


Immutable Objects


Final is used to construct immutable objects in java. See – Immutable Objects

Declarations and Access Control - Java

te that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization.

Declaring arrays:

For example,use either
int[] x;
or
int x[];
Both are legal positions for the brackets. To declare a multidimensional array, use multiple sets of brackets, e.g. int i[][]; declares a two dimensional array. Note that, for example, int[]i[]; is also legal, and means the same thing. In Java, multidimensional arrays can be "not square" i.e. they are just arrays of arrays, and each of those constituent arrays can be of a different size.

Construct arrays:

Arrays are objects. Use the new keyword to construct them. For example having declared an array i:
int[] i;
you then construct the array and assign it to i as follows:
i = new int[10];
The size of the array is in the brackets (in this example 10). It is common to do both operations in one statement:
int i[] = new int[10];

To initialize an array using loop iteration:

An example:
int array[] = new int[15];
for(int j=0; j
array[j]=j;
}

Write code to initialize an array using the combined declaration and initialization format:

An example:
char c[]= new char[] {'a','b','c','d','e'};
or you can use
char c[]= {'a','b','c','d','e'};

Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. 

Some terms and their synonyms:

Scope/Visibility: Where something can be seen / is accessable from.
Nested/Inner Class: A class whose code sits inside the body of another 'outer' class. It exists 'inside' the class in that it can see the private methods and variables.
Instance/Member: Means the method/variable/nested class belongs to each object which is an instance of the class. The term 'a member' is often used to refer to both methods and variables of this type. Cannot be accessed by statically i.e. without having an instance of the class.
Class/Static: The method/variable/nested class belongs to the class as opposed to the instances of the class. Can be used without creating an instance of the class, but static methods/nested class cannot use instancts variables/methods.
Local/Automatic variable: A variable which is declared within a method or as a parameter to the method. Cannot be seen outside the method.

Scoping Types

"default" or "friendly" - this is where no modifier is used. Means something is only visible to classes in the same package.
protected - can only be accessed by classes in the same package or subclasses of this class. This frequently surprises experienced developers, especially those with a prior backround in the mutant hybrid of object orientated programming and assembly language known as 'C++' :-) To fair the name is misleading, as it sounds like it restricts access, where as it in fact it adds subclasses outside the package to the list of things that can access the item in question, as compared to using "default" access.
public - can be accessed by any other class.
private - can only be accessed from inside the class.

Declare classes using the modifiers public, abstract or final:

public - is visible outside of its package. Without this modifier, the class cannot be accessed outside its package.
abstract - cannot be instantiated, is allowed to contain abstract methods.
final - cannot be subsclassed.

Using the modifiers private, protected, public, static, final, native or abstract:

private - can only be accessed from inside the class. Private members are not inherited by subclasses. Inner classes can be declared private.
protected - can only be accessed by classes in the same package or subclasses of this class.
public - can be accessed by any other class.
static - belongs to the class rather than any particular instance of the class. For variables, effectively, there is just one copy of this variable for all instances of the class, and if an instance changes the value, the other instances see that new value. For methods, it means the method can be called without having created an instance, but within the methodd you cannot use the this keyword, or refer to instance variables and methods directly (without creating an instance and referring to the variable/class in that instance). For inner classes, it means they can be instantiated without having an instance of the enclosing class, but as with static methods, the methods of the inner class cannot refer to instance variables or methods of the enclosing class directly.
final - cannot be changed. Variables are constants, methods cannot be overridden, classes cannot be subclassed. Since Java1.1 you can declare the variable without assigning a value. Once you assign a value, you cannot change it. The are known as 'blank' finals, are frequently used for things like constants you wish to initialise from a configuration file.
native - a method which is not written in java and is outside the JVM in a library.
abstract - a method which is not implemented. Must be implemented in a subclass if that subclass is to be 'concrete' and allow people to instantiate it.

Nested Classes

To define a non-static nested class either in a class or method scope:

Place the class definition (for the nested class) inside another class definition (the outer class) or a method.

To define, in method scope, an anonymous nested class that implements a specified interface:

An anonymous nested class is defined where is it instantiated (in a method). An anonymous nested class must either implement an interface or extend a class, but the implements or extends keywords are not used. For example the following line causes the method to return an object which is an instance of an anonymous nested class:
return new SomeClass() { /*body of the anonymous class goes here*/ };
You might like to think of an anonymous nested class as part of a really long new statement, which happens to contain a class definition, and which is why it has a ";" at the end. The following example calls someMethod(), passing an instance of the anonymous nested class:
someMethod(new SomeClass() { /*body of the anonymous class goes here*/ });
In both cases SomeClass() is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. These classes cannot define a constructor, as they do not have a name that you can use to declare the constructor method. If SomeClass() is a class, the default constructor of that class is called, if you want to use a non-default constructor instead, you supply arguments e.g.:
return new SomeClass(12) { /*body of the anonymous class goes here*/ };
will call the SomeClass constructor which takes an int.

Write code in a non-static method of the outer class to construct an instance of the nested class.

Inner x = new Inner(); constructs an instance of Inner where Inner is a nested class defined in the current class.

Write code to construct an instance on a nested class where either no this object exists, or the current this object is not an instance of the outer class.

You must create an instance of the outer class first. Given a class, Outer, containing a nested class Inner:
Outer.Inner y = new Outer().new Inner();
The above creates an instance of Inner called y, but it had to construct an instance of Outer first. The following example creates the Outer instance on a separate line, the syntax in the second line is the one you use when you already have an instance of the outer class.
Outer x = new Outer();
Outer.Inner y = x.new Inner();
If Inner is static, you can use:
Outer.Inner I= new Outer.Inner();

State which variables and methods in enclosing scopes are accessible from methods of the inner class.

A non-static inner class has access to all member variables and methods of the containing class. If the inner class is defined inside a method, it has access to those method (a.k.a. automatic or local) variables which are declared final, in addition to the above.
A static inner class is restricted in the same way as a static method: it cannot refer to instance variables and methods of the containing class directly (without creating an instance and referring to the variable/class in that instance).

For a given class, determine if a default constructor will be created and if so state the prototype of that constructor.
The default constructor takes no arguments e.g. classname() where classname is the name of you class. A default constructor is automatically created only if you do not create any constructors in your class. If you create a non-default constructor (i.e. one that takes an argument), then you may have to create a default one yourself, if you want there to be one.
All constructors call the default constructor of its parents class (if there is one), and so on up the hierarchy to Object, unless you specify a different constructor using super(...) (to use a constructor in the parent) or this(...). If you use such calls, they must be the first thing in the constructor.

Literals

Literal constants are values that do not change within a program. Numeric constants default to integer or double unless a suffix is appended. Note that a character can be represented by an ASCII equivalent. The literal types are:
  • Boolean: true, false
  • Character: 'c', '\f'
  • String: "Fred", "B and E"
  • Null: null
  • Integer: 5, 0xFF (hexadecimal)
         073 [leading zero] (octal), 5l (long), 0xFFlD (hex)
  • Floating Point: 2.543, -4.1E-6 (double)
         2.543f, 8e12f (float)
Note: Do not use leading zeros to format integers as this can cause an unintended octal meaning. Use spaces instead!
Escape (aka backslash) sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:
SeqUsage SeqUsage
\bbackspace \\backslash
\fformfeed \"double quote
\nnewline \'single quote
\rcarriage return \###Octal encoded character
\thorizontal tab \uHHHHUnicode encoded character