Java Important Points Textbook: Notebook: First Notebook Created: 6/9/2018 1:48 PM Updated: 6/12/2018 4:49 PM Author
Java Important Points Textbook: Notebook: First Notebook Created: 6/9/2018 1:48 PM Updated: 6/12/2018 4:49 PM Author
Byconvention, the name of that class should match the name of the file that holds the program. You should also make
sure that the capitalization of the filename matches the class name.
When Java source code is compiled, each individual class is put into its own output file named after the class and using
the .class extension. This is why it is a good idea to give your Java source files the same name as the class they
contain—the name of the source file will match the name of the .class file.When you execute java as just shown, you
are actually specifying the name of the class that you want to execute. It will automatically search for a file by that
name that has the .class extension. If it finds the file, it will execute the code contained in the specified class.
3 types of comments 1)single line 2)multiline 3)documentation comment
documentation comment begin with /** and ends with */
In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program
is started.
The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is
necessary since main( ) is called by the Java Virtual Machine before any objects are made.
args receives any command-line arguments present when the program is executed.
System.out.print() doesnot put newline character at the end after printing but System.out,println() put newline at the
end after printing.
Control statements
if statement
condition statement;
if( )
for loop
initialization; condition; iteration statement
for( ) ;
Identifiers
They must not begin with a number, lest they be confused with a numeric literal.
-,+,* etc cannot be used
Primitive datatypes
• Integers This group includes byte(1byte), short(2 byte), int(4 byte), and long(8 bytes), which are for whole-
valued
signed numbers.
• Floating-point numbers This group includes float(4 bytes) and double(8 bytes), which represent
numbers with fractional precision
• Characters This group includes char, which represents symbols in a character set,
like letters and numbers.
• Boolean This group includes boolean, which is a special type for representing
true/false values
System.out.println("10 > 9 is " + (10 > 9));//output 10 > 9 is true
0x7ffffffffffffffL or 9223372036854775807L is the largest long.// integer literal
6.022E23, 314159E–05, and 2e+100.//floating point literal D or d is attached for double and f or F attached at end for
float
For octal notation, use the backslash followed by the three-digit number. For example, ‘\141’ ‘a’.
is the letter
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, ‘\u0061’ is the ISO-
Latin-1‘a’ ‘\ua432’
because the top byte is zero. is a Japanese Katakana character.
Examples of string literals
“Hello World”
“two\nlines”
“\”This is in quotes\”“
When one type of data is assigned to another type of variable, an automatic type conversion will take place if the
following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type. so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type
conversion(sometimes called a narrowing conversion,) . It has this general form:
(target type value
- )
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
normal right shift >> preserves the sign bit but >>> add 0 at the msb after shift
For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be
sure that a division operation will be valid before evaluating it:
Highest
() [] .(dot)
++ – – ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest
Control statements
Selection
control statements can be put into the following categories: selection, iteration, and jump. statements allow your
program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration
statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump
statements allow your program to execute in a nonlinear fashion.
In switch case if there is no break then all the conditions after the statement that has no break is evaluated and
executed
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
This program generates the following output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
for each version of for loop
// The for-each loop is essentially read-only.
class NoChange {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
The first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect
on the underlying array nums, as the second for loop illustrates. The output, shown here, proves this point:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
In 2d array
for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
Jump Statements
They are break,continue,return
java supports goto by using labelled break
The general form of the labeled break statement is shown here:
break label;
A label is any valid Java identifier followed by a colon.
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Running this program generates the following output:
Before the break.
This is after second block.
Labelled continue is also supported
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
The continue statement in this example terminates the loop counting j and continues with the next iteration of the
loop counting i. Here is the output of this program:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
Diff betw argument and parameter
parameter is the variable that recieves the value passed to a method and the value passed when method is invoked is
called argument.
Instance variable hiding(same name for local variable and instance variable): solution use this keyword
Finalization: means use of finalize() function to perform some action before destroying the objects(before garbage
collection)
syntax:
protected void finalize( )
{
// finalization code here
}
static keyword
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described in the
next chapter.)
First static instance variables created then static block is executed;
As you can see, the size of each array is displayed. Keep in mind that the value of length has nothing to do with the
number of elements that are actually in use. It only reflects the number of elements that the array is designed to hold.
Nested class
A nested class has access to the members, including private members, of the class in which it is nested.
There are two types of nested classes: static and non-static . A static nested class is one that has the static modifier
applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer
to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all
of the variables and methods of its outer class and may refer to them directly in the same way that other non-static
members of the outer class do.
You can, however, create an instance of Inner class outside of Outer class by qualifying its name with Outer, as in
Outer.Inner
anonymous inner classes , which are inner classes that don’t have a name.
Strings
String are immutable;
definition of string functions
boolean equals(String object )
int length( )
char charAt(int index )
Variable length arguments
method that takes a variable number of arguments is called a variable-arity method , or simply avarargs method . This
feature is called varags
Avariable-length argument is specified by three periods (...). For example, here is how vaTest( ) is written using a
vararg:
static void vaTest(int ... v) {
inside vaTest( ), v is accessed using the normal array syntax. Here is the preceding program rewritten using a vararg
// Demonstrate variable-length arguments.
class VarArgs {
// vaTest() now uses a vararg.
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Notice how vaTest() can be called with a
// variable number of arguments.
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}
conditions of varags
int doIt(int a, int b, double c, int ... vals) { //correct
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!
ambiguity is problem in varags when two overloaded varags are defined and a zero argument function of the same
name is called.
Inheritance
That is, when a reference to a subclass object is assigned to a superclass reference variable, you will have access only
to those parts of the object defined by the superclass
for method overriding subclass and super class must have the function with same name and type signature ,if type
signature is different then method overloading take place
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than
compile time.Dynamic method dispatch is important because this is how Java implements run-time polymorphism.
In other words, it is the type of the object being referred to (not the type of the reference variable) that determines
which version of an overridden method will be executed
Advantage of method overriding
code reuse
run time polymorphism
robustness
uses of final
1)declare constants
2)prevent overriding
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.
3)prevent inheritance;class is declared final
Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of
any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array.
Packages
Packages are containers for classes that are used to keep the class name space compartmentalized.
Private No Modifier Protected Public
Same class Yes Yes Yes Yes
Same
package
subclass
Same
package
non-subclass
Different
package
subclass
No No Yes Yes
Different
package
non-subclass
No No No Yes
Interfaces
When you implement an interface method, it must be declared as public.
If a class includes an interface but does not fully implement the methods defined by that interface, then that class must
be declared as abstract.
An interface can be declared a member of a class or another interface. Such an interface is called amember interface or
anested interface
A nested interface can be declared as public, private, or protected. This differs from a top-level interface, which
must either be declared as public or use the default access level
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes.
When a class implements an interface that inherits another interface, it must provide implementations for all methods
defined within the interface inheritance chain. Following is an example:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Exception handling
An exception is an abnormal condition that arises in a code sequence at run time.
All exception types are subclasses of the built-in class Throwable
Athrows clause lists the types of exceptions that a method might throw
Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the
program does not specify a throws clause to declare this fact, the program will not compile.
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
To make this example compile, you need to make two changes. First, you need to declare that throwOne( ) throws
IllegalAccessException. Second, main( ) must define a try/catch statement that catches this exception. The
corrected example is shown here:
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Chained Exception
The chained exception feature allows you to associate another exception with an exception.
To allow chained exceptions, two constructors and two methods were added to Throwable. The constructors are
shown here:
Throwable(Throwable causeExc )
Throwable(String msg causeExc
, Throwable )
The getCause( ) method returns the exception that underlies the current exception. If there is no underlying
exception, null is returned. The initCause( ) method associates causeExc with the invoking exception and returns a
reference to the exception. Thus, you can associate a cause with an exception after the exception has been created.
// Demonstrate exception chaining.
class ChainExcDemo {
static void demoproc() {
// create an exception
NullPointerException e =
new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}
The output from the program is shown here:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
MultiThreading
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.
there are two distinct types of multitasking: processbased and thread-based.
In processbased multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
In athread-based multitasking environment, the thread is the smallest unit of dispatchable code.
Advantages of multithread over multi process
Processes are heavyweight tasks that require their own separate address spaces. Interprocess communication is
expensive and limited. Context switching from one process to another is also costly. Threads, on the other hand, are
lightweight. They share the same address space and cooperatively share the same heavyweight process.Interthread
communication is inexpensive, and context switching from one thread to the next is low cost. While Java programs
make use of processbased multitasking environments, process-based multitasking is not under the control of Java.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can
be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates,
because idle time is common. For example, the transmission rate of data over a network is much slower than the rate at
which the computer can process it. Even local file system resources are read and written at a much slower pace than
they can be processed by the CPU. And, of course, user input is much slower than the computer.
Monitor is used for thread synchronization
// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
output
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
//currentThread return reference to currently executing thread. here 5 is the priority which is default for main and main
is the group to which the thread belongs.
A thread group is a data structure that controls the state of a collection of threads as a whole.
definition of fns
static void sleep(longmilliseconds ) throws InterruptedException
static void sleep(longmilliseconds, nanoseconds
int ) throws InterruptedException
final void setName(String threadName )
final String getName( )
using runnable
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
output
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
main thread must be the last thread to finish running.
using extend
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
definitions of fns
final boolean isAlive( )
final void join( ) throws InterruptedException
level
final void setPriority(int )
final int getPriority( )
// Demonstrate thread priorities.
class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
output
Low-priority thread: 4408112
High-priority thread: 589626904
synchronization
synchronized( object ){
// statements to be synchronized
}
eg:
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods.
• wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.
definitions
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
other definitions
final void suspend( )
final void resume( )
final void stop( )
The following program demonstrates these methods:
// Using suspend() and resume().
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
output
New thread: Thread[One,5,main]
One: 15
New thread: Thread[Two,5,main]
Two: 15
One: 14
Two: 14
One: 13
Two: 13
One: 12
Two: 12
One: 11
Two: 11
Suspending thread One
Two: 10
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One
Suspending thread Two
One: 10
One: 9
One: 8
One: 7
One: 6
Resuming thread Two
Waiting for threads to finish.
Two: 5
One: 5
Two: 4
One: 4
Two: 3
One: 3
Two: 2
One: 2
Two: 1
One: 1
Two exiting.
One exiting.
Main thread exiting.
//another
void focusGained(FocusEvent ) fe
void focusLost(FocusEvent )fe
The ComponentListener Interface
This interface defines four methods that are invoked when a component is resized, moved, shown, or hidden. Their general forms
are shown here:
void componentResized(ComponentEvent ) ce
void componentMoved(ComponentEvent ) ce
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The ContainerListener Interface
This interface contains two methods. When a component is added to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( ) is invoked. Their general forms are shown here:
void componentAdded(ContainerEvent ) ce
void componentRemoved(ContainerEvent ) ce
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form is
shown here:
}}
//short circuiting effect no error at output
float array should be initialized using 'f' ie
float f5[]={1.0f,2.0f,3.0f}; otherwise compile time error since it will be treated as double