Objective 1.1 |
---|
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 and so forth). 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. |
It is simple to recognize Java keywords, but it may be confused for some people to tell difference with the language you are using. Remember
abstract | do | if | package | synchronized |
boolean | double | implements | private | this |
break | else | import | protected | throw |
byte | extends | instanceof | public | throws |
case | false | int | return | transient |
catch | final | interface | short | true |
char | finally | long | static | try |
class | float | native | strictfp | void |
const | for | new | super | volatile |
continue | goto | null | switch | while |
default | assert | enum |
boolean byte char short int long float double |
private protected public |
These keywords control the visibility of variables and methods inside the class.
Keywords used for modifiers are:
abstract final static private protected public synchronized transient native volatile strictfp |
try catch finally throw throws |
break continue do while for switch case default if else |
package import class extends implements interface new return instanceof this super void |
true false null |
const goto |
Modifier | Used on | Meaning |
abstract | class interface method |
Contains unimplemented methods and cannot be instantiated. All interfaces are abstract. Optional in declarations No body, only signature. The enclosing class is abstract |
final |
class method field variable |
Cannot be subclassed Cannot be overridden and dynamically looked up Cannot change its value. static final fields are compile-time constants. Cannot change its value. |
native |
method | Platform-dependent.
No body, only signature |
none(package) |
class interface member |
Accessible only in its package Accessible only in its package Accessible only in its package |
private |
member |
Accessible only in its class(which defines it). |
protected |
member |
Accessible only within its package and its subclasses |
public |
class interface member |
Accessible anywhere Accessible anywhere Accessible anywhere its class is. |
strictfp |
class method |
All methods in the class are implicitly strictfp. All floating-point computation done is strictly conforms to the IEEE 754 standard. All values including intermediate results must be expressed as IEEE float or double values. It is rarely used. |
static |
class method field initializer |
Make an inner class top-level class A class method, invoked through the class name. A class field, invoked through the class name one instance, regardless of class instances created. Run when the class is loaded, rather than when an instance is created. |
synchronized |
method |
For a static method, a lock for the class is acquired before executing the method. For a non-static method, a lock for the specific object instance is acquired. |
transient |
field |
Not be serialized with the object, used with object serializations. |
volatile |
field |
Accessible by unsynchronized threads, very rarely used. |
Modifier | Class | Variable | Method | Constructor | Free-Floating Block |
public | yes | yes | yes | yes | no |
protected | no | yes | yes | yes | no |
none or package or default | yes | yes | yes | yes | yes |
private | no | yes | yes | yes | no |
final | yes | yes | yes | no | no |
abstract | yes | no | yes | no | no |
static | no | yes | yes | no | yes |
native | no | no | yes | no | no |
transient | no | yes | no | no | no |
volatile | no | yes | no | no | no |
synchronized | no | no | yes | no | yes |
strictfp | yes | no | yes | yes | no |
Whenever you declare a data type, you follow the type/name pair rule. That means type first and followed by an identifier.
To declare an int type:
int num; |
To declare an object type:
Employee emp; |
You can declare same type variables in one line with comma to separate:
double payRate, payment, total; |
Or initialize part of or all of them.
double payRate=0.5, payment=1000, total; |
Declaring a class means you define a new reference type and describe how the class is implemented. You declare a class by using keyword class, a class identifier and a pair of curly braces. Everything is included in the class block(inside the curly brace). The formula is:
[access modifiers] class className [extends superClass] [implements interface1, interface2,..]{ //fields //methods //member classes //member interfaces //constructors //instance initializers //static initializers //inherited members if a superclass exists. } |
For example, the simplest class would be:
class Hello{} |
No-body class is a legal class.
The HelloWorld class with a body
public class HelloWorld { public static void main(String[] args){ System.out.println("Hello World"); } } >java HelloWorld Hello World |
If a class is declared public, then it can be referred to from other packages. In the example,
package scjp.test; public class Test { int a, b, c; } //in another file import scjp.test.*; class TestFeature { Test t = new Test(); } |
class Test is available for class TestFeature because class Test is a public class, it can be referred to from other packages.
In the following example,
package scjp.test; class Test { int a, b, c; } //in another source file import scjp.test.*; class TestFeature { Test t = new Test();//error } |
the compiler will generate an error, indicating that class Test is not accessible because class Test is not public and it can only be accessible from its own package.
A class declared without any modifier, especially without any access modifier can only be accessed in its own package. In the example,
package scjp.test; class Test { int a, b, c; } //in another source file package scjp.test; class TestFeature { Test t = new Test(); } |
classes TestFeature and Test are in the same package scjp.test, thus class Test is accessible in the class TestFeature.
If a class is incompletely implemented, it must be declared abstract, such a class cannot be instantiated, but can be extended by subclasses. Under the following conditions, a class must be declared abstract.
In the example:
abstract class Employee { String name, address, phone; int companyID = 888; int getCompanyID() { return companyID; } ... abstract double calculateSalary(double rate, double hours); } abstract class SalesDepartment extends Employee { ... double sales; .. } class FrontDeskEmployee extends Employee { ... double calculateSalary(double rate, double hours) { ... return xx; } } |
a class Employee is declared that must be declared abstract, because it contains a declaration of an abstract method named calculateSalary. The subclass of Employee named SalesDepartment inherits the abstract method calculateSalary, but not provide any implementation, so it must also be declared abstract. On the other hand, the subclass of Employee named FrontDeskEmployee provides an implementation of calculateSalary, so it needs not be declared abstract.
A compile-time error occurs if an attempt is made to create an instance of an abstract class like:
Employee em = new Employee(); //wrong or Employee em = new SalesDepartment();//wrong |
would result in a compile-time error because both Employee and SalesDepartment are abstract classes. The correct declaration would be
Employee em = new FrontDeskEmployee(); |
For a class implementing one or more interfaces,
interface A { void amethod(); } interface B { void bmethod(); } abstract class C implements A, B { amethod() {} } class D implements A, B { amethod() {} bmethod() {} } |
class C should be declared abstract because it doesn't provide implementation for bmethod of B interface; and class D should not be declared abstract because it provides implementations for amethod and bmethod in both interfaces A and B which class D implemented.
An abstract class may have constructors or a main(). You can execute a compiled abstract class if it has a correctly formed main() method.
If you want your class to be subclassed and to complete the implementation in the subclass, you should declare such class abstract.
If you don't want a class to be subclassed, you should declare it final.
If you don't want a class to be instantiated, you may declare the class with a private default constructor. An example is class Math.
A class can be declared final if its definition is complete and no subclasses are desired or required. A final class cannot have any subclasses. It is not possible for a class to be declared both final and abstract. Because a final class never has any subclasses, the methods of a final class are implicitly final and are never overridden.
final class TestA {} class TestB extends TestA {}//wrong |
A class can be declared strictfp if you intent to make all float or double expressions within the class declaration be explicitly FP-strict. This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp.
public strictfp class Test { double d; float f; Test(double d) { this.d = d; } void method(double d) {} ... } |
strictfp modifier is rarely used. It is not in the test scope. It is listed here just for your information.
package statement should come first if it is present. import statement should be first if package statement is not present. class declaration should be the third if package and import statements are both present.
A class with modifier public and package and import statements.
package org.javacamp; import java.awt.*; public class Test { .... } |
A class can only "extends" one super class, but "implements" many interfaces.
A class can only extend one super class. Assume Shape is a super class.
public class Circle extends Shape{ ... } |
A class can implement many interfaces.
package org.javacamp; import java.awt.*; public class Circle extends Shape implements WindowListener, MouseListener{ .... } |
A nested class is any class whose declaration occurs within the body of another class or interface. A nested class is often referred to inner class.
An inner class may have public, protected, default(no-access modifier), private, final, and static modifiers, while an outer class can only use public, abstract, final, strictfp and default modifiers. For example:
class A{ static int i = 10; } class Outer{ class Inner extends A{ //nonstatic member class static final int i = 3; } static class Nested{ //static member class static int z = 5; } interface InterInner{} //implicitly static interface void method() { class Local {} //local class } } |
There are 4 kinds of member classes.
A static inner class is a nested class(or called top-level class). If you don't need a connection between the inner class object and the outer class object, then you can make the inner class static.
public class Outer { static class Nested { } } |
A static inner class may contain static fields.
class Outer{ static class Nested { static int z = 5; // ok, Nested is a static } } |
To access a static inner class, use formula:
OuterClass.InnerClass |
To reference to the above example, you use
Outer.Nested |
A class may contain an interface. This inner interface is implicitly static.
class Outer{ class inner{} interface InterInner{} // implicitly static } |
Note: Member interfaces are always implicitly static.
A nonstatic member class is an inner class without static modifier.
An inner class may not contain a static field, but if that field is a constant, it is ok.
class A{ static int i = 10; } class Outer{ class Inner extends A{ static final int i = 3; // ok - compile-time constant } } |
To access a member of the outer class, you may use this to access it. For example:
class OuterClass { int count = 0; class InnerClass { int count = 10000; public void display() { System.out.println("Outer: " + OuterClass.this.count); System.out.println("Inner: " + count); } } } |
To access the nonstatic member class, you may need to have an instance of the outer class.
You can gain access to an inner class by using the syntax:
To access nonstatic inner class
Outer.Inner i = new Outer().new Inner(); or Outer.Inner i = outClassInstance.new Inner(); |
It doesn't matter how deeply an inner class may be nested. It can transparently access all of the members of all the classes it is nested within.
class A { class B { class C {} } } to access: A a = new A(); A.B b = a.new B(); A.B.C c = b.new C(); |
A local inner class is a class in a block or a method. For example
class A { void method() { class B {}//local inner class } if (sthTrue){ class C {}//local inner class } class D {}//nonstatic class ... } |
classes B and C are local inner classes. See more examples below:
public class Outer { public void amethod() { class Demo {} ... } } |
public class Outer { public void amethod(boolean b) { if (b) { class Demo {} ... } } } |
class Outer { int i = 100; static void classMethod() { final int l = 200; class LocalInStaticContext{ int k = i; // compile-time error, i is non-static. int m = l; // ok, l is constant. } } void foo() { class Local { // a local class int j = i; //ok. } } } |
Anonymous class is a class without name. In the example,
jeditorpane.addKeyListener(new KeyAdapter () { //anonymous class public void keyPressed(KeyEvent e) { } }); |
the above code can be rewritten (expanded) to:
class xxx extends KeyAdapter {//xxx means anonymous public void keyPressed(KeyEvent e) { } } jeditorpane.addKeyListener(new xxx() ); |
In the example,
printButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { } }); |
the above code can be rewritten (expanded) to
class xxx implements ActionListener { xxx means anonymous public void actionPerformed(ActionEvent ae) { } } printButton.addActionListener(new xxx()); |
By using anonymous classes in your code, your code will be concise and easy to read. See more examples below:
public class Outer { public Shape amethod(boolean b) { ... return new Shape{ .... }; //here semicolon is required } } |
public class Outer { public void amethod(new ActionListener() { ... }}); } |
public class Outer { public InterfaceName amethod() { return new InterfaceName() { private int one = 1; public int value() { return one; } }; } } |
public class Outer { public BaseClassName amethod() { return new BaseClassName(int x) { private int one = 1; public int value() { return super.value()* one; } }; } } |
public class Outer { public BaseClassName amethod(final String str) {//must be final to be accessed by anonymous class. return new BaseClassName() { private String s = str;//perform initialization at the point of definition of fields public String getString() { return s; } }; } } |
public class Outer { public BaseClassName amethod(final String str, final float price) { return new BaseClassName() { private int cost; { cost = Math.round(price); if (cost > 100) //dosomething } private String s = str; public String getString() { return s; } }; } } |
A file can only contain one outer public class, but can contain multiple non-public classes. Note that this will produce separate .class output files for each class declaration in a source file.
Compiler generates class file for each class declaration. For plain inner classes, the generated class file has the following format:
outerClassName$innerClassName.class |
For anonymous inner class, compiler generates class file with the following format.
outerClassName$n.class |
The n listed above indicates the counting of the anonymous inner classes. If you have 5 anonymous inner classes inside an class, you will have 5 classes with n from 1 to 5.
Java interface is a skeleton which specifies the protocol that a class must provide if the class implements that interface.
All methods are abstract and implicitly public and all variables are constants by default in an interface.
Interface declaration has the following syntax:
[public] interface interfaceIdentifier { [public final] variable declaration with initialization [public abstract] method signature } |
Or
[public] interface extends AnotherInterface { .... } |
The definition for an interface has the following rules:
An interface can extend an interface. For example:
interface Sub extends Super { String getServer(); } |
interface A {} interface B extends A{} //Note: interface extends interface, not implements interface C extends B{} |
Every interface is public by default. Every variable in an interface is public and final by default. Every method in an interface is a public and abstract by default.
public interface Server { public final String name = "RMI server"; public void connect(); public String getServerName(); ... } |
The above code is equivalent to.
public interface Server { String name = "RMI server"; void connect(); String getServerName(); ... } |
If a class implements an interface, that class must provide implementation of the methods in that interface. Otherwise, the class must be declared abstract. For example:
interface A { void amethod(); } class Test implements A { void anewMethod() {} void amethod() {} } |
If the class Test fails to provide implementation of the amethod(). the class Test should be declared abstract, like the code below:
interface A { void amethod(); } abstract class Test implements A {//note: amethod in A is not implemented in Test void anewMethod() {} } |
When an interface extends an interface, the sub interface will inherit functionality of the super interface. See an example below:
interface A { String s = "test A"; String getName(); } interface B extends A{ String str = "test B"; String getAnotherName(); } class Test implements B { public String getName() { return s; } public String getAnotherName() { return str; } public static void main(String[] args) { System.out.println(new Test().getName()); System.out.println(new Test().getAnotherName()); } } |
The above code prints: "test A" and "test B". If the class Test doesn't define getName() method in the interface A, the code won't compile.
Import statements must come after any package statements and before any class declaration. Import statements cannot come within classes, after classes are declared or anywhere else.
The import statement allows you to use a class directly instead of fully qualifying it with the full package name. For example, if you want to use a button in your class some where, you may code:
java.awt.Button submit = new java.awt.Button("Submit"); |
If you use import statement, you don't need to use the fully qualified name. You can write your code neatly like:
import java.awt.Button; ... Button submit = new Button("Submit"); ... |
Note that using many import statements do not result in a performance overhead or a change in the size of the .class output file. When your program is executed, the system will look for the class used in your program. If the class is not defined in your program, the system will look for import statement to see if the class is available for loading, if not, an error will be raised.
Method declarations describe code that may be invoked by method invocation expressions. The method declaration has the following formula:
[access modifiers] returnType methodName([parameter-list]) [throws exceptionList] { //local variables //inner classes } |
The signature of a method consists of the name of the method and the number and types of formal parameters to the method.
If a method has a return type, the keyword return will be used to return a value. If no return type, the keyword void will be used. return can be used for no return method. For example:
public void calculate() {return; } //return nothing public static void main(String[] args) {} //no return double add(double a, double b) {//return a double value return a + b; } |
A class may not declare two methods with the same signature, or a compile-time error occurs.
class Point { int x, y; abstract void move(int dx, int dy); void move(int dx, int dy) { x += dx; y += dy; } } //compile-time error |
A method can throw an exception. A throws clause is used to declare any checked exceptions that can result from the execution of a method or constructor.
void method() throws IOException {} |
Method names may be overloaded. For details, see objective 6.
A special method main serves as a start point for a program. It has the following signature.
public static void main(String[] args) {} or static public void main(String[] args) {} |
The order for the public and static modifiers doesn't matter. It is conventional to use public instead of other modifier like private or protected. The modifier static is a must. The return type is void which is a must too. The formal parameter is a array of String. Alternation of the main method signature will result in failure of launching the program.
Not one of the following is a legal main method which serves as a program start entry. They will be treated as general methods in a program and will not raise compile time error.
public class Test { public void main(String[] args) {} public static void main(String args) {} public int main(String[] args, int i) {...} public static void main(char[] args) {} public String[] main(String args, int index) {...} } |
A method with a modifier has a different functionality in a program. You can declare a method as a:
public static void method() {} static String getName(){} |
Note that an attempt to reference the current object using the keyword this or the keyword super in the body of a class method results in a compile-time error.
A static method cannot be an abstract. The following code will generate a compile-time error.
public abstract static void amethod(){}//compile-time error. |
class Test { int i; Test() { super(); } Test(int i) { this(i); } public void method() {} String getName() {} //etc. } |
A compile-time error occurs if
An abstract class can override an abstract method by providing another abstract method declaration.
An instance method that is not abstract can be overridden by an abstract method.
A private method and all methods declared in a final class are implicitly final.
A compile-time error occurs if
class A { final void method() {} } class B extends A { void method(){}//error, you cannot override a final method. } |
class A { public native void method();//implemented by platform-dependent native code. } |
class A { synchronized void method(){} } |
For details, see objective 7.
class A { public strictfp void method(){} } |
There are seven kinds of variables:
For example:
class Point { static int numPoints; // numPoints is a class variable int x, y; // x and y are instance variables int[] w = new int[10]; // w[0] is an array component int setX(int x) { // x is a method parameter int oldx = this.x; // oldx is a local variable this.x = x; return oldx; } } |
A variable or expression whose type is an interface type can reference any object whose class implements that interface.
Instance variable is called non-static variable. Any member variable declared without static modifier is an instance variable. An instance variable is associated with an instance of an object. Initialization for instance variable is not required except for final variables. When an instance variable is declared, it takes its default value. The following are all instance variables.
class Test { String SSN; double salary; char sex; int empID; .... } |
A variable declared inside a class curly braces and outside the method and has no static keyword is called instance variable.
An instance variable belongs to the instance of an object, not class itself.
Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
class Hello { String say ="Hello";//say is an instance variable. ... } |
A class variable is a static variable. Any member variable with no static modifier is called class variable. A class variable is associated with class itself. It is shared by all instance of an object. Initialization for class variables are not required, they take their default values. Because class variables are shared by instances of an object, they should be initialized in the code process before being shared. The following are all class variables:
class Test { static int companyID; static double raiseRate; static char[] levels; .... } |
A variable declared inside a class curly braces and outside the method and has a static keyword is called static variable or static field.
A static variable belongs to the class, not the instance of an object. It is shared by the instances of an object.
class Hello { static String say ="Hello";//say is a class variable. ... } |
A variable declared inside a method is called an automatic variable or a method variable.
An automatic variable is a local variable, declared in a method. When the method returns, all automatic variables will be out of scope. All local variables are required to be initialized before being used.
class Test { void amethod() { int i = 0; int j = 5; .... } } |
The following code will generate a compiler error.
class Hello { public static void main(String[] args) { String name; //need to be initialized System.out.println("Hello " + name);//compile time error } } |
public static void main(String[] args) { String say = "Hello";//say is a local variable. ... } |
An automatic variable shadows a class level variable.
class Test { String say = "Hello"; void amethod() { String say = "World"; System.out.println(say); //prints World, not Hello } ... } |
An automatic variable must be initialized before being used.
void amethod() { String say; System.out.println(say); //compile time error, say is not initialized. } |
Since the variable say is not initialized, the compiler will generate an error.
You cannot use any modifiers for automatic variables except final.
void amethod() { public String say ="wrong";//no access modifier in a local variable. System.out.println(say); } |
The compiler will generate an error for the above code.
Constructor parameters are used to initialize objects. In the example
Constructor Parameters
class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } } |
the object Point takes two parameters x and y. When an object is created, it takes x and y values. For example:
class Test { public static void main(String[] args) { Point p1 = new Point(5,5); Point p2 = new Point(10,10); } } |
The test class has two objects of Point. The objects p1 and p2 have their own values.
Method parameters are local to the method like constructor parameters.
class Test { int x, y; Test(int x, int y) { this.x = x; this.y = y; } void method(int x, int y) { int a = x; int b = y; System.out.println("x = "+ a + " y = " + b); } public static void main(String[] args) { Test t = new Test(5,6); t.method(50,60); } } >java Test x = 50 y = 60 |
The above example shows that method parameters are local to the method.
Array components may be primitive values or object references. For specific information, please see related topics.
Exception handler parameters happen only in catch block. The catch block only takes one parameter, which is used to catch exception handling information when the exception occurs.
try { ... catch(Exception e) {} |
You are not allowed to customize the catch block to let it have more than one parameter. You are allowed to create your own exception by extending Exception class and catch your own exception when it occurs.
class LeakException extends Exception { LeakException(String explanation) { super(explanation); } } try { ... catch(LeakException e) {} |
The signature of the main:
public static void main(String[] args) {} |
Note that the main() method works as a start entry for a program. It takes a string array as a parameter.
Java can accept any number of arguments from the command line. You can use command-line arguments to interact with your program with one invocation.
You can pass messages to your program when you run your program on the command line:
>java MyProgram one two three |
The argument String[] args in main() method will take one, two and three as its first three elements. Java array index starts with zero not 1. For example:
class Test { public static void main(String[] args) { if (args.length > 0) System.out.println(args[0]); } } |
When you run it in the following way:
>java Test one two three one |
Note that "one" will be printed on the screen, not the class name "Test" or "java". Thus the values for the string array would be:
args[0] == "one"; args[1] == "two"; args[2] == "three"; |
If you run the test in the following way:
>java Test 1.1 1.1 |
The 1.1 value is a string type, not a double type. If you want to change it into a double, use wrapper class Double.parseDouble().
double d = Double.parseDouble(args[0]); |
If you want to get primitive types from argument list, use methods in wrapper classes like Double.parseDouble(args[x]), Integer.parseInt(args[x]), etc.
You may use the following code to know how many arguments passed to the program.
public static void main(String[] args) { int howmanyArgs = args.length; ... } |
Note, the size for an array is field length, not length() which returns the size of a string.
It is possible to have an ArrayIndexOutOfBoundsException thrown in the main. See the following code:
class Test { public static void main(String[] args) { System.out.println(args[2]); } } >java Test one two |
The above code causes an ArrayIndexOutOfBoundsException because args[2], the third argument doesn't exist.
Recap: any value passed through command line to the program is a String type and the first argument index is zero not one; The first argument is not the class name or program name.
There are 12 modifiers listed below.
public native void amethod() throws SomeException; |
package is a keyword in Java. It is used to organize class files and establish a library.
When you create your own classes, you can place them in packages, so that you can import classes from your package into new program to avoid rewriting code.
The general syntax for package declaration is:
package packName.packName2.packNamen; |
The dot notation indicates a package hierarchy which can be mapped to the subdirectory of your file system.
The order for the package statement in a source file is required. The package statement must be put before the import statement or class name like the following:
package packName.packName2.packNamen; import java.xxx ; class XXX |
The following code will generate an error.
import java.io.*; package mypack.cal;//wrong place class Test{} |
Note that if you do not place a package statement in a source file, it will be considered to have a default package which corresponds to the current directory.
To create a package, you need to place package statement in your file. When you compile the file, the generated class file will be placed in the package. When you want to use the class file, just import it into your program. For example:
package org.javacamp.scjp.test; class SalaryCalculator {} >javac -d SalaryCalculator.java |
SalaryCalculator class will be put into the org\javacamp\scjp\test\ subdirectory when you compile the code with the -d switch. Note that if the subdirectories don't exist, Java compiler will create these subdirectories for you automatically.
When you want to use such class, you can import it into your program easily by using import statement like the following code. You don't need to rewrite or copy SalaryCalculator code to your file.
import org.javacamp.scjp.test.SalaryCalculator; class EmployeePayRoll { SalaryCalculator cal = new SalaryCalculator(); ... } |
Creating packages encourages developers to reuse code, reduce debug and development time.
The visibility modifiers are a key part of the encapsulation mechanism for Java. Encapsulation allows separation of the interface from the implementation of methods.The benefit of this is that the details of the code inside a class can be changed without it affecting other objects that use it. This is a key concept of the Object Oriented paradigm (had to use that word somewhere eventually).
Encapsulation generally takes form of methods to retrieve and update the values of private class variables. These methods are known as an accessor(getters) and mutator(setters) methods.
Class & Static: Using static modifier to describe a feature like a method, a variable or a nested class is called class or static feature. A class or a static feature means such feature is shared by all the instances of the class, and belongs to the class itself. A class feature can be accessed without creating an instance of the class.
Instance & nonstatic: Not using static modifier to describe a feature like a method or a variable is called instance feature. An instance feature belongs to an instance of a class or an object, not the class itself.
Local & Automatic variable: A variable which is declared within a method and can not be accessed from the outside of the method. Local variable must be initialized before being used. A parameter list of a method can only be seen and accessed inside the method.
Nested & Inner: A feature or a code sits inside the body of another or "outer" feature. like nested class or inner class. Nested feature or inner feature exists inside another feature in that it can see the private feature.
Scope & Visibility: Something features can be seen or can be accessible from
The following form will give you range info about 8 primitive data types. For specific information about each type, please click links.
Type |
Contains |
Default |
Size |
Range |
true or false | false | 1 bit | NA | |
Unicode character unsigned |
\u0000 | 16 bits or 2 bytes |
0 to 216-1 or \u0000 to \uFFFF |
|
Signed integer | 0 | 8 bit or 1 byte |
-27 to 27-1 or -128 to 127 |
|
Signed integer | 0 | 16 bit or 2 bytes |
-215 to 215-1 or -32768 to 32767 |
|
Signed integer | 0 | 32 bit or 4 bytes |
-231 to 231-1 or -2147483648 to 2147483647 |
|
Signed integer | 0 | 64 bit or 8 bytes |
-263 to 263-1 or -9223372036854775808 to 9223372036854775807 |
|
IEEE 754 floating point single-precision |
0.0f | 32 bit or 4 bytes |
±1.4E-45 to ±3.4028235E+38 |
|
IEEE 754 floating point double-precision |
0.0 | 64 bit or 8 bytes |
±439E-324 to ±1.7976931348623157E+308 |
The 8 primitive data types(a boolean type, a character type, four integer types, and two floating types) can be visualized in the following image.
Type |
Literal |
Two values: true or false. boolean b = true; or boolean b = false; |
|
Unicode character unsigned Default value: \u0000 char ch = 'A'; char[] chs = {'A', 'B', 'C'}; |
|
Signed integer byte b = 127; byte bb = -12; |
|
Signed integer short s = 12; short ss = -5; |
|
Signed integer int i = 5555; int ii = -1234; |
|
Signed integer long k = 15L; long j = -23l; |
|
IEEE 754 floating point single-precision float f = 0.0f; float f2 = 12.5F; |
|
IEEE 754 floating point double-precision double d = 3.4D; double d2 = 53.0d; double d3 = 1.2e+10; double d4 = 1.2e-10; |
The String type is a class, not a primitive type. String literals contain a string of letters including escape sequences enclosing in a double quote.
Several strings can be concatenated with a plus sign.
You can use new to declare a string or use an assignment to declare and initialize it at the same time.
If a string contains another string, it should use escape sequence.
public class Test { public static void main(String[] args) { String s = "This is a test"; String s1 = "\nThis is the second line"; String s2 = "\nPrint double quotes \" \" out"); String s3 = new String("\nThis is the last line"); System.out.println(s+s1+s2+s3); } } Print the following on the screen: This is a test This is the second line Print double quotes " " out This is the last line |
If the first element in the System.out.println() is a string, the following data type will be treated as a string. See the following:
int i = 5; int j = 10; double d = 10.5; System.out.println(i + j + d); //print: 25.5 System.out.println("Data: " + i + j + d); //print: Data: 51010.5 |
The boolean type has two possible values, representing two states: on or off, yes or no, true or false. Java reserves the words true and false to represent these two boolean values.
To declare a boolean variable:
public class Test { boolean b; public static void main(String[] args) { System.out.println(new Test().b); // prints false // System.out.println(b); //You can't reach b, which is not static variable. } } |
The char type represents Unicode characters. Its size is 16 bits long.
To declare a char variable, simple place it between single quotes(apostrophes):
You can use escape sequence to represent character literal.
'\uxxxx is Unicode escape sequence, where xxxx is for hexadecimal digits
'\xxx' is Latin-1 character, where xxx is an octal(base 8) number between 000 and 377.
Nonprinting ASCII character:
'\t' -- horizontal tab
'\b' -- backspace
'\n' -- newline
'\f' -- form feed
'\r' -- carriage return
public class Test { public static void main(String[] args) { char c = 'A'; char tab = '\t'; char nul = ' '; char aleph = '\u05D0'; char backslash = '\\'; char singleQuote ='\''; char doubleQuote = '\"'; System.out.println(c); //... } } |
You can't do these:
char nul = ''; //wrong char singleQuote = '''; //wrong char doubleQuote = '"'; //wrong char backslash = '\'; //wrong |
byte, short, int, long are called integer types. These four types differ only in the number of bits.
Literals for each type: byte, short and int are almost the same.
public class Test { public static void main(String[] args) { byte b = 127; // Min:-128 Max: 127 int i1 = 28; int i2 = 0x1c; //hexadecimal 28 int i3 = 034; // octal 28 int i4 = 0xCAFEBABE; //magic number used to identify Java class files long l1 = 12345L; //a long value long l2 = 12345l; //a long value long l3 = 0xffL; //a long value System.out.println(l3); } } |
You can't do these:
byte b = 128; //out of range, too large short s = -32770; //out of range, too small int i = 0xCAFEBABEFF; //too large if byte b1 = 127, b2 = 2; byte sum = b1 + b2; //not allowed, but System.out.println(b1+b2); //OK, because "+" in the .println() will //promote byte or short to int automatically. |
float and double data types represent real numbers. The float has at least 6 significant decimal digits and a double has at least 15 significant digits. The literals use a string of digits.
public class Test { public static void main(String[] args) { float f = 6.02e23f; //represents 6.02 x 1023 double d = 1e-6; // represents 1 x 10-6 double d2 = 123.4; //no problem to compile. //no exception thrown even if illegal operations double inf = 1/0; //infinity double neginf = -1/0; // -infinity double negzero = -1/inf; // negative zero double NaN = 0/0; //NaN--not a number } } |
To check whether a float or double value is NaN, you must use the Float.isNaN() and Double.isNaN() methods.
Wrapper classes are classes related primitives. Each primitive type has a corresponding wrapper class.
boolean -- Boolean char -- Character* byte -- Byte short -- Short int -- Integer* long -- Long float -- Float double -- Double |
Field, method, member class, member interface, and constructor declarations may include the access modifiers public, protected, or private.
A. Super B. sub C. Switch D. do E. for |
Answer: D, E. All Java keywords are lower-case. Java is a case sensitive language.
A. implement B. extends C. sizeof D. length E. default |
Answer: B,E.
A. friendly B. protected C. Class D. interface E. privated |
Answer: B,D.
1) float f = 10f; 2) float f = 10.1; 3) float f = 10.1f; 4) byte b = 10b; 5) short myshort = 99S; 6) String name = 'Excellent tutorial Mr Green'; 7) char c = 17c; 8) int z = 015; 9) boolean b = -1; 10) boolean b2 = false; 11) int i = 019; 12) char c = 99; 13) double d = 15L; 14) long l = 15d; 15) short s = 12c; |
Answer: 1), 3),8),10),12),13). Note that 019 is not octal number, because octal number doesn't have 9.