Java 1
Java 1
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
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
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;
return 10;
output:
hi I can print
3
DATA TYPES AND TYPE CONVERSION
Variable Identifiers
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 (√)
4
Other:
void
Unused keywords:
const , goto
Reserved literals:
enum
All the key words contains only lower case alphabate symbols
Size(in
Data Type value-range
bits)
Boolean
boolean 1 true or false
Datatype
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.
• 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
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.
2. In case of Interfaces:
For the interfaces the names should be adjective and follows camel case.
3. In case of Methods:
The first letter should be lower case and then normal camel case rules should be used.
6
setCustomerName();
4. In case of variables:
Like methods the camel case format should be used stating with a lower case letter.
5. Constants:
They should be named using upper case letter with unscore (_) is the saperator.
• 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.
• 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.
2. Character Literals
char ch = 'w';
7
Character literals can also be some special characters
char ch = '\r';
3. Integral Literals
int a = 5; // valid.
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.
8
By default, they are of type double.
5. String Literals
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.
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:
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.
Memory Storage
10
When a program is loaded into memory, it is organized into three areas of memory,
called segments:
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
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
long myLongInteger;
int myInteger;
myLongInteger = myInteger;
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:
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
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
6. Boxing conversions
7. Unboxing conversions
8. Unchecked conversions
9. Capture conversions
(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.
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
• 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
Despite the fact that loss of precision may occur, widening conversions among
primitive types never result in a run-time exception. For example,
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.
2. If the floating-point number is NaN , the result of the first step of the
conversion is an int or long 0.
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.
The example:
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.
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.
• 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 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
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:
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:
If one item is a primitive, and the other item is a corresponding wrapper object, then boxing can
occur :
Operation Behavior
20
r of class and type Boolean, such that r.booleanValue() == p
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:
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.
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.
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,
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
As an example, consider an int being stored and then retrieved from an ArrayList:
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);
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):
3. Try not to use any of the comparison operators (<, >, <=, >=, ==, etc) with wrappers.
6. Overloading
Wrapper classes should only be used whenever you absolutely cannot use a primitive.
Otherwise, auto-unbox (de-autobox) the value and use the primitives.
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;
0: bipush 42
5: astore_0
6: aload_0
10: aload_0
14: iadd
15: aload_0
25
16: invokevirtual #3; //Method java/lang/Integer.intValue:()I
19: iadd
20: aload_0
24: iadd
25: aload_0
29: iadd
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.
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:
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:
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:
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
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
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.
28
For (int i = 0; i <10; 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.
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.
Autoboxing and use Auto-Unboxing and do not need any special steps, and all the
compiler will be arranged happen automatically.
Al.add (1);
Because the compiler will quietly convert this code to close this:
And the way to treat an Integer type is the object can be:
Because the compiler will quietly to this code into shape similar to this:
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.
1. The basic types of data used assign types of variables. For example, an int data type
assign an Integer type variables.
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.
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
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;
List 11: Autoboxing operation will be automatically before the upward transition
Int i = 27828;
Long Integer and is not a subclass, so the transformation impossible. If it must be carried out
this operation, a transition needs additional manual:
Int i = 27828;
1. Assign parcel of the basic types of object variables. For instance, one type Integer assign
an int data type variables.
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.
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
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 "+".
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.
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.
Case 'a':
Case 'e':
Case 'i':
Case 'o':
Case 'u':
Break;
Default:
Break;
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);
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
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
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:
2. Not facing basic types of expression to call in the method of parcels. This application will
be rejected completely compiler:
Int i = 1;
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:
Integer i = null;
Integer i = null;
Null and tried to call the method is a virtual machine is not acceptable behavior.
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.
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.
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
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.
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
1. an identity 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.
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.
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 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.
• 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[]:
• an identity 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, 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 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.
Here are some examples of casting conversions of reference types, similar to the example in
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.
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:
The following example uses casts to compile, but it throws exceptions at run
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
Some operators apply unary numeric promotion to a single operand, which must produce a value
of a numeric type:
• 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
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
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:
After the type conversion, if any, value set conversion is applied to each operand.
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
Types of 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.
These can be used as switch case labels, subject, of course, to the usual byte, short, char
and int-only restriction.
or just plain load constants, static finals whose value is not known
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.
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 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:
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 );
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.
The type of c must be same or derived type of “A” other wise violation leads to Compile time
error saying incompatible types .
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:
Examples:
4.Der1 obj5= (Der1) obj4; // not valid (class cast exception at run time)
Der1 , Der2 extends the Base1 class, Der3 , Der4 extends the Base2 class.
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.
} body-of-loop
Here is a loop written as both a for-each loop and a basic for loop.
int sum = 0;
sum += d;
And here is the same loop using the basic for. It requires an extra iteration variable.
57
int sum = 0;
sum += ar[i];
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.
• At least Java 5. Don't use it if you need compatibility with versions before Java 5.
* Improved readability
Limitations:
58
OPERATORS
1) Arithmetic Operators
2) Unary 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)
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
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
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.
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.
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:
Example on | operator
Code:
byte x = 50;
byte y = 51;
byte result = (byte) (x|y);
System.out.println("Result of x|y= : " + result );
00110010
00110011
-------------
00110011
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 );
00110010
00110011
-------------
00000001
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)
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:
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
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;
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.
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...
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:
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:
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 {}
Output:
true
Following are the key points to be remembered while using instanceof operator
Here “instanceof” operator should be used but if both Dog and cat class have method eat then
using “instanceof” operator is useless.
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 );
Output: Value of b is : 30
Value of b is : 20
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.
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
}
}
4. Local Class
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.
or:
Example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
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);
}
}
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.
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.
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 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>
} );
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.
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
ii) Encapsulation
By writing nested classes, we have hidden them from the world and made them
available only to their enclosing class.
i) Inner class
i) Inner class
e) Nested class behaves just like any other member of its enclosing (outer) class.
Inner Class
o We define the term "inner class" to the nested class that is:
82
not a static nested class.
class Inner{
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.
• Since inner class can't stand on its own, we need an instance of its outer class to tie it.
void getS(){
System.out.println(s);
void getInnerS(){
System.out.println(i1.s);
class Inner{
void getS(){
System.out.println(s);
void getOuterS(){
System.out.println(Outer.this.s);
o.getS();
oi.getS();
o.getInnerS();
84
oi.getOuterS();
Output:
Outer string
Inner string
Inner string
Outer string
class InnerTest{
i.seeOuter();
i.seeOuter();
class Outer{
void makeAndSeeInner(){
System.out.println(this);//refers to Outer.this
85
i.seeOuter();
void seeInner(){
void seeOuter(){
System.out.println(this);
System.out.println(s);//Or, this.s
} }
void seeOuter(){
System.out.println(Outer.this.s);
System.out.println(s);
86
void abMethod(){
System.out.println(this);
System.out.println(super.s);
i.seeOuter();
o.makeAndSeeInner();
o.seeInner();
//new Outer().makeAndSeeInner();
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. :)
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.)
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.
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.
We are allowed to declare inner classes with out name ,such type of inner classes are known as
anonymous inner classes.
88
• Anonymous inner class that implements an interface
class Popcorn
System.out.println(“so sweet”);
class Sample
System.out.println(“so spicy”);
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
};
t.start();
System.out.println(“run”);
class Test
t.start();
}}
class Test
System.out.println(“run”);
};
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.
class Sample
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.
• 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:
• 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{
void seeStaticInner(){
System.out.println(StaticInner.s);//OK, s is static
System.out.println(StaticInner.s);
so.seeStaticInner();
System.out.println(s);
class SomeOther{
94
System.out.println(si.s);//'si' is simply a fake! To the end it will be
StaticOuter.StaticInner!
$java StaticOuter$StaticInner
$java SomeOther
95
Constructor
Passing arguments and properties from command line
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 getProperty(<property-name>) method in System class is used to get the value of a property
by specifying the property name as key.
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.
st.modifyStudent(score);
i = i+10;
98
}
The output:
Pass By Reference:
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.
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?
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.
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.
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.
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.
7. Exception list may vary freely. 7. Overriding methods may not throw more
checked exceptions than the overridden
methods.
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.
• 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.
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.
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()
}
}
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();
}
}
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:
• 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.
• 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.
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().
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");
}
}
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.
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.
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 :
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 :
1. final
2. static
3. abstract
4. native
5. transient
6. volatile
7. synchronized
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.
117
• We are missing key benefits of object oriented programming concepts, reusability and
flexibility.
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.
• 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
• 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
class Sub
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.
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.
• The abstract method end with a semi colon. Example: public abstract sample ();
Example:
abstract void draw(); //Note that there are no curly braces here.
void message() {
void draw() {
System.out.println("Circle drawn.");
void draw() {
System.out.println("Cone drawn.");
122
}}
circ.draw();
cone.draw();
cone.message();
}}
The output:
Circle drawn.
Cone drawn.
• 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++;
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
Example:
class NativeEx
static
class Client
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 and strictfp combination is illegal for methods because old languages may not fallow
IEEE 754 standard for floating point.
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
125
Transient Example:
import java.io.*;
int i=10;
int j-20;
System.out.println(t1.i+”----“+t1.j);
oos.writeobject(t1);
//t1.i=1000
//t1.j=2000
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.
A computer may have launched more than one process executing concurrently. This is
called multithreaded programming. The following two modifiers,
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
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.
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:
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:
128
• abstract and synchronized
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
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.
Java.lang.LegalArgumentE
Java.lang.StackOverFl
xception
owError
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
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
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
138
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;
139
Stmt 8;
}
Stmt 9;
}
catch(YException e)
{
Stmt 10;
}
finally
{
Stmt 11;
}
Stmt 12;
‘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”.
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.
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.
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)
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
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.
Declaring Assertion:
Assertion statements have two 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.
157
import java.util.*;
import java.util.Scanner;
public class AssertionExample
{
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
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.
When you enter the number out of range, output will be:
158
Static Imports
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; }
}
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