Basic Java program
//Choose a meaningful Classname. Save as "Classname.java"
public class Classname {
public static void main(String[] args) {
// Your programming statements here!
}
}
Arrays
• <elementType>[] <arrayName>;
•int [] a;
• <elementType> <arrayName>[];
• int a [];
• <arrayName>=new <elementType>[arraySize];
• a=new int[10];
• <elementType>[] <arrayName>=new <elementType>[arraySize];
• int [] a=new int[10];
• int [] a={1,2,3,4};
• char language[]={‘j’ , ’a’ , ’v’ , ’a’};
• <arrayName>.length gives the number of elements in the array.
• Arrays are passed to functions by reference, or as a pointer to the original. This means
anything you do to the Array inside the function affects the original.
10.
Multi dimensional arrays
•int twoDArray[][] = new int[3][];
• twoDArray[0] = new int[2];
• twoDArray[1] = new int[3];
• twoDArray[2] = new int[4];
11.
final key word
•You can declare a class, a variable or a method to be final.
• A final class cannot be sub-classed (or extended).
• A final variable cannot be re-assigned a new value.
• A final variable of primitive type is a constant, whose value cannot be changed.
• A final variable of a reference type (e.g., an instance of a class or an array) cannot be re-
assigned a new value (reference). That is, you can modify the content of the instance, but
cannot re-assign the variable to another instance.
• An instance blank final variables must be initialized in all the constructors of a class.
• Static final variable must be initialized in static block of the class.
• Final methods cannot be overridden but they can be overloaded.
• Abstract classes and interfaces cannot be marked as final.
12.
final and blankfinal
A final variable that is not initialized at the time of declaration is known as blank
final variable. It has to be initialized in all constructors.
A static final variable that is not initialized at the time of declaration is known as
static blank final variable. It can be initialized only in static block.
If you declare any formal parameter as final, you cannot change the value of it.
13.
final classes
final classBaseClass{}
// Error - The type DerivedClass cannot subclass the final class
BaseClass
public class DerivedClass extends BaseClass{
}
GC Phases
• MarkPhase
• Marks the live objects in the heap. Typically most of the GC time is spent
here.
• Sweep Phase
• Performs the actual garbage removal.
• Compaction Phase
• Compacts the heap to provide larger contiguous storage areas.
17.
GC Overview
• GCmanages the java Heap (default 512 MB)
• GC only executes
• When objects cannot be allocated with in the heap.
• Requested via System.gc() call.
• All other threads are stopped before GC runs.
18.
static variable
• Itis a variable which belongs to the class and not to object(instance)
• Static variables are initialized only once , at the start of the execution .
These variables will be initialized first, before the initialization of any
instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and
doesn’t need any object
• Syntax : <class-name>.<variable-name>
19.
static method
• Itis a method which belongs to the class and not to the object(instance)
• A static method can access only static data. It can not access non-static
data (instance variables)
• A static method can call only other static methods and can not call a
non-static method from it.
• A static method can be accessed directly by the class name and doesn’t
need any object
• Syntax : <class-name>.<method-name>
• A static method cannot refer to “this” or “super” keywords in anyway
20.
static block
• Thestatic block, is a block of statement inside a Java class that will be
executed when the class is loaded into memory by Class Loader of
Java Virtual Machine.
class Test{
static {
//Code goes here
}
}
21.
Class Loader
• EveryJVM has a built-in class loader (of type java.lang.ClassLoader) that is
responsible for loading classes into the memory of a Java program. Whenever a class
is referenced in the program, the class loader searches the classpath for the class
file, loads the bytecode into memory, and instantiates a java.lang.Class object to
maintain the loaded class.
• The class loader loads a class only once, so there is only one java.lang.Class object
for each class that used in the program. This Class object stores the static variables
and methods.
• During the class loading, the class loader also allocates the static variables, and
invokes the explicit initializers and static initializers (in the order of appearance).
22.
Instantiation Process
The sequenceof events when a new object is instantiated via the new operator
(known as the instantiation process) is as follows:
• JVM allocates memory for the instance in the help.
• JVM initializes the instance variables to their assigned values or default values.
• JVM invokes the constructor.
• The first statement of the constructor is always a call to its immediate
superclass' constructor. JVM invokes the selected superclass' constructor.
• JVM executes the instance initializers in the order of appearance.
• JVM executes the body of the constructor.
• The new operator returns a reference to the new object.
Constructor
A constructor isdifferent from an ordinary method in the following aspects:
• The name of the constructor method is the same as the class name, and by class
name convention, begins with an uppercase.
• Constructor has no return type (or implicitly returns void). Hence, no return statement
is allowed inside the constructor's body.
• Constructor can only be invoked via the "new" operator. It can only be used once to
initialize the instance constructed.
• You cannot call the constructor afterwards.
• Constructors are not inherited (to be explained later).
• A constructor with no parameter is called the default constructor, which initializes the
member variables to their default value.
25.
Method overloading
• Methodoverloading means that the same method name can have
different implementations (versions). However, the different
implementations must be distinguishable by their argument list
(either the number of arguments, or the type of arguments, or their
order).
26.
toString()
• Every classshould have a public method called toString() that returns a string description
of the object.
• You can invoke the toString() method explicitly by calling an InstanceName.toString() or
implicitly via println() or String concatenation operator '+'.
• Running println(anInstance) with an object argument invokes the toString() method of that
instance implicitly.
27.
Copy by valueand Copy by reference
• Java stores each primitive type in a fixed amount of memory and Java directly manipulates the values for primitives.
• However, objects and arrays do not have a standard size, and they can become quite large. Therefore, Java
manipulates these types by reference.
• Although the reference types do not have a standard size, the references to reference types do have a standard size.
• Reference types differ from primitives in the way values are copied and compared.
• When you work with a primitive data type, such as an integer, you are working directly with values and no Java object is
involved. So the statement x = y actually copies the value of y into x.
• When you work with reference types (objects), the variable does not contain the object. The variable is a reference to
that object in memory.
• So the statement x = y does not copy the object, but only copies the reference. There is still only one object, but it now
has two references.
28.
OOP
• In OOP,we often organize classes in hierarchy to avoid duplication and
reduce redundancy. The classes in the lower hierarchy inherit all the
variables (static attributes) and methods (dynamic behaviors) from
the higher hierarchies. A class in the lower hierarchy is called a
subclass (or derived, child, extended class). A class in the upper
hierarchy is called a superclass (or base, parent class). By pulling out
all the common variables and methods into the superclasses, and
leave the specialized variables and methods in the subclasses,
redundancy can be greatly reduced or eliminated as these common
variables and methods do not need to be repeated in all the
subclasses.
instanceof
• Java providesa binary operator called instanceof which returns true if
an object is an instance of a particular class. The syntax is as follows:
anObject instanceof aClass
• An instance of subclass is also an instance of its superclass.
31.
Method overriding
Asubclass instance can be assigned (substituted) to a superclass' reference.
Once substituted, we can invoke methods defined in the superclass; we cannot
invoke methods defined in the subclass.
However, if the subclass overrides inherited methods from the superclass, the
subclass (overridden) versions will be invoked.
The "@Override" is known as annotation (introduced in JDK 1.5), which asks
compiler to check whether there is such a method in the superclass to be
overridden. This helps greatly if you misspell the name of the method to be
overridden. For example, suppose that you wish to override method toString() in
a subclass. If @Override is not used and toString() is misspelled as TOString(), it
will be treated as a new method in the subclass, instead of overriding the
superclass. If @Override is used, the compiler will signal an error.
@Override annotation is optional, but certainly nice to have.
Annotations are not programming constructs. They have no effect on the
program output. It is only used by the compiler, discarded after compilation, and
not used by the runtime.
32.
super
• Recall thatinside a class definition, you can use the keyword this to refer to this instance. Similarly,
the keyword super refers to the superclass, which could be the immediate parent or its ancestor.
• The keyword super allows the subclass to access superclass' methods and variables within the
subclass' definition. For example, super() and super(argumentList) can be used invoke the
superclass’ constructor. If the subclass overrides a method inherited from its superclass, says
getArea(), you can use super.getArea() to invoke the superclass' version within the subclass
definition. Similarly, if your subclass hides one of the superclass' variable, you can use
super.variableName to refer to the hidden variable within the subclass definition.
• In the body of a constructor, you can use super(args) to invoke a constructor of its immediate
superclass. Note that super(args), if it is used, must be the first statement in the subclass'
constructor. If it is not used in the constructor, Java compiler automatically insert a super()
statement to invoke the no-arg constructor of its immediate superclass. This follows the fact that
the parent must be born before the child can be born. You need to properly construct the
superclasses before you can construct the subclass.
• If the immediate superclass does not have the default constructor (it defines some constructors but
does not define a no-arg constructor), you will get a compilation error in doing a super() call.
33.
Object class
• TheObject class, defined in the java.lang package, defines and implements behavior
common to all classes—including the ones that you write. In the Java platform,
many classes derive directly from Object, other classes derive from some of those
classes, and so on, forming a hierarchy of classes. These common behaviors enable
the implementation of features such as multi-threading and garbage collectors.
34.
Methods of Objectclass
Modifier and Type Method and Description
protected Object clone() Creates and returns a copy of this object.
boolean equals(Object obj) Indicates whether some other object is "equal to" this one.
protected void
finalize() Called by the garbage collector on an object when garbage collection determines that there
are no more references to the object.
Class<?> getClass() Returns the runtime class of this Object.
int hashCode() Returns a hash code value for the object.
void notify() Wakes up a single thread that is waiting on this object's monitor.
void notifyAll() Wakes up all threads that are waiting on this object's monitor.
String toString() Returns a string representation of the object.
void wait() Causes the current thread to wait until another thread invokes the notify() method or the
notifyAll() method for this object.
void wait(long timeout) Causes the current thread to wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void
wait(long timeout, int nanos) Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object, or some other thread interrupts the current
thread, or a certain amount of real time has elapsed.
35.
finalize()
• finalize() iscalled before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e.
releasing any system resources held, closing connection if open etc.
• Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it
will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its
finalize() method gets called.
• Similarly even after finalize gets called its not guaranteed it will be immediately collected.
• Because of above reason it make no sense to use finalize method for releasing critical resources or perform any time critical
activity inside finalize
• finalize method is called by garbage collection thread before collecting object and it is not intended to be called like normal
method.
• There is one way you can guarantee running of finalize method by calling System.runFinalization() and
Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object which are eligible
for garbage collection and whose finalize has not yet called.
• Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I doubt if you
find any trace of it.
36.
finalize()
• One ofthe most important point of finalize method is that its not
automatically chained like constructors. If you are overriding finalize
method then its your responsibility to call finalize() method of super-
class, if you forgot to call then finalize of super class will never be
called.
• Best way to call super class finalize method is to call them in finally
block as shown in below example. this will guarantee that finalize of
parent class will be called in all condition except when JVM exits
37.
Method and variablehiding
• A subclass inherits all the member variables and methods from its
superclasses (the immediate parent and all its ancestors). It can use
the inherited methods and variables as they are. It may also override
an inherited method by providing its own version, or hide an inherited
variable by defining a variable of the same name.
38.
Upcasting
• Substituting asubclass instance for its superclass is called "upcasting".
This is because, in a UML class diagram, subclass is often drawn below
its superclass. Upcasting is always safe because a subclass instance
possesses all the properties of its superclass and can do whatever its
superclass can do. The compiler checks for valid upcasting and issues
error "incompatible types" otherwise.
Circle c1 = new Cylinder(); // Compiler checks to ensure that R-value is a subclass of L-value.
Circle c2 = new String(); // Compilation error: incompatible types
39.
Downcasting
• Substituting asubclass instance for its superclass is called "upcasting". You can revert
a substituted instance back to a subclass reference. This is called "downcasting".
• Downcasting requires explicit type casting operator in the form of prefix operator
(new-type). Downcasting is not always safe, and throws a runtime
ClassCastException if the instance to be downcasted does not belong to the correct
subclass. A subclass object can be substituted for its superclass, but the reverse is
not true. Compiler may not be able to detect error in explicit cast, which will be
detected only at runtime.
Circle c1 = new Cylinder(5.0); // upcast is safe
Cylinder aCylinder = (Cylinder) c1; // downcast needs the casting operator
Circle c1 = new Circle(5); Point p1 = new Point(); c1 = p1; // compilation error: incompatible types (Point is not a
subclass of Circle) c1 = (Circle)p1; // runtime error: java.lang.ClassCastException: Point cannot be casted to Circle
abstract method andabstract class
An abstract method is a method with only signature (i.e.,
the method name, the list of arguments and the return type)
without implementation (i.e., the method’s body). You use
the keyword abstract to declare an abstract method.
An abstract method cannot be declared final, as final method
cannot be overridden. An abstract method, on the other
hand, must be overridden in a descendent before it can be
used.
An abstract method cannot be private (which generates a
compilation error). This is because private method are not
visible to the subclass and thus cannot be overridden.
A class containing one or more abstract methods is called an abstract class. An abstract
class must be declared with a class-modifier abstract.
42.
Why interfaces?
• Aninterface is a contract (or a protocol, or a common understanding) of what the classes can do. When a class
implements a certain interface, it promises to provide implementation to all the abstract methods declared in the
interface. Interface defines a set of common behaviors. The classes implement the interface agree to these
behaviors and provide their own implementation to the behaviors. This allows you to program at the interface,
instead of the actual implementation. One of the main usage of interface is provide a communication contract
between two objects. If you know a class implements an interface, then you know that class contains concrete
implementations of the methods declared in that interface, and you are guaranteed to be able to invoke these
methods safely. In other words, two objects can communicate based on the contract defined in the interface,
instead of their specific implementation.
• Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance permits you to
derive a subclass from more than one direct superclass. This poses a problem if two direct superclasses have
conflicting implementations. (Which one to follow in the subclass?). However, multiple inheritance does have its
place. Java does this by permitting you to "implements" more than one interfaces (but you can only "extends"
from a single superclass). Since interfaces contain only abstract methods without actual implementation, no
conflict can arise among the multiple interfaces. (Interface can hold constants but is not recommended. If a
subclass implements two interfaces with conflicting constants, the compiler will flag out a compilation error.)
43.
interface
• A Javainterface is a 100% abstract superclass which define a set of methods its subclasses
must support. An interface contains only public abstract methods (methods with signature
and no implementation) and possibly constants (public static final variables). You have to
use the keyword "interface" to define an interface (instead of keyword "class" for normal
classes). The keyword public and abstract are not needed for its abstract methods as they
are mandatory.
• An interface is a contract for what the classes can do. It, however, does not specify how the
classes should do it.
• An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
44.
interface
An interface issimilar to a class in the following ways:
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the name of the interface matching the name of the
file.
• The bytecode of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches
the package name.
45.
interface
However, an interfaceis different from a class in several ways, including:
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear in an interface must be declared
both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
46.
interface
When overriding methodsdefined in interfaces there are several rules to be followed:
• Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
• The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
• An implementation class itself can be abstract and if so interface methods need not be
implemented.
47.
interface
To implement interfacesthere are several rules:
• A class can implement more than one interface at a time.
• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, similarly to the way that a class can
extend another class.
• The javacompiler adds public and abstract keywords before the
interface method and public, static and final keywords before data
members
• .
50.
A file ofJava source code has the extension .java. It consists of an optional package statement followed by
any number of import statements followed by one or more class or interface definitions. (The package
and import statements will be introduced shortly.) If more than one class or interface is defined in a Java
source file, only one of them may be declared public (i.e., made available outside of the package), and
the source file must have the same name as that public class or interface, plus the .java extension.
Each class or interface definition in a .java file is compiled into a separate file. These files of compiled Java
byte-codes are known as "class files," and must have the same name as the class or interface they define,
with the extension .class appended. For example, the class SoundEffects would be stored in the file
SoundEffects.class.
Class files are stored in a directory that has the same components as the package name. If the fully
qualified name of a class is david.games.tetris.SoundEffects, for example, the full path of the class file
must be david/games/tetris/SoundEffects.class. This filename is interpreted relative to the Java "class
path," described below
52.
Package
A package isa collection of related Java entities (such as classes, interfaces, exceptions, errors and enums).
Packages are used for:
• Resolving naming conflict of classes by prefixing the class name with a package name.
• For example, com.zzz.Circle and com.yyy.Circle are two distinct classes. Although they share the same class name Circle,
but they belong to two different packages: com.zzz and com.yyy. These two classes can be used in the same program and
distinguished using the fully-qualified class name - package name plus class name. This mechanism is called Namespace
Management.
• Access Control: Besides public and private, Java has two access control modifiers – protected and default –
that are related to package. A protected entity is accessible by classes in the same package and its subclasses.
An entity without access control modifier (i.e., default) is accessible by classes in the same package only.
• For distributing a collection of reusable classes, usually in a format known as Java Archive (JAR) file.
53.
Package Naming Convention
•A package name is made up of the reverse of the Internet Domain
Name (to ensure uniqueness) plus your own organization's internal
project name, separated by dots '.'. Package names are in lowercase.
• For example, suppose that your Internet Domain Name is "zzz.com", you can
name your package as "com.zzz.project1.subproject2".
• The prefix "java" and "javax" are reserved for core Java packages and
Java extensions, respectively.
54.
Package Name &the Directory Structure
• The package name is closely associated with the directory structure used to store the classes.
The classes (and other entities) belonging to a specific package are stored together in the
same directory. Furthermore, they are stored in a sub-directory structure specified by its
package name.
• For example, the class Circle of package com.zzz.project1.subproject2 is stored as "$BASE_DIRcomzzz
project1subproject2Circle.class", where $BASE_DIR denotes the base directory of the package. Clearly,
the "dot" in the package name corresponds to a sub-directory of the file system.
• The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java
compiler and runtime must be informed about the location of the $BASE_DIR so as to locate
the classes. This is accomplished by an environment variable called CLASSPATH. CLASSPATH is
similar to another environment variable PATH, which is used by the command shell to search
for the executable programs.
55.
• There isno such concept of sub-package in Java (i.e., java.awt.event is
not a sub-package of java.awt). Two distinct packages may share
common prefix and directory structure.
• For example java.awt and java.awt.event. They are two distinct packages
sharing some common directory structures and prefix. The classes belonging
to the package java.awt are stored in directory "$BASE_DIRjavaawt" while
the classes of package java.awt.event are stored in directory "$BASE_DIR
javaawtevent".
56.
Creating Packages
• Tomake a class as part of a package, you have to include the package
statement as the first statement in the source file.
• It is a good practice to store the source codes and the classes in
separate directories, to facilitate the distribution of classes without
the source codes.
57.
Package
// d:myJavaProjectsrccomyyyCircle.java
package com.yyy;// Package statement should be the first executable statement
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
To compile the source using JDK, we need to use the -d option to specify the
package base directory of the compiled class d:myJavaProjectclasses as follows
(-d defaulted to the current directory):
> javac -d d:myJavaProjectclasses d:myJavaProjectsrccomyyyCircle.java
The compiled class will be kept in d:myJavaProjectclassescomyyyCircle.class.
Directory "com.yyy" will be created automatically.
Instead of absolute path, we could also use relative path.
58.
Package
// d:myOtherProjectTestCircle.java
import com.yyy.Circle;
publicclass TestCircle {
public static void main(String[] args) {
Circle c = new Circle(1.23);
System.out.println(c.getRadius());
}
}
d:myOtherProject> javac TestCircle.java
TestCircle.java:1: package com.yyy does not exist
import com.yyy.Circle;
^
We need to use the -cp (or -classpath) option to specify the base
directory of the package com.yyy, in order to locate com.yyy.Circle.
d:myOtherProject> javac -cp d:myJavaProjectclasses TestCircle.java
d:myOtherProject> java -cp d:myJavaProjectclasses TestCircle
Exception in thread "main" java.lang.NoClassDefFoundError: TestCircle
But now, the JRE can't even find the TestCircle class, which is located in
the current directory. This is because if CLASSPATH is not explicitly set, it
defaulted to the current directory. However, if CLASSPATH is explicitly
set, it does not include the current directory unless the current
directory is included. Hence, we need to include current directory
(denoted as '.') in the CLASSPATH, together with the base directory of
package com.yyy, separated by ';', as follows:
d:myOtherProject> java -cp .;d:myJavaProjectclasses TestCircle
59.
Suppose that theTestCircle class is in a package com.abc, and save as d:myOtherProjectsrccom
abcTestCircle.java.
// d:myOtherProjectsrccom.abcTestCircle.java
package com.abc;
import com.yyy.Circle;
public class TestCircle {
......
}
d:myOtherProject> javac -d classes -cp d:myJavaProjectclasses srccomabc
TestCircle.java
-- To run TestCircle, need to include the base directory of TestCircle and Circle in
classpath.
-- Also need to use the fully-qualified name (package name plus class name) for
TestCircle
d:myOtherProject> java -cp classes;d:myJavaProjectclasses com.abc.TestCircle
60.
package com.zzz.project1.subproject2;
public classMyClass3 {
private MyClass4 myClass4;
public MyClass3 () { // constructor
System.out.println("MyClass3 constructed");
myClass4 = new MyClass4(); // use MyClass4 in
the same package
}
// main() included here for testing
public static void main(String[] args) {
new MyClass3();
}
}
62.
Inner Class
• Innerclasses are class within Class. Inner class instance has special
relationship with Outer class. This special relationship gives inner class
access to member of outer class as if they are the part of outer class.
Inner class instance has access to all member of the outer
class(Public, Private & Protected).
• Types of Inner Classes
• Static
• Method Local
• Anonymous
• Member class
63.
Normal Inner Class
//outerclass
class OuterClass {
//inner class
class InnerClass {
}
}
When we compile the above code, we get two class files. We can’t directly execute
the inner class’s .class file with java command.
OuterClass.class
InnerClass$OuterClass.class
64.
Access normal InnerClass
• From with in outer class, Outer class can create instance of the inner class in the
same way as you create a class instance.
• InnerClass i1 = new InnerClass();
• From Outside Outer Class, Create outer class instance and then inner class instance.
• // Creating outer class instance
• OuterClass outerclass = new OuterClass();
• // Creating inner class instance
• OuterClass.InnerClass innerclass = outerclass.new InnerClass();
OR
• OuterClass.InnerClass innerClass = new OuterClass.new InnerClass();
• In case of Inner class “this” keyword will refer the currently executing inner class
Object. But to get this for outer class use “OuterClass.this”.
65.
Modifiers applied
• Normalinner class will be treated like member of the outer class so it
can have several Modifiers as opposed to Class.
• final
• abstract
• public
• private
• protected
• strictfp
66.
Method Local InnerClass
• When an inner class is defined inside the method of Outer Class it becomes
Method local inner class.
• Method local inner class can be instantiated within the method where it is
defined and no where else.
• Because objects (and their methods) created from this class may persist after
the method returns, a local inner class may not refer to parameters or non-
final local variables of the method. But it can use the instance variable.
• If method local variable is “Final”, method local inner class can use it.(* Now
variable is Final).
• Method local inner classes are eligible for modifiers like local variable so an
method local inner class can have final or abstract.
67.
Static member class
•An inner class qualified with static keyword.
• Despite its position inside another class, a static member class is
actually an "outer" class--it has no special access to names in its
containing class.
• To refer to the static inner class from a class outside the containing
class, use the syntax OuterClassName.InnerClassName.
• A static member class may contain static fields and methods.
68.
• An anonymousinner class is one that is declared and used to create one
object (typically as a parameter to a method), all within a single statement.
• An anonymous inner class may extend a class:
• new SuperClass(parameters){ class body }
• Here, SuperClass is not the name of the class being defined, but rather the
name of the class being extended. The parameters are the parameters to the
constructor for that superclass.
• An anonymous inner class may implement an interface:
• new Interface(){ class body }
• Anonymous inner classes are almost always used as event listeners
69.
enum
• Enums aretype-safe!
• Enums provide their namespace.
• Whenever an enum is defined, a class that extends java.lang.Enum is created. Hence, enum cannot extend
another class or enum. The compiler also create an instance of the class for each constants defined inside the
enum. The java.lang.Enum has these methods:
public final String name();
// Returns the name of this enum constant, exactly as declared in its enum
declaration.
// You could also override the toString() to provide a more user-friendly description.
public String toString(); // Returns the name of this enum constant, as contained in the declaration.
// This method may be overridden.
public final int ordinal(); // Returns the ordinal of this enumeration constant.
• All constants defined in an enum are public static final. Since they are static, they can be accessed via
EnumName.instanceName.
• You do not instantiate an enum, but rely the constants defined.
• Enums can be used in a switch-case statement, just like an int.
70.
Wrapper classes
The designersof Java language retain the primitive types in an object-
oriented language, instead of making everything object, so as to improve the
runtime performance.
However, in some situations, an object is required instead of a primitive
value.
The data structures in the Collection framework, such as the "dynamic
array" ArrayList and Vector, stores only objects (reference types) and not
primitive types.
Object is needed to support synchronization in multithreading.
Objects are needed, if you wish to modify the arguments passed into a
method (because primitive types are passed by value).
JDK provides the so-called wrapper classes that wrap primitive values into
objects, for each primitive type as shown in the class diagram. Each of the
wrapper classes contains a private member variable that holds the primitive
value it wraps. The wrapped value cannot be changed.
72.
Wrap via constructors
•Wrap an int primitive value into an Integer object
• Integer aIntObj = new Integer(5566);
• Wrap a double primitive value into a Double object
• Double aDoubleObj = new Double(55.66);
• Wrap a char primitive value into a Character object
• Character aCharObj = new Character('z');
• Wrap a boolean primitive value into a Boolean object
• Boolean aBooleanObj = new Boolean(true);
• All wrapper classes, except Character, also have a constructor that takes
a String, and parse the String into the primitive value to be wrapped.
73.
Number class
The followingmethods are declared in Number class, which are
implemented in concrete subclasses Byte, Short, Integer, Long, Float,
Double.
• public byte byteValue()
• public short shortValue()
• public abstract int intValue()
• public abstract long longValue()
• public abstract float floatValue()
• public abstract double doubleValue()
• public char charValue()
• public boolean booleanValue()
74.
Exception Handling
• Olderprogramming languages such as C have some drawbacks in exception handing.
For example, suppose the programmer wishes to open a file for processing:
• The programmers are not made to be aware of the exceptional conditions. For example,
the file to be opened may not necessarily exist. The programmer therefore did not
write codes to test whether the file exists before opening the file.
• Suppose the programmer is aware of the exceptional conditions, he/she might decide
to finish the main logic first, and write the exception handling codes later – this "later",
unfortunately, usually never happens. In other words, you are not force to write the
exception handling codes together with the main logic.
• Suppose the programmer decided to write the exception handling codes, the exception
handling codes intertwine with the main logic in many if-else statements. This makes
main logic hard to follow and the entire program hard to read. For example,
75.
Exception Handling
• Javaovercomes these drawbacks by building the exception handling
into the language rather than leaving it to the discretion of the
programmers:
• You will be informed of the exceptional conditions that may arise in
calling a method - Exceptions are declared in the method's signature.
• You are forced to handle exceptions while writing the main logic and
cannot leave them as an afterthought - Your program cannot
compiled without the exception handling codes.
• Exception handling codes are separated from the main logic - Via the
try-catch-finally construct.
76.
Exceptions must beDeclared
• As an example, suppose that you want to use a java.util.Scanner to
perform formatted input from a disk file. The signature of the
Scanner's constructor with a File argument is given as follows:
• public Scanner(File source) throws FileNotFoundException;
• The method's signature informs the programmers that an exceptional
condition "file not found" may arise. By declaring the exceptions in
the method's signature, programmers are made to aware of the
exceptional conditions in using the method.
77.
Exceptions must beHandled
• If a method declares an exception in its signature, you cannot use this
method without handling the exception - you can't compile the
program.
• To use a method that declares an exception in its signature, you MUST
either:
• provide exception handling codes in a "try-catch" or "try-catch-finally"
construct, or
• not handling the exception in the current method, but declare the exception
to be thrown up the call stack for the next higher-level method to handle.
78.
Main logic isseparated from the exception
handling codes
79.
Main logic isseparated from the exception
handling codes
80.
Exception propagation
• Whenan exception occurs inside a Java method, the
method creates an Exception object and passes the
Exception object to the JVM (in Java term, the method
"throw" an Exception).
• The Exception object contains the type of the exception, and
the state of the program when the exception occurs.
• The JVM is responsible for finding an exception handler to
process the Exception object.
• It searches backward through the call stack until it finds a
matching exception handler for that particular class of
Exception object (in Java term, it is called "catch" the
Exception).
• If the JVM cannot find a matching exception handler in all
the methods in the call stack, it terminates the program.
Error vs Exceptionclass
• The Error class describes internal system errors (e.g.,
VirtualMachineError, LinkageError) that rarely occur. If such an error
occurs, there is little that you can do and the program will be
terminated by the Java runtime.
• The Exception class describes the error caused by your program (e.g.
FileNotFoundException, IOException). These errors could be caught
and handled by your program (e.g., perform an alternate action or do
a graceful exit by closing all the files, network and database
connections).
83.
Exception handling mechanism
try{
// main logic, uses methods that may throw Exceptions
......
} catch (Exception1 ex) {
// error handler for Exception1
......
} catch (Exception2 ex) {
// error handler for Exception1
......
} finally { // finally is optional
// clean up codes, always executed regardless of exceptions
......
}
84.
assert
• Assertion enablesyou to test your assumptions about your program logic
(such as pre-conditions, post-conditions, and invariants).
• The assert statement has two forms:
• assert booleanExpr;
• assert booleanExpr : errorMessageExpr;
• When the runtime execute the assertion, it first evaluates the booleanExpr.
If the value is true, nothing happens. If it is false, the runtime throws an
AssertionError, using the no-argument constructor (in the first form) or
errorMessageExpr as the argument to the constructor (in the second form).
• If an object is passed as the errorMessageExpr, the object's toString() will
be called to obtain the message string.
85.
Uses of assertstatement
Assertion can be used for verifying:
• Internal Invariants: Assert that a value is within a certain constraint, e.g., assert x > 0.
• Class Invariants: Assert that an object's state is within a constraint. What must be true
about each instance of a class before or after the execution of a method? Class
invariants are typically verified via private boolean method, e.g., an isValid() method to
check if a Circle object has a positive radius.
• Control-Flow Invariants: Assert that a certain location will not be reached. For example,
the default clause of a switch-case statement.
• Pre-conditions of methods: What must be true when a method is invoked? Typically
expressed in terms of the method's arguments or the states of its objects.
• Post-conditions of methods: What must be true after a method completes successfully?
86.
Java Strings arefull-fledged objects, but they have some
properties in common with primitive types. They can
have literal values and they can be used in assignment
statements. + Operator is overloaded internally in Java
language for String.
87.
Overriding and OverloadingMethods
• An overriding method must have the same argument list and return-type (or subclass of its
original from JDK 1.5). An overloading method must have different argument list, but it can have
any return-type.
• An overriding method cannot have more restricted access. For example, a method with protected
access may be overridden to have protected or public access but not private or default access.
This is because an overridden method is considered to be a replacement of its original, hence, it
cannot be more restrictive.
• An overriding method cannot declare exception types that were not declared in its original.
However, it may declare exception types are the same as, or subclass of its original. It needs not
declare all the exceptions as its original. It can throw fewer exceptions than the original, but not
more.
• An overloading method must be differentiated by its argument list. It cannot be differentiated by
the return-type, the exceptions, and the modifier, which is illegal. It can have any return-type,
access modifier, and exceptions, as long as it can be differentiated by the argument list.
The StringBuffer class
providesseveral methods
that are useful for string
processing. The constructor
method,StringBuffer(String)
, makes it easy to convert
a String into a
StringBuffer. Similarly,
once you are done
processing the buffer, the
toString() method makes it
easy to convert a
StringBuffer back into a
String.
99.
GUI Components cannotbe added directly to a JFrame. They must be added to
its content pane. For a content pane, the default layout manager is a BorderLayout.
Java's Container class has several add() methods
that can be used to insert components
into the container:
add(Component comp) // add comp to end of container
add(Component comp, int index) // add comp at index
add(String region, Component comp) // add comp at region
103.
State Description
Ready Thethread is ready to run and waiting for the CPU.
Running The thread is executing on the CPU.
Waiting The thread is waiting for some event to happen.
Sleeping The thread has been told to sleep for a time.
Blocked The thread is waiting for I/O to finish.
Dead The thread is terminated.
106.
Type Description DefaultSize(bits) Min/Max
boolean true/false false 1 Not applicable
char Unicode character u0000 16 u0000
uFFFF
byte Signed integer 0 8 -128
127
short Signed integer 0 16 -32768
32767
int Signed integer 0 32 -2147483648
2147483647
long Signed integer 0 64 -9223372036854775808
9223372036854775807
float
IEEE 754 Floating
point 0.0 32 +/- 1.40239846E-45
+/- 3.40282347E+38
double
IEEE 754 floating
point 0.0 64 +/- 4.94065645841246544E-324
+/- 1.79769313486231570E-308
107.
Precedence Java OperatorOperands Assoc. Description
1 ++
--
+ -
~
!
(type)
Arithmetic
Arithmetic
Arithmetic
Integral
Boolean
Any
Right
Right
Right
Right
Right
Right
Unary pre/post decrement
Unary pre/post decrement
Unary plus and minus
Unary bitwise complement
Unary logical complement
cast
2 * / % Arithmetic Left Multiplication, division and remainder
3 + -
+
Arithmetic
String
Left
Left
Addition and subtraction
String concatenation
4 <<
>>
>>>
Integral
Integral
Integral
Left
Left
Left
Left shift
Right shift with sign extension
Right shift with zero extension
5 < <=
> >=
instanceof
Arithmetic
Arithmetic
Object, type
Left
Left
Left
Less than, less than or equal
Greater than, greater than or equal
Type comparison
108.
Precedence Java OperatorOperands Assoc. Description
6 ==
!=
==
!=
Primitive
Primitive
Object
Object
Left
Left
Left
Left
Equality test (value)
Inequality test (value)
Equality (refer to the same
object)
Inequality (refer to different
objects)
7 &
&
Integral
Boolean
Left
Left
Bitwise AND
Boolean AND
8 ^
^
Integral
Boolean
Left
Left
Bitwise XOR
Boolean XOR
9 |
|
Integral
Boolean
Left
Left
Bitwise OR
Boolean OR
10 && Boolean Left Conditional AND
11 | | Boolean Left Conditional OR
12 ? : Boolean, any, any Right Conditional ternary
13 =
*= /= %/ += -= <<= >>= >>>= &= ^=
|=
Variable, any
Variable, any
Right
Right
Assignment
Assignment with operation
109.
Inner Classes
This featureslets you define a class as part of another class, just as fields and methods are
defined within classes. Java defines four types of inner classes.
A nested top-level class or interface is a static member of an enclosing top-level class or
interface.
A member class is a nonstatic inner class. As a full-fledged member of its containing class, a
member class can refer to the fields and methods of the containing class, even the private fields
and methods. Just as you would expect for the other instance fields and methods of a class, all
instances of a member class are associated with an instance of the enclosing class.
A local class is an inner class defined within a block of Java code, such as within a method or
within the body of a loop. Local classes have local scope they can only be used within the block
in which they are defined. Local classes can refer to the methods and variables of their enclosing
classes. They are used mostly to implement adapters, which are used to handle events.
An anonymous class is a local class whose definition and use are combined into a single
expression. Rather than defining the class in one statement and using it in another, both
operations are combined into a single expression. Anonymous classes are intended for one-time
use. Therefore, they do not contain constructors
110.
When Java compilesa file containing a named inner class, it creates separate class files for them
with names that include the nesting class as a qualifier. For example, if you define an inner class
named Metric inside a top-level class named Converter, the compiler will create a class file
named Converter$Metric.class for the inner class. If you wanted to access the inner class from
some other class (besides Converter), you would use a qualified name: Converter.Metric.
An anonymous class bytecode files are given names like ConverterFrame$1.class.
Eg1: Inner Classes Example Program
Eg2: Local Class
Eg3: Anonymous Class
111.
Dynamic Polymorphism
• Ifa base class reference is used to call a method, the method to be
invoked is decided by the JVM, depending on the object the reference
is pointing to.
• The keyword super can be used to access any data member or
methods of the super class in the sub class.