You are on page 1of 164

Introduction to java

Introduction to java

Java was conceived by James gosling, Patrick naughten, Chris warth, FD Frank, and
Mike Sheridan at Sun Microsystem, Inc. in 1991. This language was initially called ‘Oak’ but
renamed “java” in 1995.

Java Version

Version Year import New Features

1.0 1996 --------------------

1.1 1997 Inner classes

1.2 1998 Swings, Collection

1.3 2000 Performance enhancements

1.4 2002 XML, Assertions

Generic Classes, Meta data, enhance for loop, Auto


1.5 2004
boxing, Static import, var args and Enumeration.

The Three Object Oriented Concepts

1. Encapsulation

2. Inheritance

3. Polymorphism

1. Encapsulation

The wrapping up data and methods into a single unit is known as encapsulation.
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both
safe form outside interference and misuse.

Advantages

1. Security

2. Easy to enhance

3. Maintainability

1
4. Modularity

2. Inheritance

Inheritance is the process by which one object acquired with the properties of another
object. The advantages of inheritance are reusability of code and accessibility of variables and
methods of the superclass by subclass.

3. Polymorphism

Polymorphism means the ability to take more than form, for example, an operation may
exhibit different behavior in different instances.

Java allows an object of a superclass refer to an object of any subclass. This is possible
because all objects of a base class are also objects of its superclass.

Abstraction: It refers to the act of representing essential features without including background
details or an explanation (i.e.) hiding the internal implementation is called the Abstraction.

Advantages:

1. Security

2. Enhancement easy

3. Internal implantation without effect outside

Class – A class defines the structure and behavior that will be shared by a set of objects. Classes
can inherit variables and methods from other classes

Class method – A method defined in a class, which operates on the class itself and can be called
via the class or any of its instances.

Class variable – A variable that is owned by the class and all its instances as a whole and is
stored in the class.

Instance method – A method defined in a class, which operates on an instance of that class.

Instance variable – A variable that is owned by an individual instance and whole value is stored
in the instance.

Interface – A Collection of abstract behavior specification that individual classes can then
implement.

2
Without main without static block

package something;

public class Withoutmain {

static int i=m1();

public static int m1()

System.out.println("hi I can print");

return 10;

output:

hi I can print

Exception in thread 'main' java.lang.NoSuchMethodError:main

3
DATA TYPES AND TYPE CONVERSION

Variable Identifiers

Variable names must be legal Java identifiers:

1. Keywords and reserved words may not be used.

2. It must start with a letter, dollar sign ($), or underscore (_).

3. Subsequent characters may be letters, dollar signs, underscores, or digits.

4. It is case sensitive. For example, mymodel and MyModel are different identifiers.

5. There is no length limit for java identifier, but SUN highly recommended up to 15
characters. Examples:

Total (√) total123 (√) 123total (×) total$ (√) _total (√)

total# (×) total_numbers (√) total-numbers (×)

Keywords for primitive data types:

byte, short , int , long, float , double , char , boolean

Keywords for flow control:

if , else , switch , case , default , for, do , while , break , continue , return

Keywords for Exception Handling:

try, catch , finally , throw , throws , assert

Keywords for modifiers:

public, private , protected , static , abstract , strictfp

final, transient , native , volitle , synchronised

Class related key words:

class, interface , package, extends , implements , import

Object related key words:

new, instanceOf , super , this

4
Other:

void

Unused keywords:

const , goto

Reserved literals:

true , flase , null

New key words in j2SE 1.5:

enum

All the key words contains only lower case alphabate symbols

Primitive data types

Size(in
Data Type value-range
bits)

Boolean
boolean 1 true or false
Datatype

Signed Numeric byte 8 -27 to (27-1) or -128 to +127


Datatype
short 16 -215 to (215-1) or –32768 to 32767

int 32 -231 to (231-1) or –2147483648 to 2147483647

-263 to (263-1) or –9223372036854775808 to


long 64
9223372036854775807

float 32 Float.MIN_VALUE to Float.MAX_VALUE

double 64 Double.MIN_VALUE to Double.MAX_VALUE

Unsigned
Numeric char 16 0 to (216-1) or \u0000 to \uFFFF
Datatype

5
• Primitive data type boolean can take boolean literals, true or false, as values.

• Primitive data types can also be classified as signed integrals and unsigned integrals.

byte, short, int, long are signed integrals.

• char represents unsigned integrals.

• Signed integrals represent signed numbers (positive as well as negative). They are
represented in 2's complement form.

• Default Values: Each primitive data type has a default value specified. Variable of
primitive data type may be initialized. Only class member variables are automatically
initialized. Method variables need explicit initialization.

• generic formula for calculating a range of a signed datatype with n bits to represent as:

–2(n-1) to 2(n-1) –1

Coding Standards

Java coding standards:

Sun recommended the following for the naming conventions.

1. In case of classes:

The first letter should be capitalized and if the several words are linked together to form the
name, the first letter of the inner words should be upper case.

For the classes the names should be nouns .

Ex:Student,Customer ,Employee etc.

2. In case of Interfaces:

For the interfaces the names should be adjective and follows camel case.

Ex: Runnable .Serializable,cloneable,Comparable,Movable etc

3. In case of Methods:

The first letter should be lower case and then normal camel case rules should be used.

The names should be verb –noun pairs

Ex: getBalance(); doCalculation(0;

6
setCustomerName();

4. In case of variables:

Like methods the camel case format should be used stating with a lower case letter.

Ex: buttonwidth; accountBalance mystring

5. Constants:

java constants are created by marking variables as and final.

They should be named using upper case letter with unscore (_) is the saperator.

Ex: MIN_HIGHT, MAX_HIGHT

Java Beans Naming Conventions:

• Java Beans are java classes that have properties.For every property there should be getter
and setter methods.

• All the properties must be declared as the private (to get security)

• For every non – Boolean property will we should have public getXXX() method.

• i.e the getter method is no argument method only.

• For the Boolean properties we can have setter method public setXXX()

Literals

1. Boolean Literals

There are 2 boolean literals true and false. Please note that they are case sensitive.

boolean b = true; // valid

boolean b = True; // invalid

2. Character Literals

Character literals are defined as a character in single quotes.

char ch = 'w';

Character literals can also be represented using hexadecimal values.

char ch = '\u4468'; where 4468 is hexadecimal value for some character.

7
Character literals can also be some special characters

char ch = '\r';

Other special characters are '\n' '\\'.

3. Integral Literals

By default, integral literals are of data type int.

int a = 5; // valid.

Integral literals normally represent a decimal value.

int aNumber = 28;

Integral literals can also be representing an octal value.

int aNumber = 034;

Please note that an octal literal is identified when there is 0 (zero) at the start of the
literal. Octal numbers are represented with 0 to 7 digits similar to decimal system,
which uses 0-9 digits to represent numbers. Therefore, there is no single digit above 7
in octal system.

int aNumber = 034; // valid.

int aNumber = 038; // invalid.

Integral literals can also represent the hexadecimal value.

int aNumber = 0x1a;

Please note that hex literals are case insensitive. Therefore

int aNumber = 0x1a; // valid.

nt aNumber = 0x1A; // valid.

int aNumber = 0X1a; // valid.

int aNumber = 0X1A; // valid.

4. Floating Point Literals

8
By default, they are of type double.

double d = 12.34; //valid

float f = 12.34; //invalid

float f = 12.34f; //valid

double d1 = 1.23 E+20; //valid

5. String Literals

String literals are represented as a sequence of characters enclosed in double quotes.

String s = "SampleString"; //valid

String s = 'SampleString'; //invalid

Mutable

Changeable. All Java variables are by default mutable.

Immutable

Not changeable. You can make them immutable by using the final keyword. You can also
make them private and provide no accessors to the outside world to change them. The wrapper
classes, Byte, Character, Short, Integer, Long, Float and Double are all immutable. Strings are
immutable. StringBuffers are mutable. The only way to change the value of the number inside
the object wrapper is to create a new object and point to that instead.

Advantages of Immutablitiy

You can share immutable objects between threads without danger of changes confusing the
other thread. You don’t need any locking. Two threads can both work on an immutable object at
the same time without any possibility of conflict.

• Once you check the value, you know it has to stay safe. No one can pass you a value,
then behind your back swap it to an unsafe one using a background thread. This is
particularly important in high security situations where allowing an invalid value to sneak
in could compromise system integrity, e.g. a filename. This is probably the main reason
that Strings are immutable.

• You can share duplicates by pointing them to a single instance. You need only one copy,
e.g. String interning. This saves RAM. With mutable StringBuilders that were
temporarily identical, you could not throw one away, and replace it with a reference to
the other, since at any moment their values could diverge again.
9
• You can create substrings without copying. You just create a pointer into an existing base
String guaranteed never to change. Immutability is the secret behind Java’s very fast
substring implementation.

• Immutable objects are much better suited to be Hashtable keys. If you change the value
of an object that is used as a hash table key without removing it and re-adding it you lose
the mapping.

• Since String is immutable, inside each String is a char[] exactly the correct length. Unlike
a StringBuilder there is no need for padding to allow for growth.

Returning an Immutable Result

Let us say you wanted to return some data from your method, but you did not want the user to
muck with the original. Here are six approaches to the problem:

1. Wrap the reference in an immutable wrapper class and return that.

2. Give the caller his own private copy of the data he can muck with to his heart’s content.
There is high CPU and RAM overhead in the array copying.

3. Beg or threaten the user not to modify the data in the reference you return to him.

4. Return an immutable interface to the original data. You can then change fields in the
object, but the caller cannot unless he cheats by casting. You expose only the methods
you want the user to have. Doing the same with classes is trickier since a subclass must
expose everything its superclass does.

5. You can turn a Collection into an immutable Collection with methods like

 Collections.unmodifiableCollection,

 Collections.unmodifiableList,

 Collections.unmodifiableMap,

 Collections.unmodifiableSet,.

 Collections.unmodifiableSortedMap(or)Collections.unmodifiableSortedSet.

6. You can return an Iterator with a dummy remove method.

Memory Storage

10
When a program is loaded into memory, it is organized into three areas of memory,
called segments:

1. The text segment,


2. Stack segment, and
3. Heap segment.
The text segment (sometimes also called the code segment) is where the compiled code
of the program itself resides. This is the machine language representation of the program steps to
be carried out, including all functions making up the program, both user defined and system.

The remaining two areas of system memory is where storage may be allocated by the
compiler for data storage. The stack is where memory is allocated for automatic variables within
functions.

A stack is a Last In First Out (LIFO) storage device where new storage is allocated and
deallocated at only one ``end'', called the Top of the stack The heap segment provides more
stable storage of data for a program; memory allocated in the heap remains in existence for the
duration of a program. Therefore, global variables (storage class external), and static variables
are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program
start, remains zero until the program makes use of it. Thus, the heap area need not contain
garbage.

Stack Memory:

Stack Memory referred as temporary memory and created as new during each function or
procedure or program entry used for local program variables. If the program exits, memory
allocated to the local variables will be deleted. It is a temporary memory stack is variable type

Heap Memory:

Heap Memory referred as permanent memory used for persistent objects. This dynamically
allocated distinct region of memory exists until it is explicitly released by the programmer.
where all the objects, complex structures occupy, memory. it is a permanent memory heap is
reference type

Type Conversion in Java

1. Automatic Conversion (Implicit conversion)

In Java type conversions are performed automatically when the type of the expression on
the right hand side of an assignment operation can be safely promoted to the type of the variable
on the left hand side of the assignment. Thus we can safely assign:

byte -> short -> int -> long -> float -> double

11
The -> symbol used here should be interpreted as "to a". For example:

Example

// 64 bit long integer

long myLongInteger;

// 32 bit standard integer

int myInteger;

myLongInteger = myInteger;

2. Explicit Conversion (Casting)

The above will not work the other way round. For example we cannot automatically
convert a long to an int because the first requires more storage than the second and consequently
information may be lost. To force such a conversion we must carry out an explicit conversion
(assuming of course that the long integer will fit into a standard integer). This is done using a
process known as a type cast:

Converting one type of data into another must follow the rules of casting.

Example:

myInteger = (int) myLongInteger

Wrapper Classes

Every primitive type has a corresponding wrapper class. A wrapper class allows you to
be a class object that corresponds to a value of a primitive type. Wrapper classes also contain a
number of useful predefined constants and static methods.

Conversion

A specific conversion from type S to type T allows an expression of type S to be treated at


compile time as if it had type T instead. In some cases this will require a corresponding action at
run time to check the validity of the conversion or to translate the run-time value of the
expression into a form appropriate for the new type T. For example:

1. A conversion from type Object to type Thread requires a run-time check to make sure
that the run-time value is actually an instance of class Thread or one of its subclasses; if it
is not, an exception is thrown.

12
2. A conversion from type Thread to type Object requires no run-time action; Thread is a
subclass of Object, so any reference produced by an expression of type Thread is a valid
reference value of type Object.

3. A conversion from type int to type long requires run-time sign-extension of a 32-bit
integer value to the 64-bit long representation. No information is lost.

4. A conversion from type double to type long requires a nontrivial translation from a 64-bit
floating-point value to the 64-bit integer representation. Depending on the actual run-time
value, information may be lost.

In every conversion context, only certain specific conversions are permitted. The Java
programming languages are grouped into several broad categories:

1. Identity conversions

2. Widening primitive conversions

3. Narrowing primitive conversions

4. Widening reference conversions

5. Narrowing reference conversions

6. Boxing conversions

7. Unboxing conversions

8. Unchecked conversions

9. Capture conversions

10. String conversions

11. Value set conversions

The five conversion contexts are described:

1. Assignment conversion converts the type of an expression tothe type of a


specified variable. Assignment conversion may cause a OutOfMemoryError (as a
result of boxing conversion), a Exception (as a result of unboxing conversion), or
a ClassCastException (as a result of an unchecked conversion) to be thrown at run
time.

2. Method invocation conversion is applied to each argument in a method or


constructor invocation and, except in one case, performs the same conversions
that assignment conversion does. Method invocation conversion may cause a
13
OutOfMemoryError (as a result of boxing conversion), a NullPointerException
(as a result of unboxing conversion), or a ClassCastException (as a result of an
unchecked conversion) to be thrown at run time.

3. Casting conversion converts the type of an expression to a type explicitly


specified by a cast operator. It is more inclusive than assignment or method
invocation conversion, allowing any specific conversion other than a string
conversion, but certain casts to a reference type may cause an exception at run
time.

4. String conversion allows any type to be converted to type String.

5. Numeric promotion brings the operands of a numeric operator to a common type


so that an operation can be performed.

Here are some examples of the various contexts for conversion:

class Test {public static void main(String[] args) {


// Casting conversion of a float literal to type int. Without the cast operator, this would
// be a compile-time error, because this is a narrowing conversion :
int i = (int)12.5f;
// String conversion (§5.4) of i’s int value:
System.out.println("(int)12.5f==" + i);
// Assignment conversion (§5.2) of i’s value to type float. This is a widening conversion:
float f = i;
// String conversion of f's float value:
System.out.println("after float widening: " + f);
// Numeric promotion (§5.6) of i’s value to type float. This is a binary numeric promotion.
// After promotion, the operation is float, float:
System.out.print(f);
f = f , i;
// Two string conversions of i and f:
System.out.println(", " + i + "==" + f);
// Method invocation conversion of f’s value to type double, needed because the method
// Math.sin accepts only a double argument:
double d = Math.sin(f);
// Two string conversions of f and d:
System.out.println("Math.sin(" + f + ")==" + d);
}
}
Output:

(int)12.5f==12
14
after float widening: 12.0

12.0, 12==144.0

Math.sin(144.0)==-0.49102159389846934

1. Identity Conversions

A conversion from a type to that same type is permitted for any type.

This may seem trivial, but it has two practical consequences. First, it is always
permitted for an expression to have the desired type to begin with, thus allowing the
simply stated rule that every expression is subject to conversion, if only a trivial identity
conversion. Second, it implies that it is permitted for a program to include redundant cast
operators for the sake of clarity.

Example int d=10;

2. Widening primitive conversion

When you change a narrower type to a wider type, you do not lose the magnitude
of the value. Therefore, Java automatically converts the type. These type conversions are
popularly known as the widening conversions. All of the following are considered as
widening type conversions

• byte to short, int, long, float, or double

• short to int, long, float, or double

• char to int, long, float, or double

• int to long, float, or double

• long to float or double

• float to double

15
Widening primitive conversions do not lose information about the overall magnitude
of a numeric value. Indeed, conversions widening from an integral type to another
integral type do not lose any information at all; the numeric value is preserved exactly.
Conversions widening from float to double in strictfp expressions also preserve the
numeric value exactly;

Conversion of an int or a long value to float, or of a long value to double, may result
in loss of precision—that is, the result may lose some of the least significant bits of the
value. In this case, the resulting floating-point value will be a correctly rounded version
of the integer value, using IEEE 754 round-to-nearest mode

A widening conversion of a signed integer value to an integral type T simply sign-


extends the two’s-complement representation of the integer value to fill the wider format.
A widening conversion of a char to an integral type T zero-extends the representation of
the char value to fill the wider format.

Despite the fact that loss of precision may occur, widening conversions among
primitive types never result in a run-time exception. For example,

class Test { public static void main(String[] args) {


int big = 1234567890; float approx = big; System.out.println(big - (int)approx);
}}
Output:-46

Thus indicating that information was lost during the conversion from type int to type
float because values of type float are not precise to nine significant digits.

3. Narrowing Primitive Conversions


16
The narrowing conversion occurs from a type to a different type that has a smaller
size, such as from a long (64 bits) to an int (32 bits).In general, the narrowing primitive
conversion can occur in these cases:

• short to byte or char

• char to byte or short

• int to byte, short, or char

• long to byte, short, char, or int

• float to byte, short, char, int, or long

• double to byte, short, char, int, long, or float

Narrowing conversions may lose information about the overall magnitude of a


numeric value and may also lose precision. A narrowing conversion of a floating-point
number to an integral type T takes two steps: First step:

1. The floating-point number is converted either to a long, if T is long, or to


an int, if T is byte, short, char, or int, as follows:

2. If the floating-point number is NaN , the result of the first step of the
conversion is an int or long 0.

a. Otherwise, if the floating-point number is not infinity, the floating-


point value is rounded to an integer value V, rounding toward zero
using IEEE 754 round-toward-zero mode. Then there are two
cases:

i. If T is long, and this integer value can be represented as a


long, then the result of the first step is the long value V.

ii. Otherwise, if this integer value can be represented as an int,


then the

3. result of the first step is the int value V.

a. Otherwise, one of the following two cases must be true:

i. The value must be too small (a negative value of large


magnitude or negative infinity), and the result of the first
step is the smallest representable value of type int or long.

17
ii. The value must be too large (a positive value of large
magnitude or positive infinity), and the result of the first
step is the largest representable value of type int or long.

4. In the second step:

a. If T is int or long, the result of the conversion is the result of the


first step.

b. If T is byte, char, or short, the result of the conversion is the result


of a narrowing conversion to type T of the result of the first step.

A. The narrowing primitive conversion must be explicit.

B. You need to specify the target type in parentheses.

The example:

class Test { public static void main(String[] args) {


float fmin = Float.NEGATIVE_INFINITY;
float fmax = Float.POSITIVE_INFINITY;
System.out.println("long: " + (long)fmin +" to " + (long)fmax);
System.out.println("int: " + (int)fmin +" to " + (int)fmax);
System.out.println("short: " + (short)fmin +" to " + (short)fmax);
//System.out.println("short:"+(int)(char)(short)fmin+"to"+(int)(char)(short)fmax);
// This answer is 0 to 65535
System.out.println("char: " + (int)(char)fmin +" to " + (int)(char)fmax);
System.out.println("byte: " + (byte)fmin +" to " + (byte)fmax);} }
The output:
long: -9223372036854775808 to 9223372036854775807
int: -2147483648 to 2147483647
short: 0 to -1
char: 0 to 65535
byte: 0 to -1
4. Widening and Narrowing Primitive Conversions

The following conversion combines both widening and narrowing primitive


convesions: • byte to char

First, the byte is converted to an int via widening primitive conversion, and then
the resulting int is converted to a char by narrowing primitive conversion.

5. Widening Reference Conversions

18
A widening reference conversion exists from any type S to any type T, provided S
is a subtype of T Widening reference conversions never require a special action at run
time and therefore never throw an exception at run time. They consist simply in regarding
a reference as having some other type in a manner that can be proved correct at compile
time. See §8 for the detailed specifications for classes, §9 for interfaces, and §10 for
arrays.

6. Narrowing Reference Conversions

The following conversions are called the narrowing reference conversions:

• From any reference type S to any reference type T, provided that S is a proper
super type (§4.10) of T. (An important special case is that there is a narrowing
conversion from the class type Object to any other reference type.)

• From any class type C to any non-parameterized interface type K, provided that C
is not final and does not implement K.

• From any interface type J to any non-parameterized class type C that is notfinal.

• From the interface types Cloneable and java.io.Serializable to any array type T[].

• From any interface type J to any non-parameterized interface type K, provided


that J is not a subinterface of K.

• From any array type SC[] to any array type TC[], provided that SC and TC are
reference types and there is a narrowing conversion from SC to TC.

Such conversions require a test at run time to find out whether the actual reference
value is a legitimate value of the new type. If not, then a ClassCastException is thrown.

7. Boxing Conversion

Auto-boxing, which refers to automatic conversion. Boxing conversion converts


values of primitive type to corresponding values of reference type.

Boxing partially hides the distinction between primitives and corresponding wrapper
objects, but it doesn't remove it. There are two distinctions which are not changed by boxing:

• objects can be null, while primitives cannot.


• objects have both state and identity, while primitives have only state (the value) .

Some points to remember:

• Be careful with nulls. Auto-unboxing a null object will cause a NullPointerException.


19
• Comparing items with == and equals must be done with care.

The rules for comparison of primitives and wrapper objects are as follows. If x and y are either
both primitives, or both objects, then no boxing occurs:

Operation Two primitives Two objects

x == y compare value compare identity

x.equals(y does not compile compare value


)

If one item is a primitive, and the other item is a corresponding wrapper object, then boxing can
occur :

Operation Behavior

x == y treat as two primitives, and compare value

x.equals(y) does not compile if x is a primitive ; otherwise


treat as two objects, and compare value

Specifically, the following 8 conversion are called the boxing conversions:

1. From type boolean to type Boolean

2. From type byte to type Byte

3. From type char to type Character

4. From type short to type Short

5. From type int to type Integer

6. From type long to type Long

7. From type float to type Float

8. From type double to type Double

At run time, boxing conversion proceeds as follows:

 If p is a value of type boolean, then boxing conversion converts p into a reference

20
 r of class and type Boolean, such that r.booleanValue() == p

 If p is a value of type byte, then boxing conversion converts p into a reference

 r of class and type Byte, such that r.byteValue() == p

 If p is a value of type char, then boxing conversion converts p into a reference

 r of class and type Character, such that r.charValue() == p

 If p is a value of type short, then boxing conversion converts p into a reference

 r of class and type Short, such that r.shortValue() == p

 If p is a value of type int, then boxing conversion converts p into a reference

 r of class and type Integer, such that r.intValue() == p

 If p is a value of type long, then boxing conversion converts p into a reference

 r of class and type Long, such that r.longValue() == p

 If p is a value of type float then:

 If p is not NaN, then boxing conversion converts p into a reference r of


class and type Float, such that r.floatValue() evaluates to p

 Otherwise, boxing conversion converts p intoþ a reference r of class and


type Float such that r.isNaN() evaluates to true.

 If p is a value of type double, then

 If p is not NaN, boxing conversion converts p into a reference r of class


and type Double, such that r.doubleValue() evaluates to p

 Otherwise, boxing conversion converts p into a reference r of class and


type Double such that r.isNaN() evaluates to true.

 If p is a value of any other type, boxing conversion is equivalent to an identity

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or
short number between -128 and 127, then let r1 and r2 be the results of any two boxing
conversions of p. It is always the case that r1 == r2.

8. Unboxing Conversion

21
Auto-unboxing, which refers to automatic conversion of a Boolean to a boolean,
for example. Unboxing conversion converts values of reference type to corresponding
values of primitive type. Specifically, the following 8 conversion are called the unboxing
conversions:

1. From type Boolean to type boolean

2. From type Byte to type byte

3. From type Character to type char

4. From type Short to type short

5. From type Integer to type int

6. From type Long to type long

7. From type Float to type float

8. From type Double to type double

At run time, unboxing conversion proceeds as follows:

 If r is a reference of type Boolean, then unboxing conversion converts r into


r.booleanValue().

 If r is a reference of type Byte, then unboxing conversion converts r intoþ r.byteValue().

 If r is a reference of type Character, then unboxing conversion converts r into


r.charValue().

 If r is a reference of type Short, then unboxing conversion converts r into r.shortValue().

 If r is a reference of type Integer, then unboxing conversion converts r into r.intValue().

 If r is a reference of type Long, then unboxing conversion converts r into r.longValue().

 If r is a reference of type Float, unboxing conversion converts r intoþ r.floatValue().

 If r is a reference of type Double, then unboxing conversion converts r into


r.doubleValue().

 If r is null, unboxing conversion throws a NullPointerException .

A type is said to be convertible to a numeric type if it is a numeric type, or it is a


reference type that may be converted to a numeric type by unboxing conversion. A type

22
is said to be convertible to an integral type if it is an integral type, or it is a reference type
that may be converted to an integral type by unboxing conversion.

What is difference between equals() and == ?

They both differ very much in their significance. equals() method is present in the
java.lang.Object class and it is expected to check for the equivalence of the state of objects! That
means, the contents of the objects. Whereas the '==' operator is expected to check the actual
object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different
reference variables s1 and s2.

s1 = new String("abc");

s2 = new String("abc");

Now, if you use the "equals()" method to check for their equivalence as

if(s1.equals(s2))

System.out.println("s1.equals(s2) is TRUE");

else

System.out.println("s1.equals(s2) is FALSE");

You will get the output as TRUE as the 'equals()' method check for the content equivality.

Lets check the '==' operator..

if(s1==s2)

System.out.printlln("s1==s2 is TRUE");

else

System.out.println("s1==s2 is FALSE");

Now you will get the FALSE as output because both s1 and s2 are pointing to two different
objects even though both of them share the same string content. It is because of 'new String()'
everytime a new object is created.

Try running the program without 'new String' and just with

String s1 = "abc";

String s2 = "abc";
23
You will get TRUE for both the tests.

Explanation

By definintion, the objects are all created on the heap. When you create an object, say,

Object ob1 = new SomeObject();

Object ob2 = new SomeObject();

We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets
say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects
are the same, the references differ.

sing == compares the references. Though the objects, ob1 and ob2 are same internally,
they differ on using this operation as we comare references. ob1 at address 0x1234 is compared
with ob2 at address 0x2345. Hence, this comparison would fail.

object.equals() on the other hand compares the values. Hence, the comparison between
ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this
comparison to succeed. Hence, == compares the reference value of object whereas equals()
compares content of the object.

One of the main advantages of this feature is that it automatically boxes and
unboxes the primitive data types to their corresponding wrapper classes.

Advantages of Boxing

1. Less code to write.

a. The code looks cleaner.

As an example, consider an int being stored and then retrieved from an ArrayList:

list.add(0, new Integer(59));

int n = ((Integer)(list.get(0))).intValue();

The new autoboxing/unboxing feature eliminates this manual conversion. The above
segment of code can be written as:

list.add(0, 59);

int total = list.get(0);

2. The best method for conversion is automatically chosen, e.g. Integer.valueOf(int) is used
instead of new Integer(int).
24
Disadvantages of Boxing (don’t use):

1. Avoid using wrapper classes whenever possible.

2. Never do math with wrappers.

3. Try not to use any of the comparison operators (<, >, <=, >=, ==, etc) with wrappers.

4. Avoid usage in loop statements.

5. Always check for null values.

6. Overloading

1. Avoid using wrapper classes whenever possible.

Wrapper classes should only be used whenever you absolutely cannot use a primitive.
Otherwise, auto-unbox (de-autobox) the value and use the primitives.

2. Never do math with wrappers.

This is a simple one that instinctively goes along with #1. Doing math with wrapper
classes forces a auto-unboxing operation to occur for each operator. Therefore, this code will
cause five auto-unboxing operations and two auto-boxing operation to occur:

Integer i = 42;

i = i + i + i + i + i;

This code generates this byte code:

0: bipush 42

2: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

5: astore_0

6: aload_0

7: invokevirtual #3; //Method java/lang/Integer.intValue:()I

10: aload_0

11: invokevirtual #3; //Method java/lang/Integer.intValue:()I

14: iadd

15: aload_0

25
16: invokevirtual #3; //Method java/lang/Integer.intValue:()I

19: iadd

20: aload_0

21: invokevirtual #3; //Method java/lang/Integer.intValue:()I

24: iadd

25: aload_0

26: invokevirtual #3; //Method java/lang/Integer.intValue:()I

29: iadd

30: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

33: astore_0

As you can see, the valueOf method is used to auto-box the initial value and the
intValue method is used to auto-unbox the values. The auto-unboxing happens five times and
the auto-boxing happens twice. If we use primitives instead, this is the bytecode that is created:

2: istore_0

3: iload_0

4: iload_0

5: iadd

6: iload_0

7: iadd

8: iload_0

9: iadd

10: iload_0

11: iadd

12: istore_0

Much simpler and no object creation or method calls. This code will perform much faster
than the previous example and therefore using primitives is always preferred when doing any
math at all.
26
This applies to for loop variables and counts. Using an Integer as a loop variable can
reduce performance of that loop because of the need to create new objects each loop iteration
during the auto-box operation.

3. Try not to use any of the comparison operators (<, >, <=, >=, ==, etc) with wrappers.

Auto-boxing allows you to use all of the comparison operators, except the ==. It will de-
autobox (auto-unbox) the values and compare them correctly. The problem here is that each
comparison will cause an auto-unboxing to occur and it also promotes bad style with respect to
wrapper usage. In addition, since we don’t get the == operator, to be consistent the rest of those
operators should be avoided. This is more of a coding style and practices thing, but if you are
going to be doing comparisons, you should probably unbox the values.

4. Avoid usage in loop statements.

Using wrapper classes in statements is not as much of a performance drain as doing math
with them, but it does introduce a method call during each loop iteration in order to auto-unbox
the values in order to do the comparison. This is an extension to rule #3 for capturing usages in
do, while, and for loops. This usage is not preferred:

Integer len = getLength();

for (int i = 0; i < len; i++) { ... }

This will auto-unbox the len variable during each loop iteration. Although this is simply a
method call to the intValue method, it should still be avoided. This is better:

Integer len = getLength();

int lenInt = len;

for (int i = 0; i < lenInt; i++) { ... }

5. Always check for null values.

This is a bit teadious, but when wrapper class variables are null a NullPointerException will be
thrown when doing auto-unboxing. This code illustrates this problem:

Integer len = null

int lenInt = len; // Throws NullPointerException

27
You can use terenary expresions to prevent the NullPointerExceptions or write a toolkit to do
this. Toolkits in conjunction with static imports reduce the code mess of terenary expressions.
Here is an example of both:

// Terenary

Integer wrapper = getValue();

int intValue = (wrapper == null) ? 0 : wrapper;

// Static import toolkit

import static com.inversoft.util.AutoBoxTools., ;

Integer wrapper = getValue();

int intValue = unbox(wrapper, 0);

Any which way you slice it, you want some easy method for handling null values when
you know that they are possible. If they aren’t possible, then this rule can be ignored.

6. Overloading

01 public static void main(String[] args) throws Exception


02 {
03 <smartlink>Integer</smartlink> l = 0;
04 fubar(l);
05 }
06 static void fubar(long b) {
07 System.out.println("1");
08 }
09 static void fubar(Long b) {
10 System.out.println("2");
11 }
The result is 1. Because there is no direct conversion from Integer to Long, so the “conversion”
from Integer to long is used.

1. Boxing and Unboxing operation

Boxing-operation means the parcels can generate a basic types of data object to make the
basic types of data could be used in a type of place.

List 1: manual is typical Boxing

Collection integers = new ArrayList ();

28
For (int i = 0; i <10; i + +) (

Integers.add (new Integer (i));

Used to generate the object of these categories, and has been called "wrapped category"
(Wrapper Classes). Parcels in Java Byte Class, Short, Integer, Long, Float, Double, Character
and Boolean (in the java.lang package definition), eight were for parcels byte, short, int, long,
float, double , char and boolean types of data.

The so-called Unboxing operation, it refers to the object type called inclusions corresponding
method, they represent the "basic types of data" for further disposal.

List 2: a classic case of manual Unboxing

For (Iterator itr = integers.iterator (); itr.hasNext ()) (

Integer i = (Integer) itr.next ();

System.out.println (i.intValue () + 1); )

In the latest version of the Java language - J2SE 1.5, provides "Autoboxing" and "Auto-
Unboxing" mechanism that allows the compiler to automatically complete these trivial operation,
to use a more simple approach to integration Two types of systems.

While this is the history of the operation of a long, but they called "Boxing" and
"Unboxing" approach is basically in a "Autoboxing" and "Auto-Unboxing" concept, it is widely
accepted. Before that, they seem to have a common, specific names. But since then rarely
mentioned these two concepts, so the problem Daoyemei resulted in any serious impact.

2. Use Autoboxing and Auto-Unboxing

Autoboxing and use Auto-Unboxing and do not need any special steps, and all the
compiler will be arranged happen automatically.

This can now be treated to an int data type:

List 3: automatic operation completed Boxing

Collection al = new ArrayList ();

Al.add (1);

Because the compiler will quietly convert this code to close this:

List 4: Autoboxing made after the equivalent form


29
Collection al = new ArrayList ();

Al.add (new Integer (1));

And the way to treat an Integer type is the object can be:

5 list: Automatic operation completed Unboxing

Integer one = new Integer (1);

Int two one + = 1;

Because the compiler will quietly to this code into shape similar to this:

List 6: Auto-Unboxing made after the equivalent form

Integer one = new Integer (1);

Int two one.intValue = () + 1;

In general, as long as the type is a result of basic types of expression, in the need to
allow their inclusion of the position, it will induce Autoboxing; similar, as long as the package
type is a result of the expression, in the allow only the basic types in the corresponding position,
it will induce Auto-Unboxing.

3. Autoboxing in the specific timing

Autoboxing a specific time, there are three such:

1. The basic types of data used assign types of variables. For example, an int data type
assign an Integer type variables.

List 7: assign types of variables used basic types of data

Integer i = 31415;

2. The basic types of data transmission quoted types of parameters. For example, to a
definition of the parameters into Object send a boolean type of data.

List 8: invoke types of parameters passed basic types of data

HashMap map = new HashMap ();

Map.put (true, null);

3. The basic types of data to the type used at the mandatory conversion. For example, in a
long-type data added to the front (Long).

30
List 9: from the basic types of data type to invoke mandatory conversion

System.out.println ((Long) 27828L);

4. Autoboxing limitations

Autoboxing mechanism there is a limited - only the basic types of data to their
own parcels category (as well as the inclusion of higher-level category) conversion.

Similar code is not working, despite the int data type can be used completely object to a
Long said:

List of 10: not automatically upwards at the same time restructuring and
Autoboxing

Int i = 27828;

System.out.println ((Long) i) / , compile-time error , /

This is because this code actually equals:

List 11: Autoboxing operation will be automatically before the upward transition

Int i = 27828;

System.out.println ((Long) new Integer (i)) / , compile-time error , /

Long Integer and is not a subclass, so the transformation impossible. If it must be carried out
this operation, a transition needs additional manual:

List 12: mandatory upward transition need to re-Boxing

Int i = 27828;

System.out.println ((Long) (long) new Integer (i));

5. Occurred Auto-Unboxing the specific timing

Auto-Unboxing in the specific timing, mainly have seven:

1. Assign parcel of the basic types of object variables. For instance, one type Integer assign
an int data type variables.

List 13: assign basic types of variable objects such parcels

Int i = new Integer (32);

31
2. Parcel of the basic types of objects pass parameters. For example, to a definition of the
parameters of a boolean send a Boolean data type.

List 14: basic types of parameters passed package of targets

JFrame frame = new JFrame ("^_^");

Frame.setSize (320, 200);

Frame.setVisible (new Boolean (true));

3. Object to the inclusion of basic types, mandatory conversion. For example, in a Long
data added to the front of the (long).

List of 15: from object to the inclusion of basic types of mandatory conversion

Long l = new Long (31415L);

System.out.println ((long) l);

4. The inclusion of the object to be the operator when the operation of a few. For example,
in the two-Byte data placed between the "+".

List 16: the inclusion of objects as operator of the operation

Byte a new Byte = ((byte) 1);

Byte b = new Byte ((byte) -1);

System.out.println (((a + +) <<2) + (~ b)) / , output "4" , /

System.out.println (a) / , output "2" , /

5. Parcels with an array of objects to the specified size. Of course, from a semantic said that
the type of the object must be Byte, Short, Integer or Character.

List 17: The designated parcels of objects the size of an array

Character size = new Character ( '★');

Int integers [] = new int [size]; / , create a caving 9733 int element of the array , /

6. The inclusion of targets in the switch statement in use. Of course, from a semantic said
that the type of the object must be Byte, Short, Integer or Character.

List of 18: in the switch statement in the use of targeted parcels

Character c = new Character ( 'a');


32
Switch (c) (

Case 'a':

Case 'e':

Case 'i':

Case 'o':

Case 'u':

System.out.println ( "A Vowel in English");

Break;

Default:

System.out.println ( "Not A Vowel in English");

Break;

7. Boolean object in the if / for / while / do-while statements as conditionals use.

List of 19: the Boolean object as conditionals

Boolean bool = new Boolean (Math.random ()> 0.5);

If (bool) (

System.out.println ( "Aye!");

Else ()

System.out.println ( "Nay!");

6. Auto-Unboxing limitations

Auto-Unboxing the mechanism will have such a limited - only object to the
inclusion of their corresponding basic types (as well as to accommodate a wider range of types)
conversion.

Similar code is not working, although not in excess of 32 byte can say:

List 20: Auto-not at the same time and forced downward transition Unboxing
33
Integer i = new Integer (32);

System.out.println ((byte) i) / , compile-time error , /

This is because the compiler is not recognized at the same time Auto-Unboxing
transition and forced down the operation, so the transformation impossible. If it must be carried
out this operation to manually add a transition:

List of 21: the need to make Unboxing, then forced downward transition

Integer i = new Integer (32);

System.out.println ((byte) (int) i);

But at the same time Auto-Unboxing and forced upward restructuring operation is no problem,
so the following code work very normal:

List 22: Auto-can be carried out at the same time and forced upward transition Unboxing

Integer i = new Integer (32);

System.out.println ((double) i);

7. Not automatically translate into the other cases

Type transformation when forced to remove the restrictions, there are some
cases that will not happen Autoboxing / Auto-Unboxing:

1. Basic types of array and parcels will not be among the array of automatic conversion. This
code will not be entirely acceptable compiler:

List 23: elements can be, not containers

Ints int [] = (1, 2, 3);

Integer = integers [] ints; / , compile-time error , /

2. Not facing basic types of expression to call in the method of parcels. This application will
be rejected completely compiler:

List 24: no way, no way

Int i = 1;

I.byteValue byte b = () / , compile-time error , /

8. Null conversion issue

34
Java, the application can be a special type of value - "null." Auto carried out in an
attempt to null-Unboxing operation will lead to a "NullPointerException."

For example, this code will be dished out in the run-time anomaly, despite the compiler will be
shown during a very normal:

List 25: on the surface, just an ordinary assignment

Integer i = null;

Int j = i; / , runtime error , /

This is because this code actually equals:

List of 26: In fact, in trying to call the method null

Integer i = null;

Int j = i.intValue (); / , runtime error , /

Null and tried to call the method is a virtual machine is not acceptable behavior.

9. Override the impact of

Java support "override" mechanism, allowing in the same category has many names-the
Senate and the same list different methods. Then, by the compiler at the time of call is in
accordance with the Senate to choose which one to be implemented in the end.

Autoboxing / Auto-Unboxing mechanism for the introduction of a slight increase for a


number of options to consider such factors - because it may be a way both to accept a one-
parameter version of Integer, another to accept an int Type parameter version, and Autoboxing /
Auto-Unboxing automatic mechanism in the Senate is between these two types of
transformation, the original judge rules alone, the two are competing. However, at the same
time because there are two versions of this approach is entirely reasonable, and here is not a
"reference to the method name to be called is ambiguous" compile errors to evade its
responsibility. This requires an increase in the judgement of the new rules.

This new rule is that not a Autoboxing / Auto-Unboxing version, and give priority to the
need for Autoboxing / Auto-Unboxing version.

Therefore, in such circumstances where a specific choice depends on the initial transfer
of the Senate is what type.

List of 27: not to Autoboxing / Auto-Unboxing version priority

Public class OverloadingTest

35
(
Private static void testOverloading (int i) (
System.out.println ( "int");
)
Private static void testOverloading (Integer i) (
System.out.println ( "Integer");
)
Public static void main (String [] args)
(
Int i = 1;
Integer j = new Integer (1);
TestOverloading (i) / , output "int" , /
TestOverloading (j) / , output "Integer" , /
)
)
10. Equal value and invoke the same

In the Java language has two different types of "equal" concept - the same value and
invoke the same. This makes it a "value equal to two basic types of data, after Autoboxing,
quoted by the subject of whether or not the same."

"JSR 201: Extending the Java Programming Language with Enumerations, Autoboxing,
Enhanced for loops and Static Import", on this issue, and such a provision is made:

If the value p being boxed is true, false, a byte, an ASCII character, or an integer or
short number between -127 and 128, then let r1 and r2 be the results of any two boxing
conversions of p. It is always the case that r1 == r2.

This means that the answer may be "yes" may be "No", was Autoboxing data from the
type and value to decide. Therefore, in testing whether the two representatives of the same
value, there is a need calls equals () method to carry out.

But in J2SDK 1.5 Beta 1 and Beta 2 in the actual situation, and this slightly different
from the "Autoboxing after getting the same object reference" by narrowing the scope of:

List 28: equal to the original value, after Autoboxing may be invoked after the same, or may not
equal

Boolean b = true;
Boolean b1 = b;
Boolean b2 = b;
System.out.println (b1 == b2); / , output "true" , /
Char c ='1 ';
36
Character c1 = c;
Character c2 = c;
System.out.println (c1 = c2); / , output "false" , /
11. Hampered performance

As Autoboxing mechanism, in essence, is "automatically created to represent basic types


of data," and therefore, the inevitable result will be of some prejudice.

If only use Autoboxing / Auto-Unboxing mechanism to preserve basic types of data (for
example, the basic types of Collection inside the data center), Daohai this impact can be ignored,
because it is only necessary to the original manual and the automated However, if we are to
Autoboxing frequent use of a parcel to assign values to variables, which can easily cost up to the
extent necessary to pay close attention to.

Attention to the inclusion of the variables using the "+ +" and "-" operator at the time,
will also create new audiences, rather than amending the original target state.

List 29: replacement is not amended

Integer i = new Integer (1);


Integer j = i; / , j, i point to the same object , /
System.out.println (i == j) / , the current j, i is the same object, the output "true" , /
I + +;
System.out.println (i == j) / , Now j, i is different objects, the output "false" , /
System.out.println (i) / , now i is the value of "2" , /
System.out.println (j) / , and j is the value of "1" , /
This phenomenon is due to the inclusion in the Java category is "not change (immutable)" - that
is, not allow ourselves to provide a value represented by the changes in the way - and causes.

Need a large number assignment, we can through the appropriate use of some basic types of
local variables to mitigate the impact on performance. However, if the performance bottleneck
lies in a container to frequent Add basic types of data, I am afraid it would rely on using some
specialized to accommodate basic types of data containers designed to address the type (for
example, components Jarkata Commons Primitives in the provision of those).

List 30: A section of a container needs to frequent Add to the basic types of data
procedures

Import java.util ., ;
(Public class WordCounter
Public static void main (String [] args) (
HashMap counts = new HashMap ();
For (int i = 0; i <args.length; i + +) (

37
String current = args [i];
If (counts.containsKey (current)) (
Counts.put (current, ((Integer) counts.get (current)) + 1);
Else ()
Counts.put (current, 1);
)
)
For (Iterator itr = counts.keySet (). Iterator (); itr.hasNext ()) (
String key = (String) itr.next ();
System.out.println (key + ":" + counts.get (key));
) ) )
Assignment Conversion

Assignment conversion occurs when the value of an expression is assigned to a variable:


the type of the expression must be converted to the type of the variable. Assignment contexts
allow the use of one of the following:

1. an identity conversion

2. a widening primitive conversion

3. a widening reference conversion

4. a boxing conversion optionally followed by a widening reference conversion

5. an unboxing conversion optionally followed by a widening primitive conversion.

If, after the conversions listed above have been applied, the resulting type is a raw type,
unchecked conversion (§5.1.9) may then be applied. It is a compile time error if the chain of
conversions contains two parameterized types that are not not in the subtype relation.

In addition, if the expression is a constant expression of type byte, short, char or int :

• A narrowing primitive conversion may be used if the type of the variable is byte, short, or
char, and the value of the constant expression is representable in the type of the variable.

• A narrowing primitive conversion followed by a boxing conversion may be used if the


type of the variable is:

o Byte and the value of the constant expression is representable in the type byte.

o Short and the value of the constant expression is representable in the type short.

o Character and the value of the constant expression is representable in the type
char.
38
If the type of the expression cannot be converted to the type of the variable by a conversion
permitted in an assignment context, then a compile-time error occurs.

If the type of the variable is float or double, then value set conversion is applied to the value v
that is the results of the type conversion:

• If v is of type float and is an element of the float-extended-exponent value set, then the
implementation must map v to the nearest element of the float value set. This conversion
may result in overflow or underflow.

• If v is of type double and is an element of the double-extended-exponent value


set, then the implementation must map v to the nearest element of the double
value set. This conversion may result in overflow or underflow.

If the type of an expression can be converted to the type of a variable by assignment


conversion, we say the expression (or its value) is assignable to the variable or, equivalently, that
the type of the expression is assignment compatible with the type of the variable. If, after the
type conversions above have been applied, the resulting value is

An object which is not an instance of a subclass or subinterface of the erasure of the type of the
variable, then a ClassCastException is thrown.

The only exceptions that an assignment conversion may cause are:

• An OutOfMemoryError as a result of a boxing conversion.

• A ClassCastException in the special circumstances indicated above.

• A NullPointerException as a result of an unboxing conversion on a null reference.

The following test program contains examples of assignment conversion of primitive values:

class Test {
public static void main(String[] args) {
short s = 12; // narrow 12 to short
float f = s; // widen short to float
System.out.println("f=" + f);
char c = '\u0123';
long l = c; // widen char to long
System.out.println("l=0x" + Long.toString(l,16));
f = 1.23f;
double d = f; // widen float to double
System.out.println("d=" + d);
39
}}
It produces the following output:
f=12.0
l=0x123
d=1.2300000190734863
The following test, however, produces compile-time errors:
class Test {
public static void main(String[] args) {
short s = 123;
char c = s; // error: would require cast
s = c; // error: would require cast
}}
Because not all short values are char values, and neither are all char values short values.

A value of the null type (the null reference is the only such value) may be assigned to any
reference type, resulting in a null reference of that type.

Here is a sample program illustrating assignments of references:

public class Point { int x, y; }


public class Point3D extends Point { int z; }
public interface Colorable {
void setColor(int color);
}
public class ColoredPoint extends Point implements Colorable
{
int color;
public void setColor(int color) { this.color = color; }
}
class Test {
public static void main(String[] args) {
// Assignments to variables of class type:
Point p = new Point();
p = new Point3D(); // ok: because Point3D is a
// subclass of Point
Point3D p3d = p; // error: will require a cast because a
// Point might not be a Point3D
// (even though it is, dynamically,
// in this example.)
// Assignments to variables of type Object:
Object o = p; // ok: any object to Object
int[] a = new int[3];
40
Object o2 = a; // ok: an array to Object
// Assignments to variables of interface type:
ColoredPoint cp = new ColoredPoint();
Colorable c = cp; // ok: ColoredPoint implements
// Colorable
// Assignments to variables of array type:
byte[] b = new byte[4];
a = b; // error: these are not arrays
// of the same primitive type
Point3D[] p3da = new Point3D[3];
Point[] pa = p3da; // ok: since we can assign a
// Point3D to a Point
p3da = pa; // error: (cast needed) since a Point
// can't be assigned to a Point3D
}
}
The following test program illustrates assignment conversions on reference values, but fails to
compile, as described in its comments. This example should be compared to the preceding one.

public class Point { int x, y; }


public interface Colorable { void setColor(int color); }
public class ColoredPoint extends Point implements Colorable
{
int color;
public void setColor(int color) { this.color = color; }
}
class Test {
public static void main(String[] args) {
Point p = new Point();
ColoredPoint cp = new ColoredPoint();
// Okay because ColoredPoint is a subclass of Point:
p = cp;
// Okay because ColoredPoint implements Colorable:
Colorable c = cp;
// The following cause compile-time errors because
// we cannot be sure they will succeed, depending on
// the run-time type of p; a run-time check will be
// necessary for the needed narrowing conversion and
// must be indicated by including a cast:
cp = p; // p might be neither a ColoredPoint
// nor a subclass of ColoredPoint
41
c = p; // p might not implement Colorable
}}
Here is another example involving assignment of array objects:

class Point { int x, y; }


class ColoredPoint extends Point { int color; }
class Test {
public static void main(String[] args) {
long[] veclong = new long[100];
Object o = veclong; // okay
Long l = veclong; // compile-time error
short[] vecshort = veclong;// compile-time error
Point[] pvec = new Point[100];
ColoredPoint[] cpvec = new ColoredPoint[100];
pvec = cpvec; // okay
pvec[0] = new Point(); // okay at compile time,
// but would throw an
// exception at run time
cpvec = pvec; // compile-time error
}}
In this example:

• The value of veclong cannot be assigned to a Long variable, because Long is a class type
other than Object. An array can be assigned only to a variable of a compatible array type,
or to a variable of type Object, Cloneable or java.io.Serializable.

• The value of veclong cannot be assigned to vecshort, because they are arrays of primitive
type, and short and long are not the same primitive type.

• The value of cpvec can be assigned to pvec, because any reference that could be the value
of an expression of type ColoredPoint can be the value of a variable of type Point. The
subsequent assignment of the new Point to a component of pvec then would throw an
ArrayStoreException (if the program were otherwise corrected so that it could be
compiled), because a ColoredPoint array can’t have an instance of Point as the value of a
component.

• The value of pvec cannot be assigned to cpvec, because not every reference that could be
the value of an expression of type ColoredPoint can correctly be the value of a variable of
type Point. If the value of pvec at run time were a reference to an instance of Point[], and
the assignment to cpvec were allowed, a simple reference to a component of cpvec, say,
cpvec[0], could return a Point, and a Point is not a ColoredPoint. Thus to allow such an

42
assignment would allow a violation of the type system. A cast may be used to ensure that
pvec references a ColoredPoint[]:

cpvec = (ColoredPoint[])pvec;// okay, but may throw an // exception at run time.

Method Invocation Conversion

Method invocation conversion is applied to each argument value in a method or constructor


invocation the type of the argument expression must be converted to the type of the
corresponding parameter. Method invocation contexts allow the use of one of the following:

• an identity conversion

• a widening primitive conversion

• a widening reference conversion

• a boxing conversion optionally followed by widening reference conversion

• an unboxing conversion optionally followed by a widening primitive conversion.

If, after the conversions listed above have been applied, the resulting type is a raw type, an
unchecked conversion may then be applied. It is a compile time error if the chain of conversions
contains two parameterized types that are not in the subtype relation.

If the type of an argument expression is either float or double, then value set conversion is
applied after the type conversion:

• If an argument value of type float is an element of the float-extended-exponent value set,


then the implementation must map the value to the nearest element of the float value set.
This conversion may result in overflow or underflow.

• If an argument value of type double is an element of the double-extendedexponent value


set, then the implementation must map the value to the nearest element of the double
value set. This conversion may result in overflow or underflow.

If, after the type conversions above have been applied, the resulting value is an object which is
not an instance of a subclass or subinterface of the erasure of the corresponding formal parameter
type, then a ClassCastException is thrown.

Casting conversion

Casting conversion is applied to the operand of a cast operator (§15.16): the type of the operand
expression must be converted to the type explicitly named by the cast operator. Casting contexts
allow the use of:

43
• an identity conversion

• a widening primitive conversion

• a narrowing primitive conversion

• a widening reference conversion optionally followed by an unchecked conversion

• a narrowing reference conversion optionally followed by an unchecked conversion

• a boxing conversion

• an unboxing conversion

Thus casting conversions are more inclusive than assignment or method invocation conversions:
a cast can do any permitted conversion other than a string conversion or a capture conversion

Value set conversion is applied after the type conversion. Some casts can be proven incorrect at
compile time; such casts result in a compile-time error.

A value of a primitive type can be cast to another primitive type by identity conversion, if the
types are the same, or by a widening primitive conversion or a narrowing primitive conversion.

A value of a primitive type can be cast to a reference type by boxing conversion

A value of a reference type can be cast to a primitive type by unboxing conversion

If a run-time exception is thrown, it is a ClassCastException.

Here are some examples of casting conversions of reference types, similar to the example in

public class Point { int x, y; }


public interface Colorable { void setColor(int color); }
public class ColoredPoint extends Point implements Colorable
{
int color;
public void setColor(int color) { this.color = color; }
}
final class EndPoint extends Point { }
class Test {
public static void main(String[] args) {
Point p = new Point();
ColoredPoint cp = new ColoredPoint();
Colorable c;
// The following may cause errors at run time because
44
// we cannot be sure they will succeed; this possibility
// is suggested by the casts:
cp = (ColoredPoint)p;// p might not reference an
// object which is a ColoredPoint
// or a subclass of ColoredPoint
c = (Colorable)p; // p might not be Colorable
// The following are incorrect at compile time because
// they can never succeed as explained in the text:
Long l = (Long)p; // compile-time error #1
EndPoint e = new EndPoint();
c = (Colorable)e; // compile-time error #2
}
}
Here the first compile-time error occurs because the class types Long and Point are
unrelated (that is, they are not the same, and neither is a subclass of the other), so a cast between
them will always fail.

The second compile-time error occurs because a variable of type EndPoint can never
reference a value that implements the interface Colorable. This is because EndPoint is a final
type, and a variable of a final type always holds a value of the same run-time type as its compile-
time type. Therefore, the run-time type of variable e must be exactly the type EndPoint, and type
EndPoint does not implement Colorable.

Here is an example involving arrays:

class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
public String toString() { return "("+x+","+y+")"; }
}
public interface Colorable { void setColor(int color); }
public class ColoredPoint extends Point implements Colorable
{
int color;
ColoredPoint(int x, int y, int color) {
super(x, y); setColor(color);
}
public void setColor(int color) { this.color = color; }
public String toString() {
return super.toString() + "@" + color;
}
}
45
class Test {
public static void main(String[] args) {
Point[] pa = new ColoredPoint[4];
pa[0] = new ColoredPoint(2, 2, 12);
pa[1] = new ColoredPoint(4, 5, 24);
ColoredPoint[] cpa = (ColoredPoint[])pa;
System.out.print("cpa: {");
for (int i = 0; i < cpa.length; i++)
System.out.print((i == 0 ? " " : ", ") + cpa[i]);
System.out.println(" }");
}
}
This example compiles without errors and produces the output:

cpa: { (2,2)@12, (4,5)@24, null, null }

The following example uses casts to compile, but it throws exceptions at run

time, because the types are incompatible:

public class Point { int x, y; }


public interface Colorable { void setColor(int color); }
public class ColoredPoint extends Point implements Colorable
{
int color;
public void setColor(int color) { this.color = color; }
}
class Test {
public static void main(String[] args) {
Point[] pa = new Point[100];
// The following line will throw a ClassCastException:
ColoredPoint[] cpa = (ColoredPoint[])pa;
System.out.println(cpa[0]);
int[] shortvec = new int[2];
Object o = shortvec;
// The following line will throw a ClassCastException:
Colorable c = (Colorable)o;
c.setColor(0);
}
}
Numeric Promotions

46
Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion
contexts allow the use of an identity conversion (§5.1.1) a widening primitive conversion
(§5.1.2), or an unboxing conversion (§5.1.8). Numeric promotions are used to convert the
operands of a numeric operator to a common type so that an operation can be performed.

The two kinds of numeric promotion are unary numeric promotion and binary
numeric promotion

Unary Numeric Promotion

Some operators apply unary numeric promotion to a single operand, which must produce a value
of a numeric type:

• If the operand is of compile-time type Byte, Short, Character, or Integer it is subjected to


unboxing conversion. The result is then promoted to a value of type int by a widening
conversion or an identity conversion.

• Otherwise, if the operand is of compile-time type Long, Float, or Double it is


subjected to unboxing conversion.

• Otherwise, if the operand is of compile-time type byte, short, or chars, unary


numeric promotion promotes it to a value of type int by a widening conversion.

• Otherwise, a unary numeric operand remains as is and is not converted.

In any case, value set conversion is then applied.

• Unary numeric promotion is performed on expressions in the following situations:

• Each dimension expression in an array creation expression

• The index expression in an array access expression

• The operand of a unary plus operator +

• The operand of a unary minus operator -

• The operand of a bitwise complement operator ~

• Each operand, separately, of a shift operator >>, >>>, or << (§15.19); therefore a long
shift distance (right operand) does not promote the value being shifted (left operand) to
long

Here is a test program that includes examples of unary numeric promotion:

class Test {
47
public static void main(String[] args) {
byte b = 2;
int a[] = new int[b]; // dimension expression promotion
char c = '\u0001';
a[c] = 1; // index expression promotion
a[0] = -c; // unary - promotion
System.out.println("a: " + a[0] + "," + a[1]);
b = -1;
int i = ~b; // bitwise complement promotion
System.out.println("~0x" + Integer.toHexString(b)
+ "==0x" + Integer.toHexString(i));
i = b << 4L; // shift promotion (left operand)
System.out.println("0x" + Integer.toHexString(b)
+ "<<4L==0x" + Integer.toHexString(i));
}
}
This test program produces the output:

a: -1,1

~0xffffffff==0x0

0xffffffff<<4L==0xfffffff0

Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must
denote a value that is convertible to a numeric type, the following rules apply, in order, using
widening conversion (§5.1.2) to convert operands as necessary:

• If any of the operands is of a reference type, unboxing conversion is performed. Then:

• If either operand is of type double, the other is converted to double.

• Otherwise, if either operand is of type float, the other is converted to float.

• Otherwise, if either operand is of type long, the other is converted to long.

• Otherwise, both operands are converted to type int.

After the type conversion, if any, value set conversion is applied to each operand.

Binary numeric promotion is performed on the operands of certain operators:

• The multiplicative operators , , / and %


48
• The addition and subtraction operators for numeric types + and –

• The numerical comparison operators <, <=, >, and >=

• The numerical equality operators == and !=

• The integer bitwise operators &, ^, and |

• In certain cases, the conditional operator ? :

An example of binary numeric promotion appears above in. Here is another:

class Test {
public static void main(String[] args) {
int i = 0;
float f = 1.0f;
double d = 2.0;
// First int, float is promoted to float, float, then
// float==double is promoted to double==double:
if (i , f == d)
System.out.println("oops");
// A char&byte is promoted to int&int:
byte b = 0x1f;
char c = 'G';
int control = c & b;
System.out.println(Integer.toHexString(control));
// Here int:float is promoted to float:float:
f = (b==0) ? i : 4.0f;
System.out.println(1.0/f);
}
}
which produces the output:
7
0.25
The example converts the ASCII character G to the ASCII control-G (BEL), by

masking off all but the low 5 bits of the character. The 7 is the numeric value of

this control character.

Types of Constants

There are seven different animals loosely called constants: .

49
1. Literals

e.g.

42, "abc"

You may use byte, short, char and int literals as switch case labels. However
longs and Strings are not supported.

2. Compile Time Constants

or just plain compile constants, Officially known as “compile-time constant expressions”


these are static finals whose value

// constants known at compile time

static final int ARMS = 2;

static final int LIMBS = ARMS , 2;

These can be used as switch case labels, subject, of course, to the usual byte, short, char
and int-only restriction.

3. Load-Time Class Constants

or just plain load constants, static finals whose value is not known

static final int SERIALNUMBER = ++generator;

These cannot used in switch case labels. All the "variables" in an interface are implicitly
static finals. They may be either compile time constants or load time constants.

4. Instance Constants

instance finals whose value is not known until object instantiation time, e. g.

These too cannot used as switch case labels. It is sometimes possible for an instance
constant to be evaluated at compile time. In that case it is treated like a literal, much like
a static compile-time constant. You can use a compile-time local int constant as a case
label.

5. Local Constants

stack finals whose value is not known until the method executes, e. g.

final int bottomLine = getTax();

These too cannot used as switch case labels.


50
final int LEGS = 2;

As in the example above, it is sometimes possible for a local constant to be evaluated at


compile time. In that case it is treated like a literal, much like a static compile-time
constant. You can use a compile-time local int constant as a case label.

6. Parameter Constants

A parameter marked final. This indicates the called method will never change its local
copy of the passed parameter.

7. enum Constants

The names of the possibilities for an enum. These are under-the-hood static finals
evaluated at load time, but through the magic of Java, you can use them as if they were
known at compile time, e.g. as case labels.

Sun’s coding conventions require constants to have names all in capital letters.

Compile Time vs Load Time Constants

Compile time constants are evaluated at compile time, and treated as if they were literals, inlined
in the code. It is not totally obvious which expression Java can evaluate at compile time.
Compile time and load time constants look similar. Both are static final. Here are some examples
to help:

Compile Time vs Load Time Constants

Expression Compile
Time
or
Load Time
public static final int DAYS_IN_WEEK = 7; Compile
Time
public static final int SECONDS_PER_HOUR = 60 , 60; Compile
Time
public static final String COPYRIGHT = "Copyright (c) " + "2005"; Compile
Time
public static final int POSTAGE_IN_CENTS = 60; Compile
public static final int HANDLING_IN_CENTS = 500; Time
public static final int EXTRA_IN_CENTS = POSTAGE_IN_CENTS +
HANDLING_IN_CENTS;
public static final int POSTAGE_IN_CENTS = 60; Compile
public static final int HANDLING_IN_CENTS = 500; Time
public static final int BIGGER_IN_CENTS =
( POSTAGE_IN_CENTS > HANDLING_IN_CENTS )
51
? POSTAGE_IN_CENTS
: HANDLING_IN_CENTS;
public static final boolean DEBUGGING = true; Compile
public static final int BUFFSIZE; Time
static
{
if ( DEBUGGING )
{
BUFFSIZE = 256;
}
else
{
BUFFSIZE = 8096;
}
}
public static final int POSTAGE_IN_CENTS = 60; Load Time
public static final int HANDLING_IN_CENTS = 500;
public static final int BIGGER_IN_CENTS =
Math.max( POSTAGE_IN_CENTS, HANDLING_IN_CENTS );
public static final Random wheel = new Random(); Load Time
public static final int CARD = wheel.nextInt( 52 );

Object type casting:

The parent class reference can be used to hold child class instances.

C obj=new C();

P obj=new C();

From the polymorphism ,we can use like this.If the parent class reference used to hold child class
instance by using that reference we are allowed to call only the methods available in the parent
class.i.e by using that parent class reference we are not allowed to call child class specific
methods.

Example:

class Parent
{ void m1()
{ System.out.println(“parent m1”); }
void m2()
{ System.out.println(“parent m2”); }
}
class child extends Parent
{
52
void m1() { System.out.println(“child m1”); }
void m3()
{ System.out.println(“child m3”); }
}
public static void main(String ar[])
{
Child c1=new Child();
c1.m1(); // child m1
c1.m2() // parent m2
c1.m3() // child m3
Parent p1=new Child();
p1.m1() // child m1
p1.m2() //parent m2
p1.m3() // compile time error
}
}
Interface reference can be used to hold implemented classes objects.At that time by using that
reference we are allowed to call only the methods which are defined in that interface.

Runnable r=new Thread();


r.run(); // valid
r.start() ; // in valid
Runnable r=new Runnable() ; // in valid
Object creation for interface is not possible.
Thread t=new Thread () // valid
Object o=new Object () // valid

General Syntax of object typecasting:


A b=(C) d;
Here A interface or a class
b is the reference variable
C is the class
d is reference or object.

Rule1 for compilation:

The type of c must be same or derived type of “A” other wise violation leads to Compile time
error saying incompatible types .

Rule2 for compilation:

53
The type of ‘d’ must have some relation with ‘c’(either parent –child or child-parent )other wise
violation leads to compile time error saying incompatible types.

Examples:

1.String s=(String) (new Object()); //valid


2.String s=(Object)(new String(“abc”); // not valid
3.String s=(StringBuffer)(new Object()); // not valid
4.String s=(StringBuffer)(new String(“abc”)); // not valid
RunTime checking by the JVM:

The underlying object of ‘d’ must be same or derived type of ‘c’;

Examples:

1.Object o1=new String(“laxman”);

String s=(String)o1; // valid

String s=(Object)o1; // not valid

2.Base1 obj=new Der2();

Object obj2=(Base1)obj; // valid

Der2 obj3=(Der2)obj2; // valid

See the Sample codes:

For example If Base1 extends Object

Der1 ,Der2 extends the Base1

3.Base1 obj4=(Der2)obj3; // valid

4.Der1 obj5= (Der1) obj4; // not valid (class cast exception at run time)

5.Object o1=new Object ();

String s=(String)o1; // not valid (class cast exception at run time)

See the Sample codes:

Base1 , Base2 are extends the Object class

Der1 , Der2 extends the Base1 class, Der3 , Der4 extends the Base2 class.

1.Number n=(Integer)(new Byte(b)); // not valid


54
2.Throwable r=(Exception)(new Error()); // not valid

3.Throwable r=(Exception)(new Exception()); // valid

4.Number n=new Boolean(“true”); // not valid

5.Object o=(Base1)(new Der2()); // valid

6.Base2 o=(Der3)o; // not valid

6.Base1 o=(Der3)(new Der4()); // not valid

Example:

class Dog
{
}
class Beagle extends Dog
{
}
class Kennel
{
public static void main(String arg[])
{
Beagle b1=new Beagle();
Dog d1=new Dog();
Dog d2=b1;
Beagle b3=(Beagle)d2; // valid
Beagle b4=d2; // not vlaid
Beagle b2=(Beagle)d1; // valid
}
}
LOOP
What Is Basic Difference Between While Loop And Do-while Loop?

1. In While loop the condition is tested first and then the statements are executed if the condition
turns out to be true. In do while the statements are executed for the first time and then the
conditions are tested, if the condition turns out to be true then the statements are executed again.

2. A do while is used for a block of code that must be executed at least once. These situations
tend to be relatively rare, thus the simple while is more commonly used.

55
3. A do while loop runs at least once even though the the condition given is false while loop do
not run in case the condition given is false 4. In a while loop the condition is first tested and if it
returns true then it goes in the loop In a do-while loop the condition is tested at the last.

5. While loop is entry control loop where as do while is exit control loop.

6. Syntax:

while loop :

while (condition)

Statements;

do while loop :

Do

Statements;

}while(condition);

For-each Loop

Purpose : The basic for loop was extended in Java 5 to make iteration over arrays and
other collections more convenient. This newer for statement is called the enhanced for or
for-each (because it is called this in other programming languages). I've also heard it
called the for-in loop.

Use it in preference to the standard for loop if applicable (see last section below) because
it's much more readable.

Series of values. The for-each loop is used to access each successive value in a collection
of values.

Arrays and Collections. It's commonly used to iterate over an array or a Collections
class (eg, ArrayList).

Iterable<E>. It can also iterate over anything that implements the Iterable<E> interface
(must define iterator() method). Many of the Collections classes (eg, ArrayList)

56
implement Iterable<E>, which makes the for-each loop very useful. You can also
implement Iterable<E> for your own data structures.

General Form

The for-each and equivalent for statements have these forms. The two basic equivalent forms are
given, depending one whether it is an array or an Iterable that is being traversed. In both cases an
extra variable is required, an index for the array and an iterator for the collection.

For-each loop Equivalent for loop

for (type var : arr) { for (int i = 0; i < arr.length; i++) {

body-of-loop type var = arr[i];

} body-of-loop

for (type var : coll) { for (Iterator<type> iter = coll.iterator();


iter.hasNext(); ) {
body-of-loop
type var = iter.next();
}
body-of-loop

Example - Adding all elements of an array

Here is a loop written as both a for-each loop and a basic for loop.

double[] ar = {1.2, 3.0, 0.8};

int sum = 0;

for (double d : ar) { // d gets successively each value in ar.

sum += d;

And here is the same loop using the basic for. It requires an extra iteration variable.

double[] ar = {1.2, 3.0, 0.8};

57
int sum = 0;

for (int i = 0; i < ar.length; i++) { // i indexes each element successively.

sum += ar[i];

Where the for-each is appropriate

Altho the enhanced for loop can make code much clearer, it can't be used in some common
situations.

• Only access. Elements can not be assigned to, eg, not to increment each element in a
collection.

• Only single structure. It's not possible to traverse two structures at once, eg, to compare
two arrays.

• Only single element. Use only for single element access, eg, not to compare successive
elements.

• Only forward. It's possible to iterate only forward by single steps.

• At least Java 5. Don't use it if you need compatibility with versions before Java 5.

Advantages of for-each Loop:

* Less error prone code

* Improved readability

* Less number of variables to clean up

Limitations:

* Cannot be used where the collection is to be altered while traversing/looping through

* My not be suitable while looping through multiple collections in parallel.

58
OPERATORS

1) Arithmetic Operators

+ Additive operator (also used for String concatenation)


- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

2) Unary Operators

+ Unary plus operator; indicates positive value (numbers are


positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical compliment operator; inverts the value of a Boolean

3) Equality and Relational Operators

== Equal to
= Not equal to
> Greater than
>= Greater than or equal to
< Less than
= Less than or equal to

4) Conditional Operators

&& Conditional-AND
|| Conditional-OR
? : Ternary (shorthand for if-then-else statement)

5) Bitwise and Bit Shift Operators

~ Unary bitwise complement


<< Signed left shift
>> Signed right shift
59
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

6) Type Comparison Operator

instanceof Compares an object to a specified type

7) Simple Assignment Operator

= Simple assignment operator

1. The Arithmetic Operators:

Operator Description (A=10, B=20) Example


+ Addition - Adds values on either side of A + B will give 30
the operator
- Subtraction - Subtracts right hand A - B will give -10
operand from left hand operand
* Multiplication - Multiplies values on A * B will give 200
either side of the operator
/ Division - Divides left hand operand by B / A will give 2
right hand operand
% Modulus - Divides left hand operand by B % A will give 0
right hand operand and returns remainder
++ Increment - Increase the value of B++ gives 21
operand by 1
-- Decrement - Decrease the value of B-- gives 19
operand by 1

Example:
public class Arithmetic {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
byte a1=10;
byte b1=20;
byte c1;
c1=(byte)(a1+b1);
System.out.println("c1=(byte)(a1+b1) = "+c1);
60
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}

Output:
c1 = 30
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27

Ex:
byte a=10;
byte b=20;
byte c=a+b;
System.out.println (c); //compile time error

if we can perform any arithmetic operation between any 2 variables a and b the result is
always max (int, type a, type b )
byte + short=int
char + char=int
int + char=int
int + long=long
doubles + byte=double

int a=10+’a’ => 10+97=107


double b=10+12.5 => 10.0+12.5=>22.5;
For representing infinity, there are no constant ; define in the integer class. Hence 0/0
results is sum time exception saying arithmetic exception
System.out.println(10/0); //Runtime Exception by zero .

61
System.out.println(10.0/0); //infinity
System.out.println(10.0f/0); //infinity
But in the float and double classes for representing infinity constants are defined.
System.out.println (Float. POSITIVE_INFINITY); // infinity
System.out.println( Float NEGATIVE_ INFINITY); //-infinity

final float postive_ infinity ,


final float negative _ infinity are the constants contain in float class.
0/0 is undefined in the Integer class for representing undefined results there is no constant
available . Hence 0/0 results arithmetic exception.
0/0 →arithematic exception but in float and double classes for representing
undefined values there is a commands available . public static final float NaN.
NaN→not a number and public static final double NaN

Example:
System.out.println(0.0 / 0) → NaN
System.out.println(Math.sqrt(4)); → 2.0
System.out.println(Math. Sqrt(-4)); → NaN.
System.out.println(10/0)→ Arithmatic exception
System.out.println(10.0 / 0)→ infinity
System.out.println(-10.0 /0→ - infinitz
System.out.println(0/0) → Arithematic Exception.
System.out.println(0.0/0 → NaN
System.out.println(-10/0) → arithmatic exception
System.out.println(-10.0/0)→ -infinity,
System.out.println(-0.0/0)→ NaN.
Float. POSITIVE_INFINITY = = Float. POSITIVE_INFINITY; // true
Float . POSITIVE_INFINITY = =Double. POSITIVE_INFINITY. // true
Float . NaN = =Float. NaN.
Float. NaN >double. NaN }false
Float. NaN !=Float. NaN →true.
• if one are comparing NaN with any other , including NaN itself, the result is always false,
except for not equal(!=)operator.

Arithmetic exception:
1. runtime exception (unchecked)
2. only in the cone of integer arithmetic.
3. / and % only there two operators result in Arithmetic exception.

String concatenation operation:-


‘+’ is the only operator in java which in overloaded. We can one for arithmetic addition and for

string concatenation.

String a=”java”.
int b=30;

62
int c=20;
int d=10;
System.out.println (a+b+c+d);→java302010;
System.out.println(b+a+c+d);→ 30java2010
System.out.println(b+c+d+a); →60java
System.out.println(b+c+a+d);→50java10.

* If at least one operand is of string type then + acts as string concatenation operator other wise +
acts as arithematic operator.

2. The Relational Operators:

Operator Description (A=10, B=20) Example


== Checks if the values of two operands are equal or not, if yes (A == B) is not true.
then condition becomes true.
!= Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

Example
public class Relational {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
63
3. The Bitwise Operators:

Java defines several bitwise operators which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example


& Binary AND Operator copies a bit to the (A & B) will give 12 which is 0000 1100
result if it exists in both operands.
| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011 1101
exists in eather operand.
^ Binary XOR Operator copies the bit if it (A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.
~ Binary Ones Complement Operator is (~A ) will give -60 which is 1100 0011
unary and has the efect of 'flipping' bits.
<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111 0000
operands value is moved left by the
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15 which is 1111
operands value is moved right by the
number of bits specified by the right
operand.
>>> Shift right zero fill operator. The left A >>>2 will give 15 which is 0000 1111
operands value is moved right by the
number of bits specified by the right
operand and shifted values are filled up
with zeros.

1- The AND operator : (&)


x y x&y
-----------------------------
0 0 0
0 1 0
1 0 0
1 1 1
Example on & operator
64
Code:
byte x = 50;
byte y = 51;
byte result = (byte) (x&y);
System.out.println("Result of x&y= : " + result );
The result equal = 50
00110010
00110011
-------------
00110010

2- The OR operator : (|)


x y x|y
-----------------------------
0 0 0
0 1 1
1 0 1
1 1 1

Example on | operator
Code:

byte x = 50;
byte y = 51;
byte result = (byte) (x|y);
System.out.println("Result of x|y= : " + result );

The result equal = 51

00110010
00110011
-------------
00110011

3- The XOR operator : (^)

x y x^y
-----------------------------
0 0 0
0 1 1
1 0 1
1 1 0

byte x = 50;
byte y = 51;
byte result = (byte) (x^y);

65
System.out.println("Result of x^y= : " + result );

The result equal = 1

00110010
00110011
-------------
00000001

4- The Inversion Operator: (~)


Invert each bit in the byte .
Example :
Code:
~00110010 = 11001101

5- Boolean Inversion Operator (!)


invert the value of Boolean

Left Shift Operator:


a << b shift the bits of a ,b times to the left hand side.
Ex: 8 << 33 then 8 << 33 % 32 = 8 << 1 // result=16
Ex: 8 << - 31 then 8 << -31+32 = 8 << 1 // result= 16

Right Shift Operator:


a>>b shift the bits of a ,b times to the right hand side by filling the left hand side bits with sign
bit.
8 >> 1 --> 0000 …….100 = 4.
Filled with sign bit zero.
a >> b =a/2 power b for 8 >> 1 =8/2 power 1 =8/2=4.
If b < 31 then b=b+32
If b >31 then b= b% 32.
- 8 >> 1 ---> -8/2 power 1 = -8/2= -4.

Unsigned Right Shift Operator:

66
a>>> b , shift the bits of a, b times to the right hand side. By filling left most bits with zero
always.If a is +ve ,then there is no difference between right shift and unsigned right shift
operator.Except shift distance zero ,the result of unsigned right shift operator is always positive.
I few are applying shift operator between a and b the result type is always max(int type of a)

Case1: byte b=8 >>1; // valid


Case2: int a=8;
byte b=a >> 1; // invalid
Case3: final int a=8;
byte b=a>>1; // valid
Case 4:long c=1;
byte b=8>>c; //invalid (as per max(int,type of a)

In a << ,>> ,>>> b ,If a and b ,both are compile time constants then the compiler won’t go for
formula for the result type.If at least one in the variable ,either a or b then the compiler checks
the type of the result which is max(int,type of a) , the type b never participated in the result .

4) Logical Operators:

Operator Description Example


Called Logical AND operator. If both the
&& operands are non zero then then condition (A && B) is false.
becomes true.
Called Logical OR Operator. If any of the
|| two operands are non zero then then (A || B) is true.
condition becomes true.
Called Logical NOT Operator. Use to
reverses the logical state of its operand. If
! !(A && B) is true.
a condition is true then Logical NOT
operator will make false.

A B A|B A&B A^B !A


67
x || y x && y
false false false false false true
true false true false true false
false true true false true true
true true true true false false

1) | the OR operator
2) & the AND operator
3) ^ the XOR operator
4) ! the NOT operator
5) || the short-circuit OR operator
6) && the short-circuit AND operator
7) == the EQUAL TO operator
8) != the NOT EQUAL TO operator

What is the difference between & and && operators?


These are Bitwise and Logical Operators in Java
1. &= bitwise AND
2. &&= logical AND (Shourt-circuit)

1. These operators & are used with boolean operands and return a boolean value (true or false).
These operators evaluate both the operands of an expression

An Ex:-
boolean b1= false;
boolean b2 = true;
b1 & b2= false;

2.The Logical operators && are used when we want to form compound condition by combining
two or more relations.
An example is:
a>b && X=10;
a=true;
b=true;
a&&b=true;

Ex if (age>55 && salary<1000);

The & operators evaluate both sides of the operators and then give a boolean
value and && operator first evaluate the left hand side expression of the operator. If they get
their final value in that They do not the right hand side expression of the operator.
1) & and | which can also be applied to integral operands for bitwise operations the
conditional operators && and || can only be applied to boolean operands. Their
evaluation results in a boolean value.

68
2) unlike their logical counterparts there are no compound assignment operators for the
conditional operators.
3) Conditional operators && and || their evaluation is short-circuited.

Why do we need to use shift operator in Java?


Answer: Using shift operators in Java we can:

Make faster integer division/multiplication operations:

4839534 * 4
can be done like this:
4839534 << 2

or

543894 / 2
can be done like this:
543894 >> 1

1) Shift operations much more faster than multiplication for most of processors.
2) Reassembling byte streams to int values
3) For accelerating operations with graphics since Red, Green and Blue colors coded by
separate bytes.
4) Packing small numbers into one single long...

The Assignment Operators:

Operator Description Example


Simple assignment operator, Assigns
= values from right side operands to C = A + B will assigne value of A + B into C
left side operand
Add AND assignment operator, It
adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to left
operand
Subtract AND assignment operator,
It subtracts right operand from the
-= C -= A is equivalent to C = C - A
left operand and assign the result to
left operand
*= Multiply AND assignment operator, C *= A is equivalent to C = C * A
It multiplies right operand with the
left operand and assign the result to
69
left operand
Divide AND assignment operator, It
divides left operand with the right
/= C /= A is equivalent to C = C / A
operand and assign the result to left
operand
Modulus AND assignment operator,
%= It takes modulus using two operands C %= A is equivalent to C = C % A
and assign the result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
Right shift AND assignment
>>= C >>= 2 is same as C = C >> 2
operator
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
bitwise exclusive OR and
^= C ^= 2 is same as C = C ^ 2
assignment operator
bitwise inclusive OR and assignment
|= C |= 2 is same as C = C | 2
operator

Example:
class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
70
c <<= 2 ;
System.out.println("c <<= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= a = " + c );
c &= a ;
System.out.println("c &= 2 = " + c );
c ^= a ;
System.out.println("c ^= a = " + c );
c |= a ;
System.out.println("c |= a = " + c );
}
}

Output
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a = 0
c ^= a = 10
c |= a = 10

instanceOf Operator:

This operator is used only for object reference variables. The operator checks whether the object
is of a particular type(class type or interface type). instanceOf operator is wriiten as:

( Object reference variable ) instanceOf (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side then the result will be true. Following is the example:

String name = = 'James';


boolean result = s instanceOf String;
// This will return true since name is type of String

71
This operator will still return true if the object being compared is the assignment compatible with
the type on the right. example:
class Vehicle {}

public class Car extends Vehicle {


public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}

Output:
true

Following are the key points to be remembered while using instanceof operator

1. Instanceof operator is used to restore full functionality of an object.


2. While programming many times heterogeneous collection are used and then to invoke
full functionality of an object casting is required then to check the type of instance,
“instanceof” operator can be used.
3. “instanceof” operator loads class in jvm making it a heavy operation so it is desirable to
avoid it, If you can use overridden method instead.

See following code sample

if (mobj instanceof Dog)


{ return (Dog)mobject.run(); }

else if (mobj instanceof Cat)


{ return (Cat)mobject.walk(); }

else { System.out.println("Unknown animal..."); }

Here “instanceof” operator should be used but if both Dog and cat class have method eat then
using “instanceof” operator is useless.

Misc Operators(Conditional Operator ( ? : ))

Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as :
variable x = (expression) ? value if true : value if false
public class Test {
public static void main(String args[]){
int a , b;

72
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}}

Output: Value of b is : 30
Value of b is : 20

Precedence of Java Operators:

Category Operator Associativity


Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

==, .equals(), compareTo(), and compare()

Equality comparison: One way for primitives, Four ways for objects

73
Comparison Primitives Objects
a == b, a != b Equal Compares references, not values. The use of == with object
values references is generally limited to the following:
• Comparing to see if a reference is null.
• Comparing two enum values. This works because there is
only one object for each enum constant.
• You want to know if two references are to the same
object
a.equals(b) N/A Compares values for equality. Because this method is defined in
the Object class, from which all other classes are derived, it's
automatically defined for every class. However, it doesn't
perform an intelligent comparison for most classes unless the
class overrides it. It has been defined in a meaningful way for
most Java core classes. If it's not defined for a (user) class, it
behaves the same as ==.
It turns out that defining equals() isn't trivial; in fact it's
moderately hard to get it right, especially in the case of
subclasses. The best treatment of the issues is in Horstmann's
Core Java Vol 1. [TODO: Add explanation and example]
a.compareTo(b) N/A Comparable interface. Compares values and returns an int
which tells if the values compare less than, equal, or greater than.
If your class objects have a natural order, implement the
Comparable<T> interface and define this method. All Java
classes that have a natural ordering implement this (String,
Double, BigInteger, ...).
compare(a, b) N/A Comparator interface. Compares values of two objects. This is
implemented as part of the Comparator<T> interface, and the
typical use is to define one or more small utility classes that
implement this, to pass to methods such as sort() or for use by
sorting data structures such as TreeMap and TreeSet. You might
want to create a Comparator object for the following.
• Multiple comparisions. To provide several different
ways to sort somthing. For example, you might want to
sort a Person class by name, ID, age, height, ... You
would define a Comparator for each of these to pass to
the sort() method.
• System class. To provide comparison methods for classes
that you have no control over. For example, you could
define a Comparator for Strings that compared them by
length.
• Strategy pattern. To implement a Strategey pattern,
which is a situation where you want to represent an
algorithm as an object that you can pass as a parameter,
save in a data structure, etc.
If your class objects have one natural sorting order, you may not
need this.
74
Comparing Object references with the == and != Operators
The two operators that can be used with object references are comparing for equality (==) and
inequality (!=). These operators compare two values to see if they refer to the same object.
Although this comparison is very fast, it is often not what you want.
Usually you want to know if the objects have the same value, and not whether two objects are a
reference to the same object. For example,
if (name == "Mickey Mouse") // Legal, but ALMOST SURELY WRONG
This is true only if name is a reference to the same object that "Mickey Mouse" refers to. This
will be false if the String in name was read from input or computed (by putting strings together
or taking the substring), even though name really does have exactly those characters in it.
Many classes (eg, String) define the equals() method to compare the values of objects.

Comparing Object values with the equals() Method


Use the equals() method to compare object values. The equals() method returns a boolean value.
The previous example can be fixed by writing:
if (name.equals("Mickey Mouse")) // Compares values, not refererences.
Because the equals() method makes a == test first, it can be fairly fast when the objects are
identical. It only compares the values if the two references are not identical.

Other comparisons - Comparable<T> interface


The equals method and == and != operators test for equality/inequality, but do not provide a way
to test for relative values. Some classes (eg, String and other classes with a natural ordering)
implement the Comparable<T> interface, which defines a compareTo method. You will want to
implement Comparable<T> in your class if you want to use it with Collections.sort() or
Arrays.sort() methods.

Defining a Comparator object


As described in the table above on compare(), you can create Comparators to sort any arbitrary
way for any class. For example, the String class defines the CASE_INSENSITIVE_ORDER
comparator.

If you override equals, you should also override hashCode()


Overriding hashCode(). The hashCode() method of a class is used for hashing in library data
structures such as HashSet and HashMap. If you override equals(), you should override
hashCode() or your class will not work correctly in these (and some other) data structures.
Shouldn't .equals and .compareTo produce same result?
The general advice is that if a.equals(b) is true, then a.compareTo(b) == 0 should also be true.
Curiously, BigDecimal violates this. Look at the Java API documentation for an explanation of
the difference. This seems wrong, although their implementation has some plausibiliby.
Other comparison methods
String has the specialized equalsIgnoreCase() and compareToIgnoreCase(). String also supplies
the constant String.CASE_INSENSITIVE_ORDER Comparator.
The === operator (Doesn't exist - yet?)

75
Comparing objects is somewhat awkward, so a === operator has been proposed. One proposal is
that
a === b would be the same as ((a == b) || ((a != null) && a.equals(b)))
Common Errors
Using == instead of equals() with Objects
When you want to compare objects, you need to know whether you should use == to see if they
are the same object, or equals() to see if they may be a different object, but have the same value.
This kind of error can be very hard to find.

Classes
Inner class
76
Inner class is a class defined inside other class and act like a member of the enclosing class.

Types of classes

1. Top Level class


2. Static Member class
3. Non-Static inner class or Member class
4. Local Class
5. Anonymous class

1. Top Level class

public class Foo {


public static void main(String[] args) {

}
}

2. Static Member class

public class Nest {

private static String var = "foo";

private static class Nested {


public Nested() {
var = "bar";
}
}
}

3. Non-Static inner class or Member class

public class Nest {


private String var = "foo";
private class Nested {
public Nested() {
var = "bar";
}
}
}

4. Local Class

public class Enclosing {

77
public Enclosing() {
class Local {
public Local() {
System.out.println( "In local class...");
}
}
new Local();
}
}

5. Anonymous Class

An anonymous class is a local class without a name. These are local classes, which are automatically
declared, and instantiated in the middle of an expression. They can specify arguments to the constructor
of the superclass, but cannot otherwise have a constructor. They can implement only one interface or
extend a class. Anonymous class cannot define any static fields, methods, or classes, except for static
final constants. In addition, like local classes, anonymous classes cannot be public, private, protected, or
static.

Syntax for Anonymous Classes

new class-name ( [ argument-list ] ) { class-body }

or:

new interface-name () { class-body }

Example

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class SimpleEvent {

public static void main(String[] args) {


JButton close = new JButton("Close");

close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
} });
78
JFrame f = new JFrame();
f.add(close);
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

Different types of anonymous classes

1) Plain old anonymous class type one–

e.g.

class superClass{
void doSomething() {
System.out.println(“Doing something in the Super class”);
}
}
class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(“Doing something in the Anonymous class”);
}
};
Here anon is the reference which is of type superClass which is the class extended by the anonymous
class i.e. superclass of the anonymous class. The method doSomething() is the super class method
overridden by the anonymous class.

2) Plain old anonymous class type two –

interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class which is the
implementer of the interface Eatable. The anonymous implementer class of the interface Eatable
implements its method prepareSweets() inside it.
79
3) Argument defined anonymous class – e.g.

interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println("It has four wheels");
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this anonymous class
is the implementer of the interface Vehicle. The method of class Car getTheBeautifilCar() expects the
argument as an object of type Vehicle. So first, we create an object of Car referenced by the variable ‘c’.
On this object of Car we call the method getTheBeautifilCar() and in the argument we create an
anonymous class in place which is the implementer of interface Vehicle hence of type Vehicle.

Benefits of Anonymous Classes

1. The key benefit of an anonymous class is encapsulation (or clutter reduction). An


anonymous class is, in a sense, the ultimate in private object oriented encapsulation. It is defined
exactly where it is needed, it can never be used anywhere else, and it has totally local scope.

2. Anonymous classes provide a very clean syntax for implementing event listeners in GUI
programming, and are handy for implementing method parameters and return objects “on the
fly”.

3. Essentially, anonymous classes relieve the programmer from defining (and keeping track
of) large numbers of special purpose classes. They are used once, defined right where the action
is, and never heard from again.

4. One final key benefit of anonymous classes is that they have access to all data and
methods of their containing classes, including private members; meaning that for small highly
localized tasks, they may require less initialization.

The advantages of Inner classes


80
The embedding of inner class into the outer class in the case when the inner class is to be
used only by one class i.e. the outer class makes the package more streamlined. Nesting the inner
class code where it is used (inside the outer class) makes the code more readable and
maintainable.

The inner class shares a special relationship with the outer class i.e. the inner class has
access to all members of the outer class and still have its own type is the main advantages of
Inner class. Advantage of inner class is that they can be hidden from the other classes in the same
package and still have the access to all the members (private also) of the enclosing class. So the
outer class members, which are going to be used by the inner class, can be made private and the
inner class members can be hidden from the classes in the same package. This increases the level
of encapsulation.

If a class A is written requires another class B for its own use, there are two ways to do
this. One way is to write a separate class B or to write an inner class B inside class A. Advantage
of writing the inner class B in the class A is you can avoid having a separate class. Inner classes
are best used in the event handling mechanism and to implement the helper classes. The
advantage of using inner class for event handling mechanism is that the use of if/else to select the
component to be handled can be avoided. If inner classes are used each component gets its own
event handler and each event handler implicitly knows the component it is working for. e.g.
Button btn1 = new Button("Submit"); Btn.addActionListener(new ActionListener(){/br>

Public void actionPerformed(ActionEvent ae){ submitClicked(); }

} );

The advantage of using static nested class is that to instantiate a static nested class you need not
create an instance of the enclosing class which reduces the number of objects the application
creates at runtime.

Disadvantages of using inner classes

1. Using inner class increases the total number of classes being used by the application. For
all the classes created by JVM and loaded in the memory, jvm has to perform some tasks
like creating the object of type class. Jvm may have to perform some routine tasks for
these extra classes created which may result slower performance if the application is
using more number of inner classes.

2. Inner classes get limited support of ide/tools as compared to the top level classes, so
working with the inner classes is sometimes annoying for the developer.

Nested class

a) Classes that are declared inside the body of a class are called "nested classes".

b) The following are the main reasons behind the concept of nested classes in Java:
81
i) Grouping of logical classes

When designing a class, we always try to create well-focused classes - with a


unique behavior and purpose. Let us imagine we have designed classes A and B on
the same principle. Later we found, class B can only be used by class A. In such
cases, we can simply put class B inside class A.

ii) Encapsulation

By writing nested classes, we have hidden them from the world and made them
available only to their enclosing class.

iii) Maintainability and re-usability of code

Encapsulation brings the beauty of maintainability of code. In our earlier


example, we can write another class B which is visible t o the entire world. This has
nothing to do with the one already present inside class A.

c) Nested class is of 2 kinds:

i) Inner class

ii) Static nested class

d) Inner class is of 3 types:

i) Inner class

ii) Method-local inner class

iii) Anonymous inner class

e) Nested class behaves just like any other member of its enclosing (outer) class.

f) It has access to all the members of its enclosing class.

Inner Class

o We define the term "inner class" to the nested class that is:

 declared inside the body of another class.

 not declared inside a method of another class.

82
 not a static nested class.

 not an anonymous inner class.

o An example: class Outer{

class Inner{

1. When we compile the above code we get 2 class files:

a. Outer.class

b. Outer$Inner.class

2. Notice that inner class is tied to its outer class though it is still a separate class.

3. An inner class cannot have any kind of static code including the public static void
main(String[] args).

4. Only classes with "public static void main(String[] args)" can be called using "java"
command.

5. In our earlier example, Inner class didn't have a static main method. So, we can't call java
Outer$Inner!

6. The inner class is just like any other member of its enclosing class.

7. It has access to all of its enclosing class' members including private.

Instantiating an Inner Class

• Since inner class can't stand on its own, we need an instance of its outer class to tie it.

• There are 2 ways to instantiate an instance of inner class:

 From within its outer class

 From outside its outer class


83
class Outer{

private String s = "Outer string"; //Outer instance variable

Inner i1 = new Inner();

void getS(){

System.out.println(s);

void getInnerS(){

System.out.println(i1.s);

class Inner{

private String s = "Inner string"; //Inner instance variable, uninitialized

void getS(){

System.out.println(s);

void getOuterS(){

System.out.println(Outer.this.s);

public static void main(String[] args){

Outer o = new Outer();

Outer.Inner oi = o.new Inner();//can also be new Outer().new Inner();

o.getS();

oi.getS();

o.getInnerS();

84
oi.getOuterS();

Output:

Outer string

Inner string

Inner string

Outer string

Another excellent example:

class InnerTest{

public static void main(String[] args){

Outer o = new Outer();

Outer.Inner i = o.new Inner();//one way

i.seeOuter();

i = new Outer().new Inner();//another way

i.seeOuter();

class Outer{

private String s = "outer s";

void makeAndSeeInner(){

System.out.println(this);//refers to Outer.this

Inner i = new Inner();//No need of Outer.this explicitly, because, Outer.this already


exists here.

85
i.seeOuter();

void seeInner(){

System.out.println(s);//How to see Inner s here? You can't, because Inner.this not


present.

strictfp class Inner{

private String s = "inner s";

void seeOuter(){

System.out.println(this);

System.out.println(Outer.this.s);//Need to mention Outer because this refers to


Inner.this here.

System.out.println(s);//Or, this.s

} }

abstract class AbInner{

private String s = "abstract inner s";

void seeOuter(){

System.out.println(this);//this refers to the subclass not the abstract class.

System.out.println(Outer.this.s);

System.out.println(s);

abstract void abMethod();

class Some extends AbInner implements Runnable, Animal{//can extend and


implement

public void run(){}

86
void abMethod(){

System.out.println(this);

System.out.println(super.s);

public static void main(String[] args){

Inner i = new Outer().new Inner();

//Inner i = new Inner();//can't exist w/o outer class instance

i.seeOuter();

Outer o = new Outer();

o.makeAndSeeInner();

o.seeInner();

//new Outer().makeAndSeeInner();

Some so = new Outer().new Some();

so.seeOuter();

so.abMethod();

interface Animal{

Run it and check your output. How to run? Look into the code and you'll definitely understand
how to do that. :)

Method-Local Inner Classes

87
• A method-local inner class is defined within a method of the enclosing class.

• For the inner class to be used, you must instantiate it, and that instantiation must happen
within the same method, but after the class definition code.

• A method-local inner class cannot use variables declared within the method (including
parameters) unless those variables are marked final.

• The only modifiers you can apply to a method-local inner class are abstract and final.
(Never both at the same time, though.)

Anonymous Inner Classes

1. Inner classes that are declared without a name are called anonymous inner classes.

2. Anonymous inner classes have no name, and their type must be either a subclass of
the named type or an implementer of the named interface.

3. An anonymous inner class is always created as part of a statement; don't forget to


close the statement after the class definition with a curly brace. This is a rare case in
Java, a curly brace followed by a semicolon.

4. Because of polymorphism, the only methods you can call on an anonymous inner
class reference are those defined in the reference variable class (or interface), even
though the anonymous class is really a subclass or implementer of the reference
variable type.

5. An anonymous inner class can extend one subclass or implement one interface,
Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot
do both. In other words, it cannot both extend a class and implement an interface, nor
can it implement more than one interface.

6. An argument-local inner class is declared, defined, and automatically instantiated as


part of a method invocation. The key to remember is that the class is being defined
within a method argument, so the syntax will end the class definition with a curly
brace, followed by a closing parenthesis to end the method call, followed by a
semicolon to end the statement: });

We are allowed to declare inner classes with out name ,such type of inner classes are known as
anonymous inner classes.

• Anonymous inner class that extends a class

88
• Anonymous inner class that implements an interface

• Anonymous inner class declared in method arguments.

1.Anonymous inner class that extends a class:

Anonymous inner class Example code:

class Popcorn

public void eat()

System.out.println(“so sweet”);

class Sample

public static void main(String arg[])

Popcorn p=new Popcorn() // no semicolon (;) here

public void eat()

System.out.println(“so spicy”);

}; // with out semicolon (;) leads compile time error

p.eat(); // so spicy

}
89
In the Anonymous inner classes,we are allowed to define new methods but we are not
allowed to access those new methods by using parent class reference .these methods just
for internal use only.

Example code:

class Sample

public static void main(String arg[])

Thread t=new Thread()

public void run()

System.out.println(“child thread job”);

};

t.start();

System.out.println(“main thread job”);

2. Anonymous inner class that implements an interface :

with out Anonymous inner class code using thread :

class MyRunnable implements Runnable

public void run()


90
{

System.out.println(“run”);

class Test

public static void main(String ar[])

MyRunnable m=new MyRunnable();

Thread t=new Thread(m);

t.start();

}}

with Anonymous inner class using thread:

class Test

{ public static void main(String arg[])

Runable r=new Runnable()

public void run()

System.out.println(“run”);

};

Thread t=new Thread(r);

t.start();

91
}

• A class can extends only one class at a time ,of course Anonymous inner class also can
extend only one class.

• A class can implements any number of interfaces but anonymous inner class can can
implement only one interface at a time.

• A class can extend a class and implement an interface at atime ,but anonymous inner
class can extend a class or implement an interface ,but not both at a time.

3. Anonymous inner class declared in method arguments:

Anonymous inner class example:

class Sample

public static void main(String arg[])

new Thread( new Runnable()

public void run()

System.out.println(“run”);

});.start();

or

If you write like this in above Thread t= new Thread( new Runnable(){……}

t.start();

• We can declare anonymous inner class either in static or non static methods .

92
• If we declare anonymous inner class in the static method the static variables of outer class
can be accessed directly from inner class.

• If we are declaring anonymous inner class inside instance method ,we can access both
instance and static variables of outer class directly from the inner class.

• From anonymous inner class we are not allowed to access the local variables of the
method unless it is marked as final.

Static Nested Classes

• Nested classes that are declared "static" are called static nested classes.

• Static nested classes are inner classes marked with the static modifier.

• A static nested class is not an inner class, it's a top-level nested class.

• Because the nested class is static, it does not share any special relationship with
an instance of the outer class. In fact, you don't need an instance of the outer class
to instantiate a static nested class.

• Instantiating a static nested class requires using both the outer and nested class
names as follows:

BigOuter.Nested n = new BigOuter.Nested();

• A static nested class cannot access non-static members of the outer class, since it
does not have an implicit reference to any outer instance (in other words, the
nested class instance does not get an outer this reference).

• An example:

class StaticOuter{

String a = "StaticOuter string";

static String b = "StaticOuter static string";

void seeStaticInner(){

//System.out.println(nonstatic);//cannot find symbol

//System.out.println(StaticInner.nonstatic);//nonstatic is not static to access like this!


93
System.out.println(new StaticInner().nonstatic);//OK

System.out.println(StaticInner.s);//OK, s is static

public static void main(String[] args){

//System.out.println(s);//Doesn't compiles without writing the exact location of s

System.out.println(StaticInner.s);

StaticOuter so = new StaticOuter();

so.seeStaticInner();

static class StaticInner{

String nonstatic = "StaticInner nonstatic string";

static String s = "StaticInner static string";

public static void main(String... args){

//System.out.println(nonstatic);//cannot be referenced from a static context

System.out.println(s);

System.out.println(b);//OK, b is a static string. But not 'a' which is non-static!

class SomeOther{

public static void main(String[] args){

System.out.println(StaticOuter.StaticInner.s);//Write the exact location of s

StaticOuter.StaticInner si = new StaticOuter.StaticInner();//To access nonstatic


members we need an object or 'this'

System.out.println(si.nonstatic);//No 'this' exists in static context!

94
System.out.println(si.s);//'si' is simply a fake! To the end it will be
StaticOuter.StaticInner!

Output: $java StaticOuter

StaticInner static string

StaticInner nonstatic string

StaticInner static string

$java StaticOuter$StaticInner

StaticInner static string

StaticOuter static string

$java SomeOther

StaticInner static string

StaticInner nonstatic string

StaticInner static string

95
Constructor
Passing arguments and properties from command line

The syntax to pass arguments from command line is as follows,

java <classname> <argument1> <argument2> <argument3> ........

Example shows the usage of command line arguments.

public class ArithmeticOperationTest


{
public static void main(String[] arguments) {
if(arguments.length > 0)
{
float numberOne = getNumber(arguments[0]);
float numberTwo = getNumber(arguments[1]);
char operator = getOperator(arguments[2]);
float result = 0.00f;
if (operator == '+')
{
result = numberOne + numberTwo;
}else if (operator == '-'){
result = numberOne - numberTwo;

96
}else if (operator == '/'){
result = numberOne / numberTwo;
}
System.out.println("result of " + numberOne + " " + operator
+ " " + numberTwo + " is " + result);
}
}
static float getNumber(String number){
float retNumber = 0.0f;
retNumber = Float.parseFloat(number.trim());
return retNumber; }
static char getOperator(String argument){
char retOperator = ' ';
retOperator = argument.trim().charAt(0);
return retOperator;
}
}
To run the above program issue the following at command line,

java ArithmeticOperationTest 10 5 /

The output is,

result of 10.0 / 5.0 is 2.0

Now, let us see how to pass properties from command line.

Passing properties from command line

The getProperty(<property-name>) method in System class is used to get the value of a property
by specifying the property name as key.

Example: public class ScoreCardPropertiesTest {


public static void main(String[] args) {
String subject = System.getProperty("subject");
System.out.println("subject is " +subject);
String score = System.getProperty("score");
System.out.println("score is " +score);
String grade = System.getProperty("grade");
System.out.println("grade is " +grade);
}}
We pass properties subject, score and grade to the above ScoreCardPropertiesTest class as
follows,
97
java -Dsubject=Maths -Dscore=95 -Dgrade=A ScoreCardPropertiesTest

The output is,

subject is Maths
score is 95
grade is A
Pass-by-value

Pass-by-value means that when you call a method, a copy of the value of each actual
parameter is passed to the method. You can change that copy inside the method, but this will
have no effect on the actual parameter.

The actual parameter (or argument expression) is fully evaluated and the resulting value is
copied into a location being used to hold the formal parameter's value during method/function
execution. That location is typically a chunk of memory on the runtime stack for the application
(which is how Java handles it), but other languages could choose parameter storage differently.

• In this method value of the variable is passed. Changes made to formal will not affect the
actual parameters.

• Different memory locations will be created for both variables.

Example: class Student {

public static void main (String [] args) {

int score = 75;

Student st = new Student();

st.modifyStudent(score);

System.out.println("The original student score: " + score);

void modifyStudent(int i){

i = i+10;

System.out.println("The modified student score: " + i);

98
}

The output:

The modifed student score: 85

The original student score: 75

Pass By Reference:

In Pass by reference address of the variable is passed to a function. Whatever changes


made to the formal parameter will affect to the actual parameters.

The formal parameter merely acts as an alias for the actual parameter. Anytime the
method/function uses the formal parameter (for reading or writing), it is actually using the actual
parameter.

• Same memory location is used for both variables.(Formal and Actual)-

• it is useful when you required to return more then 1 values

public class TestPassByReference {


public static void main(String[] args) {
// declare and initialize variables and objects
int i = 25;
String s = "Java is fun!";
StringBuffer sb = new StringBuffer("Hello, world");
// print variable i and objects s and sb
System.out.println(i); // print it (1)
System.out.println(s); // print it (2)
System.out.println(sb); // print it (3)
// attempt to change i, s, and sb using methods
iMethod(i);
sMethod(s);
sbMethod(sb);
// print variable i and objects s and sb (again)
System.out.println(i); // print it (7)
System.out.println(s); // print it (8)
System.out.println(sb); // print it (9)
}
public static void iMethod(int iTest) {
iTest = 9; // change it
System.out.println(iTest); // print it (4)
return;
99
}
public static void sMethod(String sTest) {
sTest = sTest.substring(8, 11); // change it
System.out.println(sTest); // print it (5)
return;}
public static void sbMethod(StringBuffer sbTest) {
sbTest = sbTest.insert(7, "Java "); // change it
System.out.println(sbTest); // print it (6)
return;
}}
Output of the program:
25
Java is fun!
Hello, world
9
fun
Hello, Java world
25
Java is fun!
Hello, Java world
Notes:

 Parameter refers to the list of variables in a method declaration. Arguments are the actual
values that are passed in when the method is invoked. When you invoke a method, the
arguments used must match the declaration's parameters in type and order.

 The Java programming language doesn't let you pass methods into methods. But you can
pass an object into a method and then invoke the object's methods.

 When a object variable is passed into the method, only the copy of the Object reference is
passed and not the Object itself. The bit pattern in the reference variable is copied into the
method parameter. What is this bit pattern? This bit pattern is the address of the specific
object in the memory (on the heap). In other words, both the caller and the called method
will now have identical copies of the reference and thus both will refer to the same exact
object on the heap.

If Java uses the pass-by reference, why won't a swap function work?

Your question demonstrates a common error made by Java language newcomers.


Indeed, even seasoned veterans find it difficult to keep the terms straight.

100
Java does manipulate objects by reference, and all object variables are references. However, Java
doesn't pass method arguments by reference; it passes them by value.

Take the badSwap() method for example:

public void badSwap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}
When badSwap() returns, the variables passed as arguments will still hold their original values.
The method will also fail if we change the arguments type from int to Object, since Java passes
object references by value as well. Now, here is where it gets tricky:

public void tricky(Point arg1, Point arg2)


{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
If we execute this main() method, we see the following output:

X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a
swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1
101
and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky()
method, Java passes the references by value just like any other parameter. This means the
references passed to the method are actually copies of the original references. Figure 1 below
shows two references pointing to the same object after Java passes an object to a method.

Figure 1. After being passed to a method, an object will have at least two references

Java copies and passes the reference by value, not the object. Thus, method manipulation will
alter the objects, since the references point to the original objects. But since the references are
copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original
references. Unfortunately, after a method call, you are left with only the unswapped original
references. For a swap to succeed outside of the method call, we need to swap the original
references, not the copies.

Figure 2. Only the method references are swapped, not the original ones

102
Method Overloading

Method overloading means having two or more methods with the same name but
different type of arguments or different number of arguments. These two methods may exist in
the same class or subclass and another in derive class. Return type of method and access
specifier of method is not a problem in method overloading.

Example: void sum(int a,int b) {…………..} then it can be overloaded as

void sum(int a,int b,int,c) {……………}

void sum(String s1,string s2) {……………}

Static or early Binding Polymorphism

In case of overloading the method resolution performed by the compiler is based on the
reference type.

Method overriding

Method overriding means having different implementation of the same method in the
inherited class. These two methods would have the same signature, but different implementation
one of these would exist in the base class and another in the derived class. These cannot exist in
the same class. This is dynamic or late binding polymorphism.

Example: class a {
public void display() {
System.out.println(“ it is a first class.”);
}}
class overriding extends a {
public display() {
System.out.println(“ it is a second class.”); // override }
public static void main(String arg[]){
overrinding obj = new overriding();
obj.display();
}}
Output: It is a second class.

Late binding:

When an object is sent a message then it does not know itself what type it is, the runtime
environment will decide about function calling over an object. The feature of connecting an
object with its associated message at runtime as known as polymorphism or late binding.

Rules for method overriding


103
1. The argument list should be exactly the same as that of the overridden method.
2. The return type should be the same or a subtype of the return type declared in the original
overridden method in super class.
3. The access level cannot be more restrictive than the overridden method’s level.
4. Instance methods can be overridden only if they by the subclass.
5. A method declared final cannot be overridden.
6. A method declared static cannot be overridden but can be redeclared.
7. If a method cannot be inherited then if cannot be overridden.
8. A subclass within the same package as the instance’s superclass can override any
superclass method that is not declared public or final.
9. A subclass in a different package can only override the non-final methods declared public
or protected.
10. An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overridden method should not
throws checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden.
11. Constructor cannot be override.
12. We can override a synchronized method to non-synchronized (native).
13. We can override a non-final method to final method.

Difference between overloading and overriding.

Overloading methods. Overriding method.


1. Overloaded methods supplement 1. An overriding method replaces the
each other. method it overrides.
2. Overloading methods may have 2. An overriding method must have
different argument lists of different argument lists of identical type and order.
types.
3. The return type may be different for 3. The return type must be same as that of
overloaded methods overridden method.
4. Since overloading methods are 4. The overriding method must not throw
essentially different methods, there is checked exceptions, which cannot be thrown
no restriction on exceptions they can by the original method.
throw.

104
5. Signature has to be different. Just a 5. Signature has to be the same. (including
difference in return type is not the return type)
enough.

6. Accessibility may vary freely. 6. Overriding methods cannot be more


private than the overridden methods.

7. Exception list may vary freely. 7. Overriding methods may not throw more
checked exceptions than the overridden
methods.

8. Just the name is reused. Methods are 8. Related directly to sub-classing.


independent methods. Resolved at Overrides the parent class method. Resolved
compile-time based on method at run-time based on type of the object.
signature.
9. Can call each other by providing 9. Overriding method can call overridden
appropriate argument list. method by super.methodName(), this can
be used only to access the immediate super-
class's method. super.super won't work. Also,
a class outside the inheritance hierarchy can't
use this technique.
10. Methods can be static or non-static. static methods don't participate in overriding,
Since the methods are independent, it since they are resolved at compile time based on
doesn't matter. But if two methods the type of reference variable. A static method
have the same signature, declaring in a sub-class can't use 'super' (for the same
one as static and another as non-static reason that it can't use 'this' for)
does not provide a valid overload. It's
a compile time error.

10. Remember that a static method can't be


overridden to be non-static and a non-static
method can't be overridden to be static. In
other words, a static method and a non-static
method cannot have the same name and
signature (if signatures are different, it would
have formed a valid overload)
11. There's no limit on number of Each parent class method may be overridden at
overloaded methods a class can have. most once in any sub-class. (That is, you cannot
have two identical methods in the same class)

Method hiding:

105
This is exactly same as overriding except both parent and child class methods must be
declared as static. In the method hiding the method resolution take care by compiler only based
on the reference type.
Variables can also be overridden, it's known as shadowing or hiding. But, member
variable references are resolved at compile
Example: class p {
Static int x=10;
Int5 y=20;
}
Class c extends p {
Static int x=100;
Int y=200;
}
Class sample {
Public static void main(String a[]){
P p1 = new p1();
Sytem.out.println(p1.x+“,”+p1.y); //10,20
C c1 = new c();
Sytem.out.println(c1.x+“,”+c1.y); // 100,200
P pc =new p();
Sytem.out.println(pc.x+.“,”+pc.y); //10,20
}}
We cannot override in the child class but define exactly same variable in child class. Variable
resolutions take care by complier only based on the reference type.
Constructor

Constructor will be automatically invoked when an object is created whereas method has to be
called explicitly. Constructor needs to have the same name as that of the class whereas functions need
not be the same.

• There is no return type given in a constructor signature (header). The value is this object itself so
there is no need to indicate a return value.

• There is no return statement in the body of the constructor.

• The first line of a constructor must either be a call on another constructor in the same class (using
this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler
automatically inserts a call to the parameterless super class constructor.

‘this’ Keyword
‘this’ is used to either call another constructor of the same class whose object is used to
106
call a method; or whose constructor is being used to instantiate a class. This refers to the current
object whose reference variable is used to call method or this refers to the current object in
action.It is used to access the data members and methods. ‘this’ it must be first statement in that
method or constructor.

public sample
{
this(20);
this.display();
}
It is mandatory that, when we are calling constructor through 'this' it must be first statement in that
method or constructor.

It is used to access data members and mehods

Example:

this.len=len;
this bth=bth;
this.getvalue();
this.setvalue();
‘super’ keyword

super() can be used to invoke a super class constructor. Super refers to the immediate
super class, super(); super is a keyword that refers to super class from a subclass.

super class instance variable

Example: System.out.println(super.a);

class A
{
int a = 30;
}

class B extends B
{

void show()
{
int a=10;
System.out.println("The a Value in super class is"+super.a);

107
System.out.println("The a Value in super class is"+a);
}
public static void main(String[] args)
{
B b=new B();
b.show()
}
}

super class methods


Example: super.setvalue();
class one
{
int x,y,s;
one()
{

System.out.println("First went to one default const of superclass");


}
void show(int a,int b)
{
x=a;
y=b;
System.out.println("\n superclass value X is"+x);
System.out.println("\n superclass value Y is"+y);
}
void gets()
{
s=x+y;
}
}
class two extends one
{
int a,b,c;
two()
{
System.out.println("\n second came to default const of child class");
}
void show()
{
super.gets();

108
System.out.println("\n baseclass value is"+s);
}
}
class intmet
{
public static void main(String args[])
{
two t=new two();
t.show(2,3);
t.show();
}
}

super class constructor


Example: super(a);super(a,b) and so on
class one
{
int x;
one()
{
System.out.println("First went to one default const of super
class");
}
one(int x)
{
System.out.println("\nas the supre(a)is referd one parameter
const is printed");
this.x=x;
}
void show()
{
System.out.println("\none parameter const value is"+x);
}
}
class two extends one
{
int x,a;
two()
{
System.out.println("\n second came to default const of

109
child class");
}
two( int a,int b)
{
super(a);
System.out.println("\ntwo const");
x=b;
}
void show()
{
System.out.println("\ntwo parameter const value is"+x);
super.show();
}
}

class const1
{
public static void main(String args[])
{
two t=new two();
two t1=new two(2,3);
t1.show();
}
}
Below is an example of a cube class containing 2 constructors. (One default and one
parameterized constructor).
Example:

public class Cube1 {


int length ;
int breadth ;
int height ;
public int getVolume( ) {
return ( length * breadth * height );
}
Cube1(){
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h){
110
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : "+cubeObj1.getVolume());
System.out.println("Volume of Cube2 is : "+cubeObj2.getVolume());
}
}
Java Overloaded Constructors

• Constructors can also be overloaded in similar fashion, as they are also methods.

• Java has some classes with overloaded constructors. For example, wrapper class for int has two
overloaded constructors. One constructor takes int as argument and another takes string argument.

• Integer aNumber = new Integer(2);

• Integer anotherNumber = new Integer("2005");

• One constructor can call another overloaded constructor of the same class by using this keyword.

• One constructor can call constructor of its super class by using the super keyword.

public class ConstructorOverloading{


public static void main(String args[]){
Rectangle rectangle1=new Rectangle(2,4);
int areaInFirstConstructor=rectangle1.first();
System.out.println(" The area of a rectangle in first constructor is : " + areaInFirstConstructor);
Rectangle rectangle2=new Rectangle(5);
int areaInSecondConstructor=rectangle2.second();
System.out.println(" The area of a rectangle in first constructor is : " + areaInSecondConstructor);
Rectangle rectangle3=new Rectangle(2.0f);
float areaInThirdConstructor=rectangle3.third();
System.out.println(" The area of a rectangle in first constructor is : " + areaInThirdConstructor);
Rectangle rectangle4=new Rectangle(3.0f,2.0f);
float areaInFourthConstructor=rectangle4.fourth();
System.out.println(" The area of a rectangle in first constructor is : " + areaInFourthConstructor);
}
}
111
class Rectangle{
int l, b;
float p, q;
public Rectangle(int x, int y){
l = x;
b = y;
}
public int first(){
return(l * b);
}
public Rectangle(int x){
l = x;
b = x;
}
public int second(){
return(l * b);
}
public Rectangle(float x){
p = x;
q = x;
}
public float third(){
return(p * q);
}
public Rectangle(float x, float y){
p = x;
q = y;
}
public float fourth(){
return(p * q);
}
}

Constructor Chaining

Constructor chaining occurs through the use of inheritance. A subclass constructor method's first
task is to call its superclass' constructor method. This ensures that the creation of the subclass object
starts with the initialization of the classes above it in the inheritance chain.

There could be any number of classes in an inheritance chain. Every constructor method will call
up the chain until the class at the top has been reached and initialized. Then each subsequent class below
112
is initialized as the chain winds back down to the original subclass. This process is called constructor
chaining.

Every constructor calls its superclass constructor. An implied super() is therefore included in
each constructor which does not include either the this() function or an explicit super() call as its first
statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super().

The super statement must be the first statement of the constructor.


The explicit super allows parameter values to be passed to the constructor of its superclass and must
have matching parameter types A super() call in the constructor of a subclass will result in the call of the
relevant constructor from the superclass, based on the signature of the call. This is called constructor
chaining.

Below is an example of a class demonstrating constructor chaining using super() method.

class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube() {
this(10, 10);
System.out.println("Finished with Default Constructor of Cube");
}
Cube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
2 params of Cube");
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having
3 params of Cube");
}
}

public class SpecialCube extends Cube {


113
int weight;
SpecialCube() {
super();
weight = 10;
}
SpecialCube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
2 params of SpecialCube");
}
SpecialCube(int l, int b, int h) {
super(l, b, h);
weight = 20;
System.out.println("Finished with Parameterized Constructor having
3 params of SpecialCube");
}
public static void main(String[] args) {
SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);
System.out.println("Volume of SpecialCube1 is : "
+ specialObj1.getVolume());
System.out.println("Weight of SpecialCube1 is : "
+ specialObj1.weight);
System.out.println("Volume of SpecialCube2 is : "
+ specialObj2.getVolume());
System.out.println("Weight of SpecialCube2 is : "
+ specialObj2.weight);
}
}
Output
Finished with Parameterized Constructor having 3 params of SpecialCube

Finished with Parameterized Constructor having 2 params of SpecialCube

Volume of SpecialCube1 is: 1000

Weight of SpecialCube1 is: 10

Weight of SpecialCube2 is: 20

The super() construct as with this() construct: if used, must occur as the first statement in a
constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls
114
cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in
the same class, the super() construct leads to chaining of subclass constructors to superclass
constructors. If a constructor has neither a this() nor a super() construct as its first statement, then a
super() call to the default constructor in the superclass is inserted.

Note: If a class only defines non-default constructors, then its subclasses will not include an implicit
super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a
superclass constructor, using the super() construct with the right arguments to match the appropriate
constructor of the superclass.

What is the difference between a constructor and a method?

A constructor is a member function of a class that is used to create objects of that class. It has the same
name as the class itself, has no return type, and is invoked using the new operator.

A method is an ordinary member function of a class. It has its own name, a return type (which may be
void), and is invoked using the dot operator.

Accessing the class and class Members:

The variables (including reference variables) and methods in a class are called class
members. A class can also have other classes called nested class. To access to the class members
can be controlled by using access modifiers specified in the member definition.

1. public

2. protected

3. default

4. private

1) public :

A class member declared ‘public’ can be accessed by any code from any class in
your application. This modifier makes a class or a class member most accessible.

2) protected :

A member declared ‘Protected’ is accessible to all classes in the same package in


which the class that declares the member exists. The protected member can also
be accessed from a subclass of the class that contains the member even if the
subclass is in a different package.

You cannot declare a top-level class as protected. The ‘protected’


modifier provides less accessibility than ‘public’ modifier.
115
3) default :

If you do not specify any access modifier while declaring a class or class member,
the default access is assumed.

A class or a class member with default access can be accessed by any class
in the same package. Default access cannot access by subclass that is in a
different package. The ‘default’ modifier provides less accessibility than
‘protected’ modifier.

4) Private :

A member declared as ‘private’ is only accessible to that class only. A top-level


class cannot be declared ‘private’, it can be only be private or default.

Visibility Public Protected Default Private

From the same class Yes Yes Yes Yes


From any class in the same package Yes Yes Yes No
From a subclass in the same package Yes Yes Yes No
From a subclass outside the same Yes Yes No No
package
From any non-subclass class outside the Yes No No No
package
Usage Modifiers:

1. final

2. static

3. abstract

4. native

5. transient

6. volatile

7. synchronized

1) The ‘final’ modifier

116
• The final modifier may be applied to a class, a method, or a variable.

• If the variable is declared final, it means the value of the variable is constant, and cannot be
changed.

• If the class is declared final, it means the class cannot be extended, and a final method cannot
be overridden.

Example:

Class calculator
{
final int dime = 10;
int count =10;
calculator(int i)
{
count = i;
}
}
Class Runcalculator
{
Public static void main(String arg[]) {
Final calculator calc = new calculator(1);
Calc = new calculator(2); //compile time error
Calc.count = 2;
Calc.dime = 11; // compile time error
System.out.println(“Dime: ”+calc.dime);
}
}
Output: Dime: 10

Caution

• A final object reference may not be modified; it can be used to modify the value of a non-
final variable in the object to which the final object reference refers.

• If you declare a final method inside a non-final class, it will be legal to extend the class, but
you cannot override the final method of the parent class in the subclass.

• Similarly, you can pass the final variable to a method through arguments, but you cannot
change this value even inside the method.

• final has two purposes: efficiency and safety.

117
• We are missing key benefits of object oriented programming concepts, reusability and
flexibility.

final is not the same as C++ const

If you have a final reference to an object or array, it does not stop you from changing the
fields in the object or elements of the array. final just stops you from pointing that reference
variable to a different object or array. If you want to protect the object from changes, you must
make it immutable, namely remove any setter methods from its class definition. Java’s final is
not as flexible and powerful as C++ const, however, Java’s final is less error prone.

2) The ‘static’ modifier

• The static modifier can be applied to variables, methods, and a block of code inside a
method.

• The static elements of a class are visible to all instances of the class.

• If one instances of the class makes a change to a static element, all the instances will see the
change.

• We cannot apply static keyword for the top level classes, but we can apply inner classes.

• A static method can only access the static member of the class. Because a static method does
not belong to a particular instance of the class in which it is defined, it can be called even
before a single instance of the class exits.

• Every java application has a method main (...) which is the entry point for the application
execution. It is executed without initiating the class in which it exits

• We can overload static methods. But we cannot override

• A static variable is initialized at class load time. Also, a static method and a static code block
are executed at class load time.

Static variable:

• static variables are classes variables not instance variables .They are instantiated only once
for a class. They are initialized at class load time.

118
• Static variables can be accessed by non-static methods.

• Static variables are common to all objects of class. Static variables are declared once into a
class and are available entire class.

Example: 1

class Add

static int a; // Defaultly the value of a is 0 since, it is declared as static.

class Sub

int A=Add.a; // the value of A is 0.

Example: 2

class A
{ static int a;
}
class StaticDemo
{ public static void main(String args[])
{ A obj1 = new A();
A obj2 = new A();
}
}
In such a case, objects obj1 and obj2 will not have different copies of variable a. Both objects
will refer to the same "a". In simpler words, copy of "a" is not created.

If "a" was not static, then obj1 and obj2 would hold different copies of "a".

Static methods:

• Static method can be referenced with the name of the name of the particular object of that
class.
119
• static method is the one which can be called with the class itself and can hold only the staic
variables.
• static method is use to access without creating object in the java program.
• static method represent class behavior and instance variable represent object behavior. but
instance of a class is not require for the invocation of static variable.
• static block and static method can directly invoked the static method, nonstatic method
cannot directly by static method or static block.
• ‘this’ and ‘super’ keyword cannot be used in static block and method
• static data member of the class can be referred in a static block or method.
• static method is bind with class name or object name

Example:

class StaticExample {
static int instanceCounter = 0;
int counter = 0;
StaticExample() {
instanceCounter++;
counter++;
}}
class RunStaticExample {
public static void main(String[] args) {
StaticExample se1 = new StaticExample();
StaticExample se2 = new StaticExample();
System.out.println("Value of instanceCounter for se1: " +se1.instanceCounter);
System.out.println("Value of instanceCounter for se2: " +se2.instanceCounter);
System.out.println("Value of instanceCounter: " +StaticExample.instanceCounter);
System.out.println("Value of counter for se1: " + se1.counter);
System.out.println("Value of counter for se2: " + se2.counter);
}
}
The following is the output from Listing 4-9:
Value of instanceCounter for se1: 2
Value of instanceCounter for se2 2
Value of instanceCounter: 2
Value of counter for se1: 1
Value of counter for se2 1
Static code block

120
Static variable and static methods a class may have a static code block that does not
belong to any method, but only to the class.

For example, you may not like to execute a task before the method main (...) is called.
The static code block will help because it will be executed when the class is loaded.

Example:

class StaticCodeExample {
static int counter=0;
static {
counter++;
System.out.println("Static Code block: counter: " + counter);
}
StaticCodeExample() {
System.out.println("Constructor: counter: " + counter);
}
static {
System.out.println("This is another static block");
}
}
public class RunStaticCodeExample {
public static void main(String[] args) {
taticCodeExample sce = new StaticCodeExample();
System.out.println("main: " + sce.counter);
}
}
The output:
Static Code block: counter: 1
This is another static block
Constructor: counter: 1
main: counter: 1
This output demonstrates that the static code block is executed exactly once, and before
the class constructor is executed—that is, at the time the class is loaded. It will never be executed
again during the execution lifetime of the application. Note that all the static blocks will be
executed in order before the class initialization regardless of where they are located in the class.

Note: you cannot declare the following elements as static

1. constructor
2. class (i.e. top-level class)
3. inner class methods

121
4. instance variable
5. local variable
3) The ‘abstract’ modifier

• The abstract modifier may be applied to a class or a method, but not to a variable. A class
that is declared abstract cannot be instantiated. Instantiation of an abstract class is not
allowed, because it is not fully implemented yet.

• Any class that extends an abstract an abstract class must implement all the abstract
methods of the super class unless the superclass is also an abstract class.

• If a class contains one or more abstract methods then the class must be declared abstract.

• Abstract class does not need to contain the abstract methods.

• The abstract method end with a semi colon. Example: public abstract sample ();

Example:

abstract class Shape {

abstract void draw(); //Note that there are no curly braces here.

void message() {

System.out.println("I cannot live without being a parent.");

class Circle extends Shape {

void draw() {

System.out.println("Circle drawn.");

class Cone extends Shape {

void draw() {

System.out.println("Cone drawn.");
122
}}

public class RunShape {

public static void main(String[] args) {

Circle circ = new Circle();

Cone cone = new Cone();

circ.draw();

cone.draw();

cone.message();

}}

The output:

Circle drawn.

Cone drawn.

I cannot live without being a parent.

4) The ‘strict floating point’ modifier

• strictfp is a Java keyword that restricts floating-point calculations in order to ensure


portability. The modifier was added to the Java programming language with the Java virtual
machine version 1.2.

• The modifier can be combined with classes, interfaces and methods. We cannot apply strictfp
for variable.

• If a method declared as the strictfp all the floating point calculations inside that method has
to follow “IEEE 754” standards result. We will get platform independent result.

• If a class declared as the strictfp, all concrete methods in that class has to follow IEEE 754
standard for floating point calculation.

• Abstract and strictfp combination is not for methjods. But it is valid for the classes.

123
5) The ‘native’ modifier

Native is the keyword which can be apply only for methods. i.e we can not apply native
keyword for classes and variables.

1) A native method means. The method which is implemented in non-java like c,c++;

2) Native methods are also known as foreign methods.

Advantages of Native method:

1) As the performance of java is low for improving the performance we can depends on c or c++.
These stage methods can be helped by native keywords

2) We can communicate legacy systems by using native keyword

Example:

class NativeEx

static

{ System.loadLibraries(“path of native methods library”); }

native void m1();

class Client

public static void main(String arg[])

Native n=new NativeEx();

n.m1();

}}
124
• For the native methods already implementation is available but abstract method means
implementation is not available .hence abstract and native combination is illegal for the
methods.

• Native methods already implementation is available we are not providing any


implementation. hence native method declaration should be ends with semicolon

• Native and strictfp combination is illegal for methods because old languages may not fallow
IEEE 754 standard for floating point.

• We can override a native method.

• We can overload a native method.

6) The ‘transient’ modifier

Transient is the keyword which can be applicable only for variables i.e., we are not allowed
to use transient keyword for methods and classes.

Serialization:

The process of saving an object to a file is called serialization Strictly serialization means
“The process of converting java supported format object to network supported format object (or)
file supported format object is called serialization.

1) If a variable declared as a transient, at the time of serialization JVM ignores the values of
that the transient variable. Instead of original values JVM saves default value.

2) Hence transient means not to serialize. Example:- While saving account information
permanently to a file we are not allowed to save passwords for security reasons such type of
variables we have to declare by transient keyword

3) We can serialize only serializable objects violation leads to runtime exception saying not
serializable exception

4) An object is said to be serializable if an only if the corresponding class implements


serializable interface

125
Transient Example:

import java.io.*;

class Transient Demo implements Serializable

int i=10;

int j-20;

public static void main(string args[])throws exception

Transient demo t1=new transient demo();

System.out.println(t1.i+”----“+t1.j);

file output stream fos=new file output stream(“abc.txt”);

object output stream oos=new object output stream(fos);

oos.writeobject(t1);

//t1.i=1000

//t1.j=2000

FileInputStream fis=new FileInputStream(“abc.txt”);

ObjectInputStream fis=new ObjectInputStream(fis);

Transient Demo t2=( Transient Demo)ois.writeObject(t1);

System.out.println(“t2.i+”…”+t2.j);

1. If we are not declaring implements serializable we will get a runtime exception not
serializable exception

2. if we are not keeping throws exception compile time error saying unreported exception
must be called or declared to be thrown

126
Note:-

• static variables never part of object state hence we are not participating in the
serialization process during a static variables as the transient is useless and there is no impact.

• Transient modifier is related to strong an object on the disk, such storage is called the
objects’ persistent state.

• The transient modifier can only be applied to instance variables. When you are declaring
an instance variable transient, you are instructing the JVM not to store this variable when the
object in which it is declared is being serialized.

• In a multithreaded environment, more than one process may try to access the same class
element concurrently. To handle that situation, there are a couple of modifiers that you need
to it.

The thread related modifiers

A computer may have launched more than one process executing concurrently. This is
called multithreaded programming. The following two modifiers,

Volatile and synchronized

7) The ‘volatile’ modifier

Volatile is the keyword, which can be applicable only for variables i.e. we cannot use for classes
and methods. If the value of the variable is changing frequently such type of variables, we have
to declare with the keyword volatile.

1. For the volatile variables, JVM will create a separate private copy for every thread. After
completing entire transaction but that thread, the final value will be updated in the master
copy. So that the value of the volatile variable is always stable

2. At variable level we can achieve synchronization by using volatile keyword

3. For every thread maintaining a separate copy is always difficult .hence performance of the
system goes down

127
4. Volatile means the value keep on changing but final means the value is not allowed to
change. Hence volatile and final combination is always illegal. We are not declaring a final
variable as volatile.

8) The ‘synchronized’ modifier

1. Synchronized is the keyword which can be apply for method and blocks. i.e we can not apply
synchronized keyword for classes and variables.

2. If a method declared as synchronized at a time only one thread is allowed to execute that
method on the given object.

Advantages:

1. We can provide thread safety

2. We can avoid data inconsistency problems

Disadvantages:

1. synchronized keyword increases waiting time of threads and hence performance of the
system goes down. Hence unless and until there is no specific requirement do not use
synchronized keyword in the coding.

Note: Synchronized is the keyword which is always talks about implementation but abstract
never talks about implementation. Hence synchronized and abstract combination is illegal for the
methods.

Not-valid combinations:

• abstract and final .

• abstract and strictfp

128
• abstract and synchronized

• abstract and static

• abstract and native

• abstract and private.

Modifiers elements in matrix

class Interface
Code
Element Data field Method
Constructor Top-level nested Top-level nested block

   
Public    

   
Private    

   
Protected    

   
Default    N/A

   
Final    

   
Static    

   
Abstract    

Native
       

129
   
Transient    

   
Volatile    

   
synchronized    

   
Strictfp    

EXCEPTION, ASSERTIONS, STATIC IMPORT

Exception
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a run-time error.
An exception can occur for many different reasons, including the following:
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications, or the JVM
has run out of memory.
User error, others by programmer error, and others by physical resources that have failed
in some manner cause some of these exceptions.
Java Exception

130
A Java exception is an object that describes an exceptional condition i.e., an error
condition that has occurred in a piece of code. When this type of condition arises, an object
representing that exception is created and thrown in the method that caused the error by the Java
Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at
some point, the exception is caught and processed.

There are two different ways to generate an Exception.


1. Exceptions can be generated by the Java run-time system.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
2. Exceptions can be manually generated by your code.(Run Time)
Manually generated exceptions are typically used to report some error condition to the
caller of a method.

The Exception Tree in Java


As they say, everything in Java is a class (or object), and the exceptions are no exception.
They are organized into a hierarchy of classes, a part of which is shown in Figure
The Throwable class, which is the root of the exceptions tree, is the base class of all the
exceptions in Java. The two subclasses of Throwable, directly derived from Throwable, are Error
and Exception. Errors (represented by subclasses of Error) occur in the Java virtual machine
(JVM) and not in the application itself. An error generally represents an unusual problem from
which it is difficult to recover. These problems generally originate from the execution
environment
This class and of itsthe application (for example, running out of memory). Because it is impossible
subclasses
(or difficult at best) to recover from errors during runtime, you, the programmer, are not required
represent Java.lang.Thro
to handleerrors.
them. Errors
The exceptionswable
(represented by subclasses of Exception), on the other hand,
are
generally originate from within the application. They may also be related to the way in which the
not checked by the
program is interacting with the environment (for example, referring to a nonexistent remote
compiler.
machine).Java.lang.Erro
The exceptions, if handled, should generally be handled in the program, but you are
Java.lang.Exce
not required
r to handle all of them. ption
Exception stands in the Java tree hierarchy
java.lang.Object
java.lang.Throwable
Java.lang.VirtualMach Java.lang.IOExce Java.lang.RuntimeEx
java.lang.Exception
ineError ption ception
java.lang.Error

Java.lang.LegalArgumentE
Java.lang.StackOverFl
xception
owError

An example of checked exceptions.


All subclasses of exception and their RuntimeException and its 131
subclasses (except subclasses are called runtime
RuntimeExceptions and its exception. The compiler does
subclasses) are checked exceptions. not force you to handle them
The compiler forces
or declare them
You to handle them or declare them.
Exception handling provides the following advantages
1. Separating Error Handling Code from "Regular" Code.
2. Propagating Errors Up the Call Stack.
3. Grouping Error Types and Error Differentiation.

Checked Exceptions and Runtime Exceptions


When in a program, if you perform an operation that causes an exception—that is, an
exception is thrown—you can always catch the exception and deal with it in the code. This is
called handling the exception. Based on whether or not you are required to handle them, the
exceptions in Java are classified into two categories: checked exceptions and runtime exceptions.

Checked Exceptions
The programmer is required to write code to deal with checked exceptions. The compiler
checks that such code exists. Dealing with (or handling) an exception means either declaring it in
the throws clause of your method or catching it inside the method, or both. Checked exception
are those which the Java compiler forces you to catch.
1.CloneNotSupportedException
2.IllegalAccessException
3.InstantiationException
4.InterruptedException
5.NoSuchFieldException
132
6.NoSuchMethodException
7. ClassNotFoundException

Runtime exceptions (Unchecked exceptions)


Runtime exceptions are those exceptions that are thrown at runtime because of either
wrong input data or because of wrong business logic etc. These are not checked by the compiler
at compile time. Runtime exceptions are not checked by the compiler, and you are not required
to deal with them, but it is not illegal to catch them.
1.ArithmeticException
2.ArrayIndexOutOfBoundsException
3.ClassCastException
4.IndexOutOfBoundsException
5.IllegalStateException
6.NullPointerException
7. SecurityException

CommonExceptions and Errors:


Exceptions or errors may be thrown by either JVM(JVM Exceptions) or thrown explicitly
by application developers or API programmers(programmatic exception).
1. NULLPOINTER EXCEPTION:
Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a reference variable
whose current value is null.
Ie., on null if we are applying any operation we will get NullPointerException.

2. STACK OVERFLOW ERROR:-


• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
133
Ex:class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new Sample(); }//Exception in main
thread stack overflow error
}

3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:


• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ----> IndexOutOfBoundsException---
> ArrayIndexOutOfBoundsException, StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing an array element
with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}

4. CLASS CAST EXCEPTION:


Class Sample
{
public static void main(String a[]))
134
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a reference variable
to a type the fails to cast a reference variable to a type the faith the IS- A test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;

5. NOCLASS DEF FOUND ERROR:


* It is the child class of error and it is unchecked one and unreachable.
* It is thrown by JVM. If the JVM or class loader tries to load the definition of the
class and no definition of the class could be found.

6. EXCEPTION IN INITIALIZER ERROR:


class Sample
{
Static String s;
String s1=new String(s);
public static void main(String a[])
{
System.out.println(“hai”);
}
}//Exception in initializer error caused by java.lang.NullPointerException.
Thrown by the JVM to indicate that an exception is occur during initialization of static
variable or initialization block.

7. ILLEGAL ARGUMENT EXCEPTION:

* It extends RTE and unchecked.


* Thrown by aPI developer to indicate that a method has been passed an illegal or
inappropriate argument.

135
Ex: Thread class setPriority() and sleep() methods throw this exception.
class Sample
{
p s v m(String a[])
{
Thread.currentThread().setPriority(15);
}
}//CTE: Illegal Argument exception

8. NumberFormatException:
Integer i=new Integer(“10”);//valid
Integer i=new Integer(“ten”);//invalid
CTE: NumberFormateException
int i=Integer.parseInt(arg[0]);
In commandline if we give “10” is valid. But “ten” is invalid.
It is the direct child class of illegal argument exception and thrown programmatically to
indicate the application has attempted to convert a string to the number, but the string doesn’t
have appropriate format.

9. IllegalStateException:
It extends RTE and indicates that a method has been invoked at an illegal or
inappropriate time.
Ex: PrintWriter out=res.getWriter();
Out.println(…);
Out.close();
Out.println(“…”); ---> this is not appropriate time to call print() on out object and hence
throws IllegalStateException.
10. Assertion Error:
It is the child class of error throws programatically when assert statement when Assert
statement fails.
Summarization:
Exception or error --------------------- thrown by
1. NullPointerException ------------------ JVM
2. StackOverFlowErrorException --------------- JVM
3. ArrayIndexOutOfBoundsException ------------- JVM
4. ClassCastException ------------------------- JVM
5. NoClassDefFoundError -------------------- JVM
6. ExceptionInIntializerError -------------------- JVM
136
thrown by programmatically by programmer API developer:
7. IllegealArgumentException
8. NumberFormatException
9. IllegalStateException
10. Assertion Error

Checked vs Unchecked Exceptions :


• The Exceptions which are checked by the compiler for smooth execution of program at
Runtime are called checked Exceptions.
• The Exceptions which are unable to check by the compiler are called Unchecked
Exceptions.
• Runtime Exception and its child classes: Error and its child classes are Unchecked
Exceptions. While the remaining all are Unchecked Exceptions.

Partially Checked vs Fully Checked :


A Checked Exception is said to be Fully Checked Exception if and only if all its child
classes are also checked. Otherwise it is Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked

try , catch , finally

finally block:
try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because irrespective of
exception occurred or not occurred or handled or not handled, the finally block will always
execute.

137
Difference between final, finally and finalize
• It is highly recommended to keep cleanup code inside finally block instead of finalize().
• The finally block will always execute except the place where the JVM got shutdown.
We can shutdown the JVM by calling /using System.exit(0).

Example:
try
{
System.out.println(“hai”);
}
catch( NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally

Samples:
1. try{} catch(X e){} -->valid
2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
i.e , try --> catch --> finally is the only order.
Only try{} ---> invalid,
Only catch{} ----> invalid
Only finally{} ----> invalid
Note: try without catch & catch with out try invalid

Example:
catch(..){}
finally{}
CTE: catch with out try

Control Flow in try, catch, finally block :

138
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;

See the below cases:


Case 1:- If there is no exception then 1,2,3,5,6 and normal termination.
Case 2:- If an exception raised at stmt2 and the corresponding catch block found 1,4,5,6
and normal termination.
Case 3:- If an exception raised at stmt2 and the corresponding catch block not matched
1,5 and abnormal termination.

Control Floe in the Nested try, catch, finally blocks:


try
{
Stmt1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
catch(XException e)
{
Stmt 7;
}
finally
{

139
Stmt 8;
}
Stmt 9;
}
catch(YException e)
{
Stmt 10;
}
finally
{
Stmt 11;
}
Stmt 12;

Case 1: If there is no exception 1,2,3,4,5,6,8,9,11,12 and normal termination.


Case 2: If an exception raised at stmt 2 and the corresponding catch block found then
1,10,11,12 and normal termination.
Case 3: If an exception raised at stmt2 and the corresponding catch block has not
matched then 1,11 and abnormal termination.
Case 4: If an exception raised at stmt5 and the corresponding catch block has matched
then 1,2,3,4,7,8,9,11,12 and normal termination.
Case 5: If an exception raised at stmt5 and the corresponding catch block has not
matched but the outer catch has matched then 1,2,3,4,8,10,11,12 and normal termination.
Case 6: If an exception raised at stmt5 but the inner and outer catch blocks are not
matched then 1,2,3,4,8,11 and abnormal termination.

‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects are handed over to
JVM.

Example:
class Sample

140
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads to CTE saying
“unreachable statement”.

Example:
class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();

Example:
class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or declared to be
thrown.
• Inside a program if there is any chance of throwing a checked exception explicitly or
implicitly we have to handle that checked exception by using try - catch or we have to delegate
the responsibility or exception handling to the caller. Violation leads to CTE saying Unreported
Exception xxx; must be caught or declared to be thrown.

Thank you for visiting Java Examples.For regular updates request you to subscribe to my
RSS Feed or register your Email Subscription for updates directly into your mail box.

141
throws , throw

“throws” Keyword :We can ‘throws’ keyword for delegating the responsibility of the
Exception handling to the caller.
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be
caught or declared to be thrown. To avoid CTE(compile time error) another way in using try --->
catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}

142
* If we are keeping the catch block for fully checked exception there should may be a
chance of raising exception in the corresponding try block otherwise CTE saying XXXException
is never thrown in the body of corresponding try statement.

Case 1:
try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE(compile time error)
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{
//Partially checked exception
}
Case 3:
try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{
// fully checked exception
}

Throw keyword:By using ‘throw ‘ keyword, over created customized exception objects
are handed over to JVM.

Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement

143
}
After throw we are not allowed to keep any statement, violation leads to CTE saying
“unreachable statement”.

Note the followings:


1.A catch clause cannot exist without a try statement.
2.It is not compulsory to have finally clauses whenever a try/catch block is present.
3.The try block cannot be present without either catch clause or finally clause.
4.Any code cannot be present in between the try, catch, finally blocks.

Exceptions Methods:Following is the list of important medthods available in the Throwable


class.

SN Methods with Description


1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output
stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method
at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

Declaring you own Exception:


You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes:
1. All exceptions must be a child of Throwable.
2.If you want to write a checked exception that is automatically enforced by the Handle
or Declare Rule, you need to extend the Exception class.
3.If you want to write a runtime exception, you need to extend the RuntimeException
class.

We can define our own Exception class as below:


class MyException extends Exception{
144
}
You just need to extend the Exception class to create your own Exception class. These
are considered checked exceptions. The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it a checked exception. An exception
class is like any other class, containing useful fields and methods.

Example:
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class
contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException

145
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}

The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.

// File Name BankDemo.java


public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{

146
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}

Compile all the above three files and run BankDemo, this would produce following
result:

Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

Explanations of common Java exceptions

java.lang
You are trying to use your computer to solve a
ArithmeticException mathematical problem that you cannot solve yourself.
Read up on your arithmetics and try again.
See IndexOutOfBoundsException. The difference
ArrayIndexOutOfBoundsException
is that this exception refers to more than one finger.
You have used all your arrays and need to buy
ArrayStoreException
more from the array store.
You need to stay in the class or caste you were
born into. Java will not accept dailits acting as kshatriyas
or noblemen pretending to be working class. Note the
ClassCastException
spelling mistake (of caste) that was introduced in Java 1.0
and has not been corrected for backwards compatability
reasons.
You seem to have invented your own class. There
are also caste systems that are not yet implemented in
ClassNotFoundException
Java, most notibly the balinese caste system. For example,
if you are a wesia, use the indian counterpart vaishya.

147
You are a clone. Find the original you, tell him
CloneNotSupportedException
what you want to do and then kill yourself.
You are a burgler that are running a Java program
IllegalAccessException during a burglery. Please finish stealing the computer,
leave the premises and try again.
You have tried to protest against a previous
IllegalArgumentException
exception.
IllegalMonitorStateException Please turn your computer screen back on.
You come from a state that is not yet recognized
IllegalStateException by the UN, possibly Kurdistan or Palestine. Get a real
citizenship, recompile your java code and try again.
One of the screws in your computer is threaded the
IllegalThreadStateException
wrong way. Please contact your hardware vendor.
You have put your index finger in an unacceptable
IndexOutOfBoundsException
place. Reposition it and try again.
Not everything can happen instantly. Please be
InstantiationException
more patient.
Tell your colleagues, room-mates etc. to leave you
InterruptedException
alone while you are working.
You have created an array with negative size. This
can cause information to be lost and in the long run the
NegativeArraySizeException
Universe will be destroyed. Be happy that Java noticed
what you were doing and DON'T DO IT AGAIN.
You are trying to have a picknick on a field that
does not exist. You can also get this exception if you try
NoSuchFieldException to visit an airfield that in fact does exist, but has been
classified as top-secret. I'd give you examples, but then I'd
have to kill you.
Don't use that method! Please, do things like we
NoSuchMethodException
have always done.
You do not own a dog. Get one, for example a
NullPointerException
brittany spaniel, and try again.
You are using outdated units of measurement, for
example inches or pints. Convert to SI. There is a known
NumberFormatException
bug that causes this exception to be thrown if you are very
short or tall.
148
You cannot run fast enough, possibly due to
RuntimeException obesity. Turn off your computer and go out and get som
exercise.
You have been deemed a threat to nationaly
SecurityException security. Please sit still and wait for the authorities to
come and get you.
Your panties have shiften out of place. Adjust
StringIndexOutOfBoundsException them and try again. You can also get this exception if you
are not wearing any panties at all.
You are trying to have an operation that for som
reason, ethical or otherwise, is not supported by Java.
UnsupportedOperationException Examples of this include unneeded amputations, for
example circumcisions. Please stop abusing your body
and do not remove pieces of you child, damn it!

java.util
Someone else has modified your Java code. You
ConcurrentModificationException
should probably change your password.
In order for Java to work, you must have a stack of
EmptyStackException Java books on your desk. Actually, one is enough if it is
really thick.
You are too poor to be using Java. Switch to a
MissingResourceException cheaper language (such as Whitespace, Shakespeare, Cow,
Spaghetti or C#).
There are only four elements (earth, water, air, fire).
NoSuchElementException
The Fifth Element is just a movie.
You are bugged by too many secret organizations.
TooManyListenersException
Expect a SecurityException soon.

java.awt
You are using AWT, which means your GUI will be
AWTException
ugly. This exception is only a warning and can be ignored.
Your layout is ugly, or you have selected a bad font,
FontFormatException
or too many fonts. Please consult a professional designer.
HeadlessException Java thinks you are too stupid to be a programmer.

149
One of your hardware components (e.g. harddrive,
IllegalComponentStateException
CPU, RAM) is broken. Please contact your hardware vendor.

java.awt.color
Your CMM is broken. What ever the hell that is. I usually burn
CMMException
my house down and move to a new city to start over.
Your personal profile contains suspicious information. If you are
ProfileDataException not a communist, terrorist, atheist etc., please contact the CIA to correct
the mistake.

java.awt.datatransfer
You are a bad mime. Noone can understand what you are
MimeTypeParseException trying to express. Try something simpler, like walking-against-
the-wind och being-trapped-in-an-invisible-box.
You are trying to use a flavor that is unknown to Java.
UnsupportedFlavorException
Most people seem to get by using only vanilla and cherry.

java.beans
You are too introverted. Be more extroverted. Stop being such a
IntrospectionException
nerd and go out and meet some people!
One of your properties has been vetoed. The message should
PropertyVetoException inform you of who did it and why. If it does not, you probably
shouldn't ask.

java.io
You have been trying to incinerate something
CharConversionException noncombustible. It is also possible that you have tried turning
yourself into a fish, but that's rare.
You get this exception because you don't know what
EOFException EOF stands for. Well, I'm not going to tell you, Mr
Ignoramus.
FileNotFoundException A carpenter should always know where his tools are.
You have been using IO despite of an earlier
InterruptedIOException
IOException and your activities have been interrupted.

150
InvalidClassException See ClassNotFoundException.
InvalidObjectException Objection overruled, as they say in court.
IO stands for input/output and has to do with sending
IOException and recieving data. IO is a security problem and should not be
used.
This can mean two things. Either something is
inactive and needs to be active, or something is active and
NotActiveException
needs to be inactive. Activate and inactivate things randomly
until things work.
NotSerializableException You are trying to make a TV series based on a movie.
You have issued a stream of objections. Please limit
ObjectStreamException yourself to one at a time and wait for the judge to make a
ruling before issuing a new one. See InvalidObjectException.
You seem to think that some optional data is required.
OptionalDataException
Don't make things harder than they are.
Your data stream is corrupted, which means that it has
StreamCorruptedException
been stealing packages and selling them on the black market.
You have tried to synchronize your failures with
SyncFailedException someone else and you have turned out to be a bigger failure
that that person. Try to find someone on your own level.
If you want to send something coded over the
network, you have to file your encryption key with the NSA.
UnsupportedEncodingException If you don't, you will be regarded as a terrorist and dealt with
in the appropriate way. If you get this exception, you should
run away very fast indeed.
UTF stands for Universal Transmission Format and is
a way of transmitting data that works regardless of which
UTFDataFormatException
format you use. You have tried to transmit data over UTF
using the wrong format.
You need to write the word "aborted" somewhere in
WriteAbortedException your program. It usually doesn't matter where, you just have
to do it.

java.net
BindException Java programming and bondage don't mix.

151
You are trying to connect something to something it cannot
be connected to. Try to connect it to something else. Perhaps it is
ConnectException possible to connect your things to eachother via a special
connection object that connects to both ends of your desired
connection.
You are making an urn and either it has the wrong shape
MalformedURLException (e.g. an "L" shape) or you have misspelled the word "urn" (e.g.
"url").
There is no route to the host. Contact the Road
NoRouteToHostException
Administration.
Ports and harbors must be placed right next to a water body.
PortUnreachableException
If placed inland, they will be unreachable.
This is the result of a serious breach of etiquette (such as
ProtocolException
pukíng on your host). The solution is simple: Don't do that!
You have connected your computer to a power outlet of the
wrong kind. Most of the times you have to find another outlet, but
SocketException
some computers have a switch on the back where you can set the
power outlet type.
You have connected your computer a power outlet with a
SocketTimeoutException timer and the time has run out. Such outlets should only be used for
flat-irons and similar things.
UnknownHostException Didn't your parents teach you to not talk to strangers?
You are trying to access an unknown service. The most
UnknownServiceException
known unknown service is perhaps Secret Service.
The sentence "You are I" is not syntactically correct.
URISyntaxException
Change it to "You are me". What ever the hell that means.

java.rmi
AccessException You are using Microsoft Access. Please don't.
Despite what is stated in the description of
AlreadyBoundException java.net.BindException, RMI does support bondage. However, you
cannot tie up someone that is already bound.
You are trying to connect something to something it cannot be
connected to. Try to connect it to something else. Perhaps it is
ConnectException
possible to connect your things to eachother via a special connection
object that connects to both ends of your desired connection.
152
You are trying to connect something that has to do with IO to
something it cannot be connected to. Try to connect it to something
ConnectIOException else. Perhaps it is possible to connect your things to eachother via a
special connection object that connects to both ends of your desired
connection.
Something is wrong with your marshal. What you should do
depends on what kind of marshal we are talking about. It can be a
MarshalException field marshal, police, firefighter or just your ordinary basic marshal.
Note that this exception has nothing to do with the Republic of the
Marshall Islands, a.k.a. RMI.
You are trying to use an object that does not exist. Create it or
NoSuchObjectException
don't use it, Einstein!
If you are using bondage, please make sure that at least one
NotBoundException
person is tied up.
This is a special exception that is thrown remotely. If
someone else's application has become so instable that it can't even
RemoteException
produce an exception, then you may get the exception instead. Please
find the source and inform that programmer of the error.
The Republic of the Marshall Islands has become instable. If
you live there, you should probably leave and don't come back until
RMISecurityException
your security can be guaranteed. If you live elsewhere, you can
ignore this exception.
ServerException Second serve. (Or double fault if applicable.)
Tennis matches are long enough as it is. You will get this
ServerRuntimeException
exception if you take too long to serve.
When you go to the movies, you should always keep your
StubNotFoundExc
stub. If you don't, and also leave the theater, you will not be let back
eption
in and you may have to buy a new ticket. So, KEEP YOUR STUB!
This exception should come as a total surprise to you. If it did,
UnexpectedException
everything is as it should be.
UnknownHostException Didn't your parents teach you to not talk to strangers?
You have not fullfilled your duties as an officer of the law (or
whatever marshal you used to work as). Note that the correct term is
UnmarshalException
"used to". You have been fired (which is really ironic if you were a
firefighter).

153
java.security
You have lost control of Microsoft Access. If
you cannot regain control or stop the program in some
AccessControlException
other way, you should cut the power to your computer
as fast as possible.
You should be careful with what you eat.
DigestException
Indigestion can be a serious problem.
Something somewhere appears to be unsafe. If
you have the power to do so, you should invade a
GeneralSecurityException
random country (preferably in the middle east). If you
do not have such power, you should at least get a gun.
You have explained your algorithm to a disabled
InvalidAlgorithmParameterException person in a way that is not suited to that person's level
of understanding. Keep it simple!
There are two rather different reasons for this
exception: 1. You are using the wrong key. My advice
is to paint small dots in different colors on your keys to
InvalidKeyException help you remember which one is for which lock. 2. You
are not allowed to lock up disabled people without
giving them a key. If they are smart enough to figure
out how to use it, they have a right to move freely.
You have used a disparaging term to describe a
InvalidParameterException
disabled person.
KeyException Do not try to unlock locks without a key.
You have lost your key. Most likely you left it at
KeyManagementException the office (if you're trying to enter your home) or at
home (if you're trying to enter the office).
The explanation for the previous
KeyStoreException KeyManagementException is that there is a hole in
your pocket.
You are trying to solve a problem in a
previously unknown way. Stop being so damn creative
NoSuchAlgorithmException and rewrite your program using old algorithms. You
can also patent your idea and wait for it to be
incorporated into a future Java release.
NoSuchProviderException If you are a single mom, you cannot be a

154
housewife. First, you need to get a provider for your
family.
You have tried to take an action that you do not
have the privilege to take. For example, getting away
with murder is something that only famous people can
PrivilegedActionException do, child molestation is only for catholic priests and
high ranking jehova's witnesses, and only people with
managerial positions in private corporations are allowed
to steal money.
You are a woman and are trying to be the
provider of a family. Obviously, your husband cannot
ProviderException be a housewife, so you need to let him do the providing.
Thinking that Java is old-fashioned will not change
reality. This is how things work. Deal with it.
Either you have forged someone else's signature,
SignatureException or your signature unacceptable. A signature cannot be
too ugly, too readable or too large.
Damn. You dropped your key down a drain. The
only comfort I can offer is that the key should be
UnrecoverableKeyException
unrecoverable for other people as well, so it may not be
necessary to change your locks.

java.text
ParseException You are not making any sense. Calm down and try again.

Assertion in java

What is Assertion in Java


1.An assertion is a statement in Java that enables you to test your assumptions about your
program.
2.Each assertion contains a Boolean expression that you believe will be true when the assertion
executes.
3.By verifying that the Boolean expression is indeed true, the assertion confirms your
assumptions about the behavior of your program, increasing your confidence that the program is
free of errors.

155
According to Sun, we can use assertion to test our assumption about programs. That means it
validates our program!
In another words we can say that assertions ensures the program validity by catching exceptions
and logical errors. They can be stated as comments to guide the programmer. Assertions are of
two types:

1) Preconditions.
2) Postconditions.

1) Preconditions are the assertions, which invokes when a method is invoked.


2) Postconditions are the assertions, which invokes after a method finishes.

Why use assertions?


Programming by contract
Pre-conditions - Assert precondition as requirement of client
Post-conditions - Assert post-condition as effect of client method

Where to use Assertions


We can use assertions in java to make it more understanding and user friendly, because
assertions can be used while defining preconditions and post conditions of the program. Apart
from this we can use assertions on internal, control flow and class invariants as well… to
improve the programming experience.

Declaring Assertion:
Assertion statements have two form-

The first is:


assert Expression1 ;
Where Expression1 is a boolean expression
When the system runs the assertion,it evaluates Expression1 and if it is false throws an
AssertionError with no details

The second form of the assertion statement is:


assert Expression1 : Expression2 ;
where:
Expression1 is a boolean expression
Expression2 is an expression that has a value
It cannot invoke of a method that is declared void

Complex Assertion Form

156
1.Use the second version of the assert statement to provide a detailed message for the
AssertionError.
2.The system passes the value of Expression2 to the appropriate AssertionError constructor,
which uses the string error message.
3.The purpose of the message is to communicate the reason for the assertion failure.
4.Don’t use assertions to flag user errors—why not?.
When an Assertion Fails
1.Assertion failures are labeled in stack trace with the file and line number from which they were
thrown.
2.Second form of the assertion statement should be used in preference to the first when the
program has some additional information that might help diagnose the failure.

Compiler Directives
For the javac compiler to accept code with assertions, use this command-line option:
-source 1.4
For example: javac -source 1.4 MyClass.java

Performance Problems
Assertions may slow down execution—why?
For example, if an assertion checks to see if the element to be returned is the smallest element in
the list, then the assertion would have to do the same amount of work that the method would
have to do so, assertions may be enabled and disabled. Assertions are, by default, disabled at run-
time. In this case, the assertion has the same semantics as an empty statement.

Arguments
1. no arguments
Enables or disables assertions in all classes except system classes.
2. packageName...
Enables or disables assertions in the named package and any subpackages.
3...
Enables or disables assertions in the unnamed package in the current working directory.
4. className
Enables or disables assertions in the named class .

Enabling Assertions
1.To enable assertions at various granularities, use the -enableassertions, or -ea, switch.
2.To disable assertions at various granularities, use the -disableassertions, or -da, switch
Specify the granularity with the arguments that you provide to the switc.

Here is the code of AssertionExample.java

157
import java.util.*;
import java.util.Scanner;
public class AssertionExample
{
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );

System.out.print( "Enter a number between 0 and 20: " );


int value = scanner.nextInt();
assert( value >= 0 && value <= 20 ) :
"Invalid number: " + value;
System.out.printf( "You have entered %d\n", value );
}
}

In the above example, When the user enters the number scanner.nextInt() method reads the
number from the command line. The assert statement determines whether the entered number is
within the valid range. If the user entered a number which is out of range then the error occurs.

To run the above example,


Compile the example with: javac AssertionExample.java
Assertions are primarily used by the programmer for debugging and identifying logic errors in a
application. By default, assertions are disabled when executing a program because they
reduce performance and are unnecessary for the program’s user. To enable assertions at
runtime, use the -ea command-line option when to the java command. To execute the program in
Fig. 13.9 with assertions enabled, type

java -ea AssertionExample


When you enter the number within range, output will be displayed as:

When you enter the number out of range, output will be:

158
Static Imports

Problem: (pre-J2SE 5.0)


Having to fully qualify every static referenced from external classes

Solution: New import syntax


import static TypeName.Identifier;
import static Typename.*;
Also works for static methods and enums
e.g Math.sin(x) becomes sin(x)

Static Imports Recommendations


Use it when you:
1.Require frequent access to static members from one or two classes
2.Overuse can make your program unreadable and unmaintainable.
3.Import members individually by name, not using *.
4.Organize static imports above regular imports in class definition

Example
1. Static import user defined static fields.
package MyMsg;
public class Msg {
public static final int UPPER = 1;
public static final int LOWER = 2;
public static final int MIXED = 3;
private String msg;
// Display a message in the specified case.
public void showMsg(int how) {
String str;
switch(how) {
case UPPER:
str = msg.toUpperCase();
break;
case LOWER:
str = msg.toLowerCase();

159
break;
case MIXED:
str = msg;
break;
default:
System.out.println("Invalid command.");
return;
}

System.out.println(str);
}
public Msg(String s) { msg = s; }
}

2.Static import user-defined static fields.


import MyMsg.*;
import static MyMsg.Msg.*;
class Test {
public static void main(String args[]) {
Msg m = new Msg("Testing static import.");
m.showMsg(MIXED);
m.showMsg(LOWER);
m.showMsg(UPPER);
}
}

Static Import ////////Fruits.java


package MyConstants;
public class Fruits {
public static int apple = 500;
public static int pear = 501;
public static int orange = 502;
public static int banana = 503;
public static int strawberry = 504;
}
////////////Colors.java
package MyConstants;
public class Colors {
public static int white = 0;
public static int black = 1;
public static int red = 2;
public static int blue = 3;
public static int green = 4;
public static int orange = 5;
public static int grey = 6;
}
160
///////////////////////StaticTest.java
import static MyConstants.Colors.*;
import static MyConstants.Fruits.*;
public class StaticTest {
public static void main(String args[])
{
System.out.println("orange = " + orange);
System.out.println("color orange = " + Colors.orange);
System.out.println("Fruity orange = " + Fruits.orange);
}
}

2. Java static import: old way


public class Hypotenuse {
public static void main(String args[]) {
double side1, side2;
double hypot;
side1 = 3.0;
side2 = 4.0;
hypot = Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the hypotenuse is "
+ hypot);
}
}

3. Use static import to bring sqrt() and pow() into view.


import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
public class Hypot {
public static void main(String args[]) {
double side1, side2;
double hypot;
side1 = 3.0;
side2 = 4.0;
hypot = sqrt(pow(side1, 2) + pow(side2, 2));
System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the hypotenuse is "
+ hypot);
}
}

4. Java static import: System.out and err


import static java.lang.System.err;
import static java.lang.System.out;
import java.io.IOException;
161
import java.io.PrintStream;
public class StaticImporter {
public static void writeError(PrintStream err, String msg)
throws IOException {
// Note that err in the parameter list overshadows the imported err
err.println(msg);
}
public static void main(String[] args) {
out.println("Good morning, " + "java2s");
out.println("Have a day!");
try {
writeError(System.out, "Error occurred.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

5. Static import: sort


import java.util.Arrays;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class SortImporter {
public static void main(String[] args) {
float[] f = new float[] {5, 4, 6, 3, 2, 1};
sort(f);
}
}

6. Java static import enum


import static java.lang.System.out;
import static Grade.*;
import java.io.IOException;
import java.io.PrintStream;
public class EnumImporter {
private Student[] students = new Student[4];
public EnumImporter() {
students[0] = new Student("Brett", "McLaughlin");
students[0].assignGrade(A);
students[1] = new Student("Leigh", "McLaughlin");
students[0].assignGrade(B);
students[2] = new Student("Dean", "McLaughlin");
students[0].assignGrade(C);

students[3] = new Student("Robbie", "McLaughlin");

162
students[0].assignGrade(INCOMPLETE);
}
public void printGrades(PrintStream out) throws IOException {
for (Student student : students) {
if ((student.getGrade() == INCOMPLETE) ||
(student.getGrade() == D)) {
// Make this student retake this class
}
}
}
public static void main(String[] args) {
try {
EnumImporter importer = new EnumImporter();
importer.printGrades(out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
enum Grade { A, B, C, D, F, INCOMPLETE };
class Student {
private String firstName;
private String lastName;
private Grade grade;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return new StringBuffer(firstName)
.append(" ")
.append(lastName)
.toString();
}

163
public void assignGrade(Grade grade) {
this.grade = grade;
}
public Grade getGrade() {
return grade;
}
}

164