Java Tutorial For Beginners PDF
Java Tutorial For Beginners PDF
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
NOT EQUAL TO OPERATOR 29 EQUALITY FOR PRIMITIVES ONLY COMPARES VALUES 29 EQUALITY FOR REFERENCE VARIABLES. 29 CONDITIONAL OPERATOR 19 EXAMPLES 19 LOGICAL OPERATORS 30 SHORT CIRCUIT AND OPERATOR - && 30 SHORT CIRCUIT OR OPERATOR - || 30 SHORT CIRCUIT OPERATORS ARE LAZY. 30 OPERATOR & AND | 30 OPERATOR EXCLUSIVE-OR (^) 31 NOT OPERATOR (!) 31 ARRAYS 31 ARRAY BASICS 31 CREATE AN ARRAY 31 LENGTH OF AN ARRAY: PROPERTY LENGTH 33 LOOPING AROUND AN ARRAY - ENHANCED FOR LOOP 33 FILL ARRAY WITH A VALUE 33 ARRAY RULES 33 CROSS ASSIGMENT OF PRIMITIVE ARRAYS IS ILLEGAL 33 2D ARRAYS 33 PRINT ARRAY CONTENT 34
IF ELSE CONDITION 35 IF ELSE EXAMPLE 1 35 IF ELSE EXAMPLE 2: ELSE 36 NESTED IF ELSE EXAMPLE 36 IF ELSE EXAMPLE: WITHOUT BLOCKS 37 NESTED IF ELSE EXAMPLE: GUESS THE OUTPUT 37 NESTED IF ELSE EXAMPLE 2: GUESS THE OUTPUT 37 NESTED IF ELSE EXAMPLE 3: GUESS THE OUTPUT 37 IF ELSE CONDITION SHOULD BE BOOLEAN 38 IF ELSE TRICKY EXAMPLE 38 SWITCH STATEMENT 38 SWITCH STATEMENT EXAMPLE 1 38 SWITCH STATEMENT EXAMPLE 2 NO BREAK 39 SWITCH STATEMENT EXAMPLE 3 FEW BREAKS 39 SWITCH STATEMENT EXAMPLE 4 LETS DEFAULT 40 SWITCH STATEMENT EXAMPLE 5 DEFAULT NEED NOT BE LAST 40 SWITCH STATEMENT EXAMPLE 6 - CHAR, BYTE, SHORT, INT OR ENUM 40 CASE VALUE SHOULD BE A COMPILE TIME CONSTANT. 41 WHILE LOOP 41 WHILE LOOP EXAMPLE 1 41 WHILE LOOP EXAMPLE 2 41 DO WHILE LOOP 41 DO WHILE LOOP EXAMPLE 1 41 DO WHILE LOOP EXAMPLE 2 42 FOR LOOP 42 FOR LOOP EXAMPLE 1 42 FOR LOOP SYNTAX 42 FOR LOOP EXAMPLE 2: COMMA 42 ENHANCED FOR LOOP 43 FOR LOOP EXAMPLE 3: INFINITE LOOP 43 BREAK STATEMENT 43 BREAK STATEMENT EXAMPLE 1 43 BREAK STATEMENT EXAMPLE 2: WHILE LOOP 43 BREAK STATEMENT EXAMPLE 3: INNER LOOPS 44 BREAK STATEMENT EXAMPLE 4: LABELS 44 CONTINUE STATEMENT 44 CONTINUE EXAMPLE 1: FOR LOOP 44
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
ENUM
46
ENUM
EXAMPLE1
46
ENUM
RULES
47
CONVERSION
OF
ENUM
47
ENUM
ORDINAL
47
LOOPING
AROUND
AN
ENUM
47
COMPARING
TWO
ENUMS.
47
ENUM
EXAMPLE
2
48
MORE
ENUM
BASICS
49
SWITCH
STATEMENT
IN
ENUM
49
ENUM
EXAMPLE
3
50
ENUM
CONSTANT
CLASS.
51
INHERITANCE
51
EVERY
CLASS
EXTENDS
OBJECT
CLASS
51
INHERITANCE
EXAMPLE
1
51
INHERITANCE
AND
POLYMORPHISM
53
INSTANCEOF
OPERATOR
54
CLASS,
OBJECT,
STATE
AND
BEHAVIOR
55
CLASS
55
OBJECT
56
STATE
56
BEHAVIOR
56
TOSTRING
METHOD
56
EQUALS
METHOD
57
EQUALS
METHOD
EXAMPLE
57
EQUALS
METHOD
PROPERTIES
58
HASHCODE
METHOD
59
HASHCODE
METHOD
PROPERTIES
59
HASHCODE
METHOD
EXAMPLE
59
ABSTRACT CLASS 59 ABSTRACT CLASS CANNOT BE INSTANTIATED. 60 ABSTRACT CLASS CAN CONTAIN INSTANCE AND STATIC VARIABLES 60 ABSTRACT METHODS 60 ABSTRACT CLASS & NON ABSTRACT METHODS. 60 EXTENDING AN ABSTRACT CLASS 61 A CONCRETE SUB CLASS SHOULD IMPLEMENT ALL ABSTRACT METHODS. 61 AN ABSTRACT SUB CLASS NEED NOT IMPLEMENT ALL ABSTRACT METHODS. 61
CONSTRUCTORS 62 CONSTRUCTOR EXAMPLE 1: DEFAULT CONSTRUCTOR 62 CONSTRUCTOR EXAMPLE 2: CREATING A CONSTRUCTOR 62 CONSTRUCTOR EXAMPLE 3: PROVIDE NO ARGUMENT CONSTRUCTOR 62 CONSTRUCTOR EXAMPLE 4: CALLING A SUPER CLASS CONSTRUCTOR 63 CONSTRUCTOR EXAMPLE 5 63 CONSTRUCTOR EXAMPLE 6: CONSTRUCTOR CANNOT BE DIRECTLY CALLED 64 CONSTRUCTOR EXAMPLE 7: SUPER CLASS CONSTRUCTOR IS INVOKED AUTOMATICALLY 64 CONSTRUCTOR EXAMPLE 8 65 CONSTRUCTOR EXAMPLE 9 65 CONSTRUCTORS ARE NOT INHERITED. 66 COUPLING 67 COUPLING EXAMPLE PROBLEM: 67 COUPLING EXAMPLE SOLUTION: 68 COHESION 69 COHESION EXAMPLE PROBLEM 69 COHESION EXAMPLE SOLUTION 69 ENCAPSULATION 70 ENCAPSULATION APPROACH 1 70 ENCAPSULATION APPROACH 2 70 ENCAPSULATION APPROACH 3 70 ENCAPSULATION EXAMPLE 71 INTERFACE 71 DEFINING AN INTERFACE 71 IMPLEMENTING AN INTERFACE 71 USING THE INTERFACE AND IMPLEMENTATION 72 INTERFACES AND VARIABLES 72 INTERFACES AND METHODS ERROR! BOOKMARK NOT DEFINED. EXTENDING AN INTERFACE 73 INTERFACE THINGS TO REMEMBER 73 METHOD OVERLOADING 73 METHOD OVERLOADING EXAMPLE 1 73 METHOD OVERLOADING EXAMPLE 2 74 OVERLOADING - OTHER RULES 74 METHOD OVERRIDING 74 METHOD OVERRIDING EXAMPLE 1: 74 METHOD OVERRIDING: CANNOT HAVE LESSER VISIBILITY 75 OVERRIDING METHOD CANNOT THROW NEW CHECKED EXCEPTIONS 75 OTHER OVERRIDING RULES 76
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
DEFAULT
CLASS
MODIFIER
EXAMPLES
77
METHOD
AND
VARIABLE
ACCESS
MODIFIERS
78
TWO
ACCESS
MODIFIER
QUESTIONS
78
ACCESS
MODIFIER
EXAMPLE
CLASS
78
DIFFERENT
METHOD
ACCESS
MODIFIERS
79
ACCESS
MODIFIER
EXAMPLE:
CLASS
IN
SAME
PACKAGE
79
ACCESS
MODIFIER
EXAMPLE:
CLASS
IN
DIFFERENT
PACKAGE
80
ACCESS
MODIFIER
EXAMPLE:
SUB
CLASS
IN
SAME
PACKAGE
80
ACCESS
MODIFIER
EXAMPLE:
SUB
CLASS
IN
DIFFERENT
PACKAGE
81
FINAL
MODIFIER
81
FINAL
CLASS
CANNOT
BE
EXTENDED
81
FINAL
METHODS
CANNOT
BE
OVERRIDEN.
82
FINAL
VARIABLE
VALUES
CANNOT
BE
CHANGED.
82
FINAL
ARGUMENTS
VALUE
CANNOT
BE
MODIFIED.
82
OTHER
NON
ACCESS
MODIFIERS
82
STRICTFP
83
VOLATILE
83
STATIC 83 STATIC VARIABLE/METHOD EXAMPLE 83 STATIC VARIABLES AND METHODS EXAMPLE 2 83 STATIC METHODS CANNOT BE OVERRIDDEN 85 LOCAL VARIABLES CANNOT BE DECLARED AS STATIC 85 NATIVE 83 JAVA CLASS CONTENTS 86 INNER CLASSES 86 INNER CLASSES EXAMPLE 86 INNER CLASS EXAMPLE 87 STATIC INNER NESTED CLASS 88 METHOD INNER CLASS 90
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
NUMBER FORMAT 107 FORMAT NUMBER USING DEFAULT LOCALE 107 FORMAT NUMBER USING LOCALE 107 FORMATTING A CURRENCY USING DEFAULT LOCALE 108 FORMAT CURRENCY USING LOCALE 108 PARSING USING NUMBERFORMAT 108 COLLECTION INTERFACES 108 COLLECTION INTERFACE 108 LIST INTERFACE 109 MAP INTERFACE 109 SET INTERFACE 110 SORTEDSET INTERFACE 110 SORTEDMAP INTERFACE 111 QUEUE INTERFACE 111 ITERATOR INTERFACE 112 COLLECTIONS 112 ARRAYLIST 112 SORTING COLLECTIONS 113 LIST OF OBJECTS OF A CUSTOM CLASS 114 CONVERT LIST TO ARRAY 115 CONVERT ARRAY TO LIST 116 OTHER LIST INTERFACE IMPLEMENTATIONS 116 SET INTERFACE 116 HASHSET 116 LINKEDHASHSET 117 TREESET 117 MAP INTERFACE 120 HASHMAP 120 TREEMAP 121 PRIORITYQUEUE 123 ADDING AN ELEMENT INTO PRIORITY QUEUE - OFFER METHOD 123 PEEK METHOD EXAMPLES 123 PRIORITY QUEUE AND COMPARATOR 124 COLLECTIONS STATIC METHODS 124 GENERICS 124 NEED FOR GENERICS EXAMPLE 124 GENERICS EXAMPLE 125
FILES 129 FILE CLASS 129 FILE CLASS - DIRECTORY 130 READ AND WRITE FROM A FILE 131 FILEWRITER AND FILEREADER 131 FILEWRITER CLASS 131 FILEREADER CLASS 131 BUFFEREDWRITER AND BUFFEREDREADER 132 BUFFEREDWRITER CLASS 132 BUFFEREDREADER CLASS 132 PRINTWRITER 133 PRINTWRITER CONSTRUCTORS 133 PRINTWRITER WRITE TO A FILE 133 READING THE FILE CREATED USING BUFFEREDREADER 133 SERIALIZATION 133 IMPLEMENTING SERIALIZABLE INTERFACE 133 SERIALIZING AN OBJECT - EXAMPLE 134 DE-SERIALIZING AN OBJECT EXAMPLE 134 SERIALIZATION TRANSIENT VARIABLES 134 SERIALIZATION READOBJECT METHOD 135 SERIALIZATION WRITEOBJECT METHOD 135 SERIALIZING AN OBJECT CHAIN 135 SERIALIZATION AND INITIALIZATION 137 SERIALIZATION AND STATIC VARIABLES 138 THREADS 138 NEED FOR THREADS 138 CREATING A THREAD CLASS 139 RUNNING A THREAD 140 THREAD EXAMPLE COMPLETE PROGRAM 140 THREAD SYNCHRONIZATION 141 THREADS & SYNCHRONIZED KEYWORD 144 STATES OF A THREAD 145 THREAD PRIORITY 146
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
ASSERT 152 BASIC ASSERT CONDITION EXAMPLE 153 ASSERT WITH DEBUGGING INFORMATION: EXAMPLE 153 ASSERTS - NOT FOR VALIDATION 153 GARBAGE COLLECTION 154 GARBAGE COLLECTION EXAMPLE 154 WHEN IS GARBAGE COLLECTION RUN? 154 GARBAGE COLLECTION IMPORTANT POINTS 154 INITIALIZATION BLOCKS 154 STATIC INITIALIZER 154 INSTANCE INITIALIZER BLOCK 155 JAVA BEAN CONVENTIONS 156 PRIVATE MEMBER VARIABLES 156 NAMING SETTER AND GETTER METHODS 156 LISTENER NAMING CONVENTIONS 157 REGULAR EXPRESSIONS 157 REGULAR EXPRESSION IN JAVA MATCHER AND PATTERN EXAMPLE 157 CREATING REGULAR EXPRESSIONS FOR JAVA 158 REGULAR EXPRESSIONS LOOK FOR REPETITIONS 159 GREEDY REGULAR EXPRESSIONS 159 REGULAR EXPRESSION USING SCANNER CLASS 160 TOKENIZING 160 EXAMPLE METHOD FOR TOKENIZING 160 TOKENIZING USING SCANNER CLASS 161 SCANNER CLASS: OTHER FUNCTIONS 161
Introduction
to
Java
Lets
write
our
first
Java
Program
and
learn
how
to
compile
and
run
it.
System.out.println("Hello
World");
}
}
Lets
talk
about
this
program
line
by
line.
Every
line
of
code
we
write
in
Java
is
part
of
something
called
Class
(more
about
class
later..).
First
line
defines
a
public
class
called
HelloWorld.
All
the
code
in
a
class
is
between
{
and
}.
public
class
HelloWorld
{
When
a
program
runs,
Java
should
know
which
line
of
code
has
to
be
run
first.
main
is
the
first
method
that
is
run
when
a
program
is
run.
main
is
a
method.
We
will
learn
more
about
methods
very
soon.
public
static
void
main(String[]
args)
{
Java
has
a
number
of
pre-defined
classes.
One
of
them
is
System
which
defines
a
method
that
can
write
text
to
console
(or
output).
We
are
calling
the
method
println
passing
text
Hello
World.
System.out.println("Hello
World");
Next are the closing braces. Remember that Java, like any other programming language, is particular about syntax!!
JVM
Lets
look
at
a
video
to
understand
what
the
JVM
does
for
us.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Syntax is <<Name of Class>> instanceName = new <<Name of Class>>(); An instance of a Class is called an object. In above example main method is creating an instance (or a object) of the class ExampleClass1 called example.
Syntax
is
<<RETURN_TYPE>>
<<NAME
OF
METHOD>>
().
After
this
code
of
the
method
goes
between
braces.
(Lets
talk
about
more
complex
syntax
later.)
Invoking
a
method
Look at the code inside the main method. An instance of ExampleClass1 is created and on the instance i.e. example, a method method1 is called.
Syntax of method invocation: <objectname>.methodName(); In the above example example is also called a variable. Lets learn what are the variable types present in Java next.
Variables
What
is
a
variable?
Value of a variable changes over a period of time. Example Program:
public
class
VariablesExample
{
public
static
void
main(String[]
args)
{
int
number;
number
=
5;
System.out.println(number);//5
number
=
number
+
2;
System.out.println(number);//7
number
=
number
+
2;
System.out.println(number);//9
}
}
In the program above the first line is called declaration. We are declaring a variable with name number and of type int. int is a primitive data type in Java which can hold numbers (-1,0,1,2..).
int
number;
The
next
statement
is
called
assignment.
Value
5
is
stored
into
the
variable
number.
number
=
5;
Next
statement
performs
addition
and
assignment.
Variable
number
has
a
value
5
before
this
statement.
Expression
on
the
Right
Hand
Side
is
number+
2.
Value
of
number
+
2
is
5
+
2
=
7;
Value
from
Right
Hand
Side
is
stored
into
the
variable
on
the
Left
Hand
Side
i.e.
number.
So,
7
is
stored
into
number.
number
=
number
+
2;
Value
in
variable
number
initially
was
5,
then
7,
then
9.
Value
keeps
changing.
Value
of
a
variable,
mostly,
changes
over
the
course
of
a
program.
Declaring
Variables
Syntax to declare a variable is
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Java
defines
few
types
like
int
(numbers),
float(floating
point
numbers),
char
(characters).
Variables
of
these
types
store
the
value
of
the
variable
directly.
These
are
not
objects.
These
are
called
primitive
variables.
An
example
is
shown
below:
Primitive Variables contains bits representing the value of the
variable.
int
value
=
5;
Next statement we look at will create a reference variable.
VariablesExample
example
=
new
VariablesExample();
Above statement creates a variable called example. Also new VariablesExample(); creates an object. example is called a reference variable. It stores the reference to the new object created. Reference Variables contains bits representing the way to get to the object in memory.
Primitive
Variables
Different primitive types in java are char, boolean, byte, short, int, long, double, or float. Because of these primitive types, Java is not considered as a pure objected oriented language.
Reference
Variables
As we discussed earlier , Reference Variable is used to refer to an object. (Unless declared as final) you can assign different values to reference variables. public
class
VariablesExample
{
public
static
void
main(String[]
args)
{
VariablesExample
example
=
new
VariablesExample();
example
=
new
VariablesExample();
}
}
In example above, two objects are created using new VariablesExample(). However, only one Reference Variable is created. After the first line in main method (VariablesExample example = new VariablesExample();) example holds reference to first object. After the next line (example = new VariablesExample();) example holds the reference to Second object.
Primitive
Variables
Different
primitive
types
in
java
are
char, boolean, byte, short, int, long, double, or float.
Because
of
these
primitive
types,
Java
is
not
considered
as
a
pure
objected
oriented
language.
Numeric
Data
Types
Examples
Lets
look
at
a
few
variable
declarations
and
initializations
for
numberic
data
types.
We
will
look
at
each
one
of
them
in
detail
later.
int
i
=
15;
long
longValue
=
1000000000000l;
byte
b
=
(byte)254;
float
f
=
26.012f;
double
d
=
123.567;
Examples
char
ch
=
'a';
char
ch2
=
';';
Identifiers
Names given to a class, method, interface, variables are called identifiers.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Literals
Any primitive data type value in source code is called Literal. There are four types of literals: 1. Integer & Long 2. Floating Point 3. Boolean 4. Double
Integer
Literal
There are 3 ways of representing an Integer Literal. 1. Decimal 2. Octal 3. Hexadecimal Decimal Examples: 343, 545 Octal Octal numbers use digits from 0 to 7. To represent a number in octal format, place zero in front of number. Octal Examples: int eight = 010; int nine=011; int invalid = 089;//COMPILER ERROR! 8 and 9 are invalid Hexadecimal Hex Numbers use characters - 0 to 9 and A to F. A TO F represent 10-15. Code Example: int sixteen = 0x10; int fifteen = 0XF; int fourteen = 0xe; Hexadecimal literal is case insensitive. i.e 0xabc is same as 0XABC You cannot represent numbers using formatting as literals. Code Example: int x = 23,000;//COMPILER ERROR! An integer literal by default is int.
Long
Literals
All 3 integer formats: Decimal, Octal and Hexadecimal can be used to represent long by appending with L or l. Long Examples: long a = 123456789l; long b = 0x9ABCDEFGHL; long c = 0123456789L;
Boolean
Literals
Valid boolean values are true and false. TRUE, FALSE or True, False are invalid. Examples: 1. boolean b = true; boolean b=false; 2. boolean b = TRUE;//COMPILATION ERROR 3. boolean b = 0; //COMPILER ERROR. This is not C Language
Character
Literals
1. 2. 3. 4. 5. Represented by single character between single quotes Example: char a = 'a' Unicode Representation also can be used. Prefix with \u. Example: char letterA = '\u0041'; A number value can also be assigned to character. Example: char letterB = 66; Numeric value can be from 0 to 65535; Example: char ch1 = 66000; //COMPILER ERROR! Escape code can be used to represent a character that cannot be typed as literal. Example: char newLine = '\n';
Assignment
Assignment
operator
evaluates
the
expression
on
the
right
hand
side
and
copies
the
value
into
the
variable
on
the
left
hand
side.
Consider
the
examples
below:
Assignment
Examples
int
value
=
35;//35
is
copied
into
35
int
squareOfValue
=
value
*
value;//value
*
value
=
35
*
35
is
stored
into
squareOfValue
int
twiceOfValue
=
value
*
2;
This
can
be
read
as
copy
the
value
of
a1
into
b1.
The
bit
pattern
in
a1
is
copied
into
b1.
b1 = a1;
If we change a1 or b1 after this, it would not change the other variable. a1 = 10;//b1 will remain 6
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Casting
Casting is used when we want to convert on data type to another. There are two types of Casting Implicit Casting Explicit Casting
Implicit
Casting
Implicit Casting is done by the compiler. Example: Widening Conversions i.e. storing smaller values in larger variable types. int
value
=
100;
long
number
=
value;
//Implicit
Casting
float
f
=
100;
//Implicit
Casting
Explicit
Casting
Explicit Casting is done through code. Example: Narrowing Conversions. Storing larger values into smaller variable types; long
number1
=
25678;
int
number2
=
(int)number1;//Explicit
Casting
//int
x
=
35.35;//COMPILER
ERROR
int
x
=
(int)35.35;//Explicit
Casting
Explicit casting would cause truncation of value if the value stored is greater than the size of the variable. int
bigValue
=
280;
byte
small
=
(byte)
bigValue;
System.out.println(small);//output
24.
Only
8
bits
remain.
Reference
Variable
Assignments
Example
of
reference
variable
assignment
below:
Actor
actor2
=
actor1;
copies
the
address
of
the
object
referred
by
actor1
into
actor2.
Actor
actor1
=
new
Actor();
actor1.setName("Actor1");
//This
creates
//
new
reference
variable
actor1
of
type
Actor
//
new
Actor()
on
the
heap
//
assigns
the
new
Actor
on
the
heap
to
reference
variable
Actor
actor2
=
actor1;
actor2.setName("Actor2");
System.out.println(actor1.getName());//Actor2
Compound
Assignment
Operators
Operators
like
+=,
-=,
*=
are
called
Compound
Operators.
Examples
are
shown
below:
int
a
=
5;
a
+=
5;
//similar
to
a
=
a
+
5;
a
*=
10;//similar
to
a
=
a
*
10;
a
-=
5;//similar
to
a
=
a
-
5;
a
/=
5;//similar
to
a
=
a
/
5;
Remainder(%)
Operator
Remainder when one number is divided by another. System.out.println(10
%
4);//2
System.out.println(15
%
4);//3
Conditional
Operator
Conditional Operator is a Ternary Operator (3 Operands)
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Types
of
Variables
Types: Static, Member (or instance), Local, Block
Instance
Variable
Declared inside a class outside any method. Each instance of the class would have its own values. Also called member value, field or property.
Local
Variable
Variables declared in a method Local Variables can only be marked with final modifier If the name of a Local Variable is same as the name of an instance variable, it results in shadowing.
Member
Variable
Defined at class level and without keyword static.
Static
Variable
Defined at class level and using keyword static.
Scope
of
a
Variable
Scope
of
a
variable
defines
where
(which
part
of
code)
the
value
of
variable
can
be
accessed.
JAVA
SPRING,
STRUTS,
AJAX
&
MORE
-
Videos,
Interview
Questions,
Projects
ON
RITHUS.COM
Important
Rules
Static Variable can be used anywhere in the class. Member Variable can be used in any non-static method. Local Variable can be used only in the method where it is declared. Block Variable can be used only in the block (code between { and }) where it is declared.
Scope Example 1 staticVariable is declared using keyword static.It is available in the instance method method1 and static method named staticMethod. Scope Example 2 memberVariable is declared directly in the class and does NOT use keyword static. So, it is an instance variable. It is available in the instance method method1 but not accessible in the static method named staticMethod.
Scope Example 3 method1LocalVariable is declared in the method method1. So, it is a local variable. It is available in the instance method method1 but available in any other instance or static methods.
Scope Example 4 blockVariable is declared in a block in method1. So, it is a block variable. It is available only in the block where it is defined. It is not accessible any where out side the block even in the same method.
Variable
Initialization
Initialization defines the first value that is assigned to a variable if a value is not assigned.
Important
Rules
Member/Static variables are alway initialized with default values. Default values for numeric types is 0, floating point types is 0.0, boolean is false, char is '\u0000' and for a object reference variable is null. Local variables are not initialized by default by compiler. If local variables are used before they are initialized, it would result in Compilation Error. Assigning a null value is a valid initialization for reference variables.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Initialization Example 1 player is an instance of the class Player. It contains member variables named name and score. All member variables are initialized by default. Since name refers to a String i.e a reference variable it is initialized to null. score is an int variable and hence initialized to 0. Initialization Example 2 local is a local variable defined in the main method. An attempt to access a local variable without initialization would result in a compilation error. Same is the case with value1 which is a String local variable. If null is assigned to a reference variable, reference variable is considered to be assigned.
Wrapper
Classes
A primitive wrapper class in the Java programming language is one of eight classes provided in the java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper classes in Java are immutable.
Wrapper: Boolean,Byte,Character,Double,Float,Integer,Long,Short Primitive: boolean,byte,char ,double, float, int , long,short Wrapper classes are final and immutable.
b
=
false;
xxxValue
methods
xxxValue methods help in creating primitives
Integer
integer
=
Integer.valueOf(57);
int
primitive
=
seven.intValue();//57
float
primitiveFloat
=
seven.floatValue();//57.0f
Float
floatWrapper
=
Float.valueOf(57.0f);
int
floatToInt
=
floatWrapper.intValue();//57
float
floatToFloat
=
floatWrapper.floatValue();//57.0f
parseXxx
methods
parseXxx methods are similar to valueOf but they return primitive values int
sevenPrimitive
=
Integer.parseInt("111",
2);//binary
111
is
converted
to
7
int
hundredPrimitive
=
Integer.parseInt("100");//100
is
stored
in
variable
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Boxing
and
new
instances
Auto
Boxing
helps
in
saving
memory
by
reusing
already
created
Wrapper
objects.
However
wrapper
classes
created
using
new
are
not
reused.
Two
wrapper
objects
created
using
new
are
not
same
object.
Integer
nineA
=
new
Integer(9);
Integer
nineB
=
new
Integer(9);
System.out.println(nineA
==
nineB);//false
System.out.println(nineA.equals(nineB));//true
String
A String class can store a sequence of characters. String is not a primitive in Java but a Class in its own right.
Note
that
the
value
of
str3
is
not
modified
in
the
above
example.
The
result
should
be
assigned
to
a
new
reference
variable
(or
same
variable
can
be
reused).
String
concat
=
str3.concat("value2");
System.out.println(concat);
//value1value2
Following
statement
creates
1
string
object
(created
on
the
pool)
and
1
reference
variable.
String
str1
=
"value";
However,
if
new
operator
is
used
to
create
string
object,
the
new
object
is
created
on
the
heap.
Following
piece
of
code
create
2
objects.
//1.
String
Literal
"value"
-
created
in
the
"String
constant
pool"
//2.
String
Object
-
created
on
the
heap
String
str2
=
new
String("value");
String
Manipulation
methods
Most
important
thing
to
remember
is
a
String
object
cannot
be
modified.
When
any
of
these
methods
are
called,
they
return
a
new
String
with
the
modified
value.
The
original
String
remains
unchanged.
//String
concat(String
paramString)
System.out.println(str.concat("lmn"));//abcdefghijklmn
//String
replace(char
paramChar1,
char
paramChar2)
System.out.println("012301230123".replace('0',
'4'));//412341234123
//String
replace(CharSequence
paramCharSequence1,
CharSequence
paramCharSequence2)
System.out.println("012301230123".replace("01",
"45"));//452345234523
System.out.println("ABCDEFGHIJ".toLowerCase());
//abcdefghij
System.out.println("abcdefghij".toUpperCase());
//ABCDEFGHIJ
//trim
removes
leading
and
trailings
spaces
System.out.println("
abcd
".trim());
//abcd
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Increment
Operators
Pre increment statement returns value after increment. Post increment statement returns value before increment int
i
=
25;
int
j
=
++i;//i
is
incremented
to
26,
assigned
to
j
System.out.println(i
+
"
"
+
j);//26
26
i
=
25;
j
=
i++;//i
value(25)
is
assigned
to
j,
then
incremented
to
26
System.out.println(i
+
"
"
+
j);//26
25
Decrement
Operators
Decrement Operators are similar to increment operators. i
=
25;
j
=
--i;//i
is
decremented
to
24,
assigned
to
j
System.out.println(i
+
"
"
+
j);//24
24
i
=
25;
j
=
i--;//i
value(25)
is
assigned
to
j,
then
decremented
to
24
System.out.println(i
+
"
"
+
j);//24
25
Relational
Operators
Relation
Operators
are
used
to
compare
operands.
They
a
always
return
true
or
false.
List
of
Relation
Operators
include
<,
<=,
>,
>=,
==,
and
!=.
Lets
consider
a
few
examples
of
relational
operators.
Lets
assume
a
int
variable
named
number
with
a
value
7.
int
number
=
7;
is
equal
to
operator
System.out.println(number
==
7);//true
System.out.println(number
==
9);//false
==
(equals)
operator
Lets
look
at
how
==
equals
operator
works
with
primitives
and
reference
variables.
Primitive
Variables
Equality
for
Primitives
only
compares
values
int
a
=
5;
int
b
=
5;
Reference
Variables
Integer
aReference
=
new
Integer(5);
Integer
bReference
=
new
Integer(5);
For
reference
variables,
==
compares
if
they
are
refering
to
the
same
object.
System.out.println(aReference
==
bReference);//false
bReference
=
aReference;
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Logical
Operators
Logical
Operators
are
&&,
||,
|,
&,
!
and
^.
Arrays
Arrays allow storing multiple values of same type.
Array
Basics
Lets discuss about basics of declaring and creating an Array.
Declare
an
Array
All
below
ways
are
legal.
However,
using
the
third
format
of
declaration
is
recommended.
int
marks[];
//Not
Readable
int[]
runs;
//Not
Readable
int[]
temperatures;//Recommended
Creating
an
array
marks
=
new
int[5];
//
5
is
size
of
array
Once
An
Array
is
created,
its
size
cannot
be
changed.
Declaring
and
creating
an
array
in
same
line.
int
marks2[]
=
new
int[5];
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Default
Values
byte,short,int,long
0
float,double
0.0
boolean
false
object
null
Assigning
values
to
an
array
Index
of
elements
in
an
array
runs
from
0
to
length
1.
We
can
use
the
index
of
an
element
to
store
a
value
into
an
array.
marks[0]
=
25;
marks[1]
=
30;
marks[2]
=
50;
marks[3]
=
10;
marks[4]
=
5;
Array
Rules
Array
can
contain
only
values
of
same
type.
//COMPILE
ERROR!!
//int
marks4[]
=
{10,15.0};
//10
is
int
15.0
is
float
2D
Arrays
Lets
create
a
matrix
with
2
rows
and
3
columns.
int[][]
matrix
=
{
{
1,
2,
3
},
{
4,
5,
6
}
};
int[][]
matrixA
=
new
int[5][6];
First
dimension
is
necessary
to
create
a
2D
Array.
Best
way
to
visualize
a
2D
array
is
as
an
array
of
arrays.
matrixA
=
new
int[3][];//FINE
//matrixA
=
new
int[][5];//COMPILER
ERROR
//matrixA
=
new
int[][];//COMPILER
ERROR
Ragged
2D
Array
Each
row
in
a
2D
Array
can
have
a
different
size.
This
is
called
a
Ragged
Array.
matrixA
=
new
int[3][];//FINE
matrixA[0]
=
new
int[3];
matrixA[0]
=
new
int[4];
matrixA[0]
=
new
int[5];
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Printing
a
2D
Array
int[][]
matrix3
=
{
{
1,
2,
3
},
{
4,
5,
6
}
};
System.out.println(matrix3);
//[[I@1d5a0305
System.out.println(
Arrays.toString(matrix3));
//[[I@6db3f829,
[I@42698403]
System.out.println(
Arrays.deepToString(matrix3));
//[[1,
2,
3],
[4,
5,
6]]
matrix3[0]
is
a
1D
Array
System.out.println(matrix3[0]);//[I@86c347
System.out.println(
Arrays.toString(matrix3[0]));//[1,
2,
3]
Comparing
Arrays
Arrays
can
be
compared
using
static
method
equals
defined
in
Arrays
class.
Two
arrays
are
equal
only
if
they
have
the
same
numbers
in
all
positions
and
have
the
same
size.
int[]
numbers1
=
{
1,
2,
3
};
int[]
numbers2
=
{
4,
5,
6
};
System.out.println(Arrays
.equals(numbers1,
numbers2));
//false
int[]
numbers3
=
{
1,
2,
3
};
System.out.println(Arrays
.equals(numbers1,
numbers3));
//true
Sorting
an
Array
Arrays
can
be
sorted
using
static
utility
method
sort
defined
in
Arrays
class.
Array
of
Objects
Person[]
persons
=
new
Person[3];
Creating
an
array
of
Persons
creates
4
Reference
Variables
to
Person.
It
does
not
create
the
Person
Objects
System.out.println(persons[0]);//null
Another
Example
Person[][]
persons2D
=
{
{
new
Person(),new
Person(),new
Person()},
{
new
Person(),new
Person()}
};
If
Else
Condition
If
else
is
used
to
conditionally
execute
code.
Code
inside
If
is
executed
only
if
the
condition
is
true.
if(true){
System.out.println("Will
be
printed");
}
If
Else
Example
1
int
x
=
5;
if(x==5){
System.out.println("x
is
5");//executed
since
x==5
is
true
}
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Output is 2. Once a condition in nested-if-else is true the rest of the code is not executed.
Output is "l<20" followed by "Who am I?" on next line. else belong to the last if before it unless brackets ({}) are used.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Switch
Statement
A switch statement is used when we have to choose between a list of options. Lets look at a few examples of Switch Statements and understand it more.
Output of above example is 2.The case which is matched is executed. In the above example, there is a break statement in every case. Also, there is a case named default. We will understand them more in the next examples.
Since there is no break after case 2, execution falls through to case 3. There is no break in case 3 as well. So, execution falls through to default. Rule: Code in switch is executed from a matching case until a break or end of switch statement is encountered.
Program Output Number is 2 or 3. Case 2 matches. Since there is no code in case 2, execution falls through to case 3, executes the println. Break statement takes execution out of the switch
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Code
Output
Default
Example
Output
Default
While
Loop
A loop is used to run same code again and again. Lets look at an example of while loop.
Program
Output
01234
While count is less than 5, code in the while loop is executed. Count starts at 0 and incremented to 1,2,3,4 and 5. When count is 5, the while condition (count < 5) turns to be false. So, execution stops when count is 5. Output printed is 01234.
In above example, count is initialized to 5. While loop checks for the condition count < 5. Since this condition is false at the outset, the code in while is never executed.
Do
While
Loop
do
while
also
is
used
when
it
is
not
clear
how
many
times
loop
has
to
be
executed.
However,
the
difference
between
a
while
and
a
do
while
is
that
the
code
in
do
while
is
executed
at
least
once.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
In a do while loop, condition check occurs after the code in loop is executed once.
For
Loop
For loop is used to loop code specified number of times.
Code
Output
0123456789
Example
Output
12345
Result:
Infinite
loop
=>
Loop
executes
until
the
program
is
terminated.
Break
Statement
Break statement breaks out of a loop
Program
Output
012345
Even though the for loop runs from 0 to 10, execution stops at i==5 because of the break statement. Break statement stops the execution of the loop and takes execution to the first statement after the loop.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Code
Output
012345
Program
Output
000102030405101112131415
Each time the value of k is 5 the break statement is executed. The break statement takes execution out of the k loop and proceeds to the next value of j.
Program
Output
000102030405
Continue
Statement
Continue
statement
skips
rest
of
the
statements
in
the
loop
and
starts
next
iteration
continue;
}
System.out.print(i);
}
Output
012346789
Note that the output does not contain 5. When i==5 continue is executed. Continue skips rest of the code and goes to next loop iteration. So, the print statement is not executed when i==5.
Program
Output
1234678910
Code
Output
000102030406070809101112131416171819
When k==5 the print statement in the loop is skipped due to continue. So 05 and 05 are not printed to the console.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Example
Output
00010203041011121314
This examples uses a continue statement with label. When k==5 is true, continue outer is called. So, when value of k is 5, the loop skips to the next iteration of j.
Enum
Enum allows specifying a list of values for a Type. Consider the example below. It declares an enum Season with 4 possible values.
enum
Season
{
WINTER,
SPRING,
SUMMER,
FALL
};
Enum
Example1
Consider the example below:
package
com.rithus.enums;
//Enum
can
be
declared
outside
a
class
enum
SeasonOutsideClass
{
WINTER,
SPRING,
SUMMER,
FALL
};
public
class
Enum
{
//Enum
can
be
declared
inside
a
class
enum
Season
{
WINTER,
SPRING,
SUMMER,
FALL
};
public
static
void
main(String[]
args)
{
/*//Uncommenting
gives
compilation
error
//enum
cannot
be
created
in
a
method
enum
InsideMethodNotAllowed
{
WINTER,
SPRING,
SUMMER,
FALL
};
*/
//Converting
String
to
Enum
Season
season
=
Season.valueOf("FALL");
//Converting
Enum
to
String
System.out.println(season.name());//FALL
//Default
ordinals
of
enum
//
By
default
java
assigns
ordinals
in
order
System.out.println(Season.WINTER.ordinal());//0
System.out.println(Season.SPRING.ordinal());//1 System.out.println(Season.SUMMER.ordinal());//2 System.out.println(Season.FALL.ordinal());//3 //Looping an enum => We use method values for (Season season1: Season.values()) { System.out.println(season1.name()); //WINTER SPRING SUMMER FALL (separate lines) } //Comparing two Enums Season season1 = Season.FALL; Season season2 = Season.FALL; System.out.println(season1 == season2);//true System.out.println(season1.equals(season2));//true } }
Enum
Rules
Enums can be declared in a separate class(SeasonOutsideClass) or as member of a class(Season). Enums cannot be declared in a method.
Conversion
of
Enum
Function valueOf(String) is used to convert a string to enum.
//Converting
String
to
Enum
Season
season
=
Season.valueOf("FALL");
Function name() is used to find String value of an enum.
//Converting
Enum
to
String
System.out.println(season.name());//FALL
Enum
Ordinal
Java assigns default ordinals to an enum in order. However, it is not recommended to use ordinals to perform logic.
//Default
ordinals
of
enum
//
By
default
java
assigns
ordinals
in
order
System.out.println(Season.WINTER.ordinal());//0
System.out.println(Season.SPRING.ordinal());//1
System.out.println(Season.SUMMER.ordinal());//2
System.out.println(Season.FALL.ordinal());//3
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Enum
Example
2
package
com.rithus.enums;
public
class
EnumAdvanced
{
//Enum
with
a
variable,method
and
constructor
enum
SeasonCustomized
{
WINTER(1),
SPRING(2),
SUMMER(3),
FALL(4);
//variable
private
int
code;
//method
public
int
getCode()
{
return
code;
}
//Constructor-only
private
or
(default)
//modifiers
are
allowed
SeasonCustomized(int
code)
{
this.code
=
code;
}
//Getting
value
of
enum
from
code
public
static
SeasonCustomized
valueOf(int
code)
{
for
(SeasonCustomized
season:
SeasonCustomized
.values())
{
if
(season.getCode()
==
code)
return
season;
}
throw
new
RuntimeException("value
not
found");//
Just
for
kicks
}
//Using
switch
statement
on
an
enum
public
int
getExpectedMaxTemperature()
{
switch
(this)
{
case
WINTER:
return
5;
case
SPRING:
case
FALL:
return
10;
case
SUMMER:
return
20;
}
return
-1;//
Dummy
since
Java
does
not
recognize
this
is
possible
}
};
public
static
void
main(String[]
args)
{
SeasonCustomized
season
=
SeasonCustomized.WINTER;
/*//Enum constructor cannot be invoked directly //Below line would cause COMPILER ERROR SeasonCustomized season2 = new SeasonCustomized(1); */ System.out.println(season.getCode());//1 System.out.println(season .getExpectedMaxTemperature());//5 System.out.println(SeasonCustomized.valueOf(4));//FALL } }
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Enum
Example
3
Consider the example below:
package
com.rithus.enums;
public
class
EnumAdvanced2
{
//Enum
with
a
variable,method
and
constructor
enum
SeasonCustomized
{
WINTER(1)
{
public
int
getExpectedMaxTemperature()
{
return
5;
}
},
SPRING(2),
SUMMER(3)
{
public
int
getExpectedMaxTemperature()
{
return
20;
}
},
FALL(4);
//variable
private
int
code;
//method
public
int
getCode()
{
return
code;
}
//Constructor-only
private
or
(default)
//modifiers
are
allowed
SeasonCustomized(int
code)
{
this.code
=
code;
}
public
int
getExpectedMaxTemperature()
{
return
10;
}
};
public
static
void
main(String[]
args)
{
SeasonCustomized
season
=
SeasonCustomized.WINTER;
System.out.println(season
.getExpectedMaxTemperature());//5
System.out.println(SeasonCustomized.FALL
.getExpectedMaxTemperature());//10 } }
Inheritance
Inheritance allows extending a functionality of a class and also promotes reuse of existing code.
Inheritance
Example
1
Consider the example class Actor below:
public
class
Actor
{
public
void
act(){
System.out.println("Act");
};
}
We can extend this class by using the keyword extends. Hero class extends Actor.
//IS-A
relationship.
Hero
is-a
Actor
public
class
Hero
extends
Actor
{
public
void
fight(){
System.out.println("fight");
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
However, we can create an Inheritance Chain class
Pet
extends
Animal
{
}
class
Dog
extends
Pet
{
}
Lets
create
two
new
sub
classes
of
Animal
overriding
the
existing
shout
method
in
Animal.
class
Cat
extends
Animal
{
public
String
shout()
{
return
"Meow
Meow";
}
}
class
Dog
extends
Animal
{
public
String
shout()
{
return
"BOW
BOW";
}
public
void
run(){
}
}
Look
at
the
code
below.
An
instance
of
Animal
class
is
created.
shout
method
is
called.
Animal
animal1
=
new
Animal();
System.out.println(
animal1.shout());
//Don't
Know!
Look
at
the
code
below.
An
instance
of
Dog
class
is
created
and
store
in
a
reference
variable
of
type
Animal.
Animal
animal2
=
new
Dog();
//Reference
variable
type
=>
Animal
//Object
referred
to
=>
Dog
//Dog's
bark
method
is
called.
System.out.println(
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
When
shout
method
is
called
on
animal2,
it
invokes
the
shout
method
in
Dog
class
(type
of
the
object
pointed
to
by
reference
variable
animal2).
Even
though
dog
has
a
method
run,
it
cannot
be
invoked
using
super
class
reference
variable.
//animal2.run();//COMPILE
ERROR
instanceof
Operator
Let us consider the following class and interface declarations: class
SuperClass
{
};
class
SubClass
extends
SuperClass
{
};
interface
Interface
{
};
class
SuperClassImplementingInteface
implements
Interface
{
};
class
SubClass2
extends
SuperClassImplementingInteface
{
};
class
SomeOtherClass
{
};
instanceof
operators
checks
if
an
object
is
of
a
particular
type.
Lets
consider
the
code
below.
We
create
a
few
instances
of
the
classes
declared
above.
SubClass
subClass
=
new
SubClass();
Object
subClassObj
=
new
SubClass();
SubClass2
subClass2
=
new
SubClass2();
SomeOtherClass
someOtherClass
=
new
SomeOtherClass();
Lets
now
run
instanceof
operator
on
the
different
instances
created
earlier.
System.out.println(subClass
instanceof
SubClass);//true
System.out.println(subClass
instanceof
SuperClass);//true
System.out.println(subClassObj
instanceof
SuperClass);//true
System.out.println(subClass2
instanceof
SuperClassImplementingInteface);//true
instanceof
can
be
used
with
interfaces
as
well.
Since
Super
Class
implements
the
interface,
below
code
prints
true.
System.out.println(subClass2
instanceof
Interface);//true
Class
A class is a Template. In above example, Class CricketScorer is the template for creating multiple objects. A class defines state and behavior that an object can exhibit.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Object
An instance of a class. In the above example, we create an object using new
CricketScorer(). The reference of the created object is stored in scorer variable. We can create multiple objects of the same class.
State
Values assigned to instance variables of an object. Consider following code snippets from the above example. The value in score variable is initially 0. It changes to 6 and then 10. State of an object might change with time.
scorer.six();
//State
of
scorer
is
(score
=>
6)
scorer.four();
//State
of
scorer
is
(score
=>
10)
Behavior
Methods supported by an object. Above example the behavior supported is six(), four() and getScore().
toString
method
Consider the class given below: class
Animal
{
public
Animal(String
name,
String
type)
{
this.name
=
name;
this.type
=
type;
}
String
name;
String
type;
}
Run this piece of code: Animal
animal
=
new
Animal("Tommy",
"Dog");
System.out.println(animal);//com.rithus.Animal@f7e6a96
Output does not show the content of animal (what name? and what type?). To show the content of the animal object, we can override the default implementation of toString method provided by Object class.
public String toString() { return "Animal [name=" + name + ", type=" + type + "]"; } } Run this piece of code: Animal animal = new Animal("Tommy","Dog"); System.out.println(animal);//Animal [name=Tommy, type=Dog] Output now shows the content of the animal object.
equals
method
Default implementation of equals method is defined in Object class. The implementation is similar to == operator. Two object references are equal only if they are pointing to the same object. We need to override equals method, if we would want to compare the contents of an object
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Let's now provide an implementation of equals which satisfy these properties: //Client class @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Client other = (Client) obj; if (id != other.id) return false; return true; }
hashCode
method
HashCode's are used in hashing to decide which group (or bucket) an object should be placed into. A group of object's might share the same hashcode. The implementation of hash code decides effectiveness of Hashing. A good hashing function evenly distributes object's into different groups (or buckets).
Abstract
Class
An
abstract class cannot be instantiated. Lets understand about an Abstact class with examples. JAVA
SPRING,
STRUTS,
AJAX
&
MORE
-
Videos,
Interview
Questions,
Projects
ON
RITHUS.COM
Abstract
Methods
An Abstract method does not contain body.
//Abstract
Class
can
contain
0
or
more
abstract
methods
//Abstract
method
does
not
have
a
body
abstract
void
abstractMethod1();
abstract
void
abstractMethod2();
Abstract
method
-
Only
in
Abstract
Class.
Abstract
method
can
be
declared
only
in
Abstract
Class.
In
the
example
below,
abstractMethod()
gives
a
compiler
error
because
NormalClass
is
not
abstract.
class
NormalClass{
abstract
void
abstractMethod();//COMPILER
ERROR
}
abstract void abstractMethod2(); //Abstract Class can contain 0 or more non-abstract methods public void nonAbstractMethod(){ System.out.println("Non Abstract Method"); } public static void main(String[] args) { //An abstract class cannot be instantiated //Below line gives compilation error if uncommented //AbstractClassExample ex = new AbstractClassExample(); } }
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Constructors
Constructor is invoked whenever we create an instance(object) of a Class. We cannot create an object without a constructor. If we do not provide a constructor, compiler provides a default no-argument constructor.
// This is called a one argument constructor. public Animal(String name) { this.name = name; } public static void main(String[] args) { // Since we provided a constructor, compiler does not // provide a default constructor. // Animal animal = new Animal();//COMPILER ERROR! // The only way we can create Animal1 object is by using Animal animal = new Animal("Tommy"); } }
Constructor
Example
5
Member variables/methods should not be used in constructor calls (super or this). Static variables or methods can be used. public
Animal()
{
//member
variable
cannot
be
used
in
a
constructor
call
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Program
Output
Animal Constructor Dog Constructor Labrador Constructor It is almost as if super() method is invoked as the first line of every constructor. The example code below shows how the code above behaves.
class Animal { public Animal() { super();// IMPLICIT CALL System.out.println("Animal Constructor"); } } class Dog extends Animal { public Dog() { super();// IMPLICIT CALL System.out.println("Dog Constructor"); } } class Labrador extends Dog { public Labrador() { super();// IMPLICIT CALL System.out.println("Labrador Constructor"); } }
Constructor
Example
8
Since a subclass constructor explicitly calls a super class constructor with no arguments, this can cause a few compiler errors. Let's look at an example. class
Animal
{
String
name;
public
Animal(String
name)
{
this.name
=
name;
System.out.println("Animal
Constructor");
}
}
class
Dog
extends
Animal
{
public
Dog()
{
//
COMPILER
ERROR!
No
constructor
for
Animal()
System.out.println("Dog
Constructor");
}
}
public Dog() makes an implicit super() call i.e. a call to Animal() (no argument) constructor. But no such constructor is defined in Animal class.
Constructor
Example
9
Similar example below except that the Dog no argument constructor is not provided by programmer. However, the compiler would give the no argument constructor, which would invoke super() method. This would again result in a compilation error. class
Animal
{
String
name;
public
Animal(String
name)
{
this.name
=
name;
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
new Dog("Terry") is not allowed even though there is a constructor in the super class Animal with signature public Animal(String name). Solution is to create an explicit constructor in sub class invoking the super class constructor. Add below constructor to Dog class. class Dog extends Animal { public Dog() { super("Default Dog Name"); } }
Coupling
Coupling is a measure of how much a class is dependent on other classes. There should minimal dependencies between classes. So, we should always aim for low coupling between classes.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Cohesion
Cohesion
is
a
measure
of
how
related
the
responsibilities
of
a
class
are.
A
class
must
be
highly
cohesive
i.e.
its
responsibilities
(methods)
should
be
highly
related
to
one
another.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Encapsulation
Encapsulation is hiding the implementation of a Class behind a well defined interface. Encapsulation helps us to change implementation of a class without breaking other code.
Encapsulation
Approach
1
In
this
approach
we
create
a
public
variable
score.
The
main
method
directly
accesses
the
score
variable,
updates
it.
Example
Class
public
class
CricketScorer
{
public
int
score;
}
Lets
use
the
CricketScorer
class.
public
static
void
main(String[]
args)
{
CricketScorer
scorer
=
new
CricketScorer();
scorer.score
=
scorer.score
+
4;
}
Encapsulation
Approach
2
In
this
approach,
we
make
score
as
private
and
access
value
through
get
and
set
methods.
However,
the
logic
of
adding
4
to
the
score
is
performed
in
the
main
method.
Example
Class
public
class
CricketScorer
{
private
int
score;
public
int
getScore()
{
return
score;
}
public
void
setScore(int
score)
{
this.score
=
score;
}
}
Lets
use
the
CricketScorer
class.
public
static
void
main(String[]
args)
{
CricketScorer
scorer
=
new
CricketScorer();
int
score
=
scorer.getScore();
scorer.setScore(score
+
4);
}
Encapsulation
Approach
3
In
this
approach
-
For
better
encapsulation,
the
logic
of
doing
the
four
operation
also
is
moved
to
the
CricketScorer
class.
Example
Class
public
class
CricketScorer
{
private int score; public void four() { score += 4; } } Lets use the CricketScorer class. public static void main(String[] args) { CricketScorer scorer = new CricketScorer(); scorer.four(); }
Encapsulation
Example
In
terms
of
encapsulation
Approach
3
>
Approach
2
>
Approach
1.
In
Approach
3,
the
user
of
scorer
class
does
not
even
know
that
there
is
a
variable
called
score.
Implementation
of
Scorer
can
change
without
changing
other
classes
using
Scorer.
Interface
An interface defines a contract for responsibilities (methods) of a class. Lets look at a few examples of interfaces.
Defining
an
Interface
An
interface
is
declared
by
using
the
keyword
interface.
Look
at
the
example
below:
Flyable
is
an
interface.
//public
abstract
are
not
necessary
public
abstract
interface
Flyable
{
//public
abstract
are
not
necessary
public
abstract
void
fly();
}
Implementing
an
Interface
We can define a class implementing the interface by using the implements keyword. Let us look at a couple of examples:
Example
1
Class
Aeroplane
implements
Flyable
and
implements
the
abstract
method
fly().
public
class
Aeroplane
implements
Flyable{
@Override
public
void
fly()
{
System.out.println("Aeroplane
is
flying");
}
}
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Variables
in
an
interface
Variables
in
an
interface
are
always
public,
static,
final.
Variables
in
an
interface
cannot
be
declared
private.
interface
ExampleInterface1
{
//By
default
-
public
static
final.
No
other
modifier
allowed
//value1,value2,value3,value4
all
are
-
public
static
final
int
value1
=
10;
public
int
value2
=
15;
public
static
int
value3
=
20;
public
static
final
int
value4
=
25;
//private
int
value5
=
10;//COMPILER
ERROR
}
Methods
in
an
interface
Interface
methods
are
by
default
public
and
abstract.
A
concrete
method
(fully
defined
method)
cannot
be
created
in
an
interface.
Consider
the
example
below:
interface
ExampleInterface1
{
//By
default
-
public
abstract.
No
other
modifier
allowed
void
method1();//method1
is
public
and
abstract
//private
void
method6();//COMPILER
ERROR!
/*//Interface
cannot
have
body
(definition)
of
a
method
//This
method,
uncommented,
gives
COMPILER
ERROR!
void
method5()
{
System.out.println("Method5");
}
*/
}
Extending
an
Interface
An interface can extend another interface. Consider the example below:
interface
SubInterface1
extends
ExampleInterface1{
void
method3();
}
Class
implementing
SubInterface1
should
implement
both
methods
-
method3
and
method1(from
ExampleInterface1)
An interface cannot extend a class. /*
//COMPILE
ERROR
IF
UnCommented
//Interface
cannot
extend
a
Class
interface
SubInterface2
extends
Integer{
void
method3();
}
*/
A class can implement multiple interfaces. It should implement all the method declared in all Interfaces being implemented.
interface
ExampleInterface2
{
void
method2();
}
class
SampleImpl
implements
ExampleInterface1,ExampleInterface2{
/*
A
class
should
implement
all
the
methods
in
an
interface.
If
either
of
method1
or
method2
is
commented,
it
would
result
in
compilation
error.
*/
public
void
method2()
{
System.out.println("Sample
Implementation
for
Method2");
}
public
void
method1()
{
System.out.println("Sample
Implementation
for
Method1");
}
}
Method
Overloading
A method having the same name as another method (in same class or a sub class) but having different parameters is called an Overloaded Method.
Method
Overriding
Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method Overriding.
Lets
create
a
sub
class
of
Animal
Cat
-
overriding
the
existing
shout
method
in
Animal.
class
Cat
extends
Animal
{
public
String
bark()
{
return
"Meow
Meow";
}
}
bark method in Cat class is overriding the bark method in Animal class.
Example
1
class
SuperClass{
public
void
publicMethod(){
}
}
class
SubClass{
//Cannot
reduce
visibility
of
SuperClass
Method
//So,
only
option
is
public
public
void
publicMethod()
{
}
} publicMethod in SubClass can only be declared as public. Keyword protected, private or (default) instead of public would result in Compilation Error.
Example
2
class
SuperClass{
void
defaultMethod(){
}
}
class
SubClass{
//Can
be
overridden
with
public,(default)
or
protected
//private
would
give
COMPILE
ERROR!
public
void
defaultMethod(){
}
}
defaultMethod in SuperClass is declared with default access. Any method overriding it can have access default or greater. So default, protected and public are fine. Overriding method cannot be private.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
publicMethod() in SuperClass throws FileNotFoundException. So, the SubClass publicMethod() can throw FileNotFoundException or any sub class of FileNotFoundException. It can also not throw an Exception (as in the example). But, it cannot throw any new Exception. For example, public void publicMethod() throws IOException would cause compilation error.
Covariant
Returns
A sub class is considered to be of same type as its super class. So, in interfaces or abstract class, it is fine to provide implementations using the Sub Class Types as Return Types.(com.rithus.SameType)
Class
Modifiers
Access
Modifiers
Access
modifier
for
a
class
can
be
public
or
(default),
It
cannot
be
private
or
protected.
public
class
PublicClass{
}
class
DefaultClass{
}
protected
class
Error{//COMPILER
ERROR
}
private
class
Error{//COMPILER
ERROR
}
Non-access
modifiers
strictfp,
final,
abstract
modifiers
are
valid
on
a
class.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Is
Accessible
through
reference/instance
variable?
We
create
an
instance
of
the
class
and
try
to
access
the
variables
and
methods
declared
in
the
class.
ExampleClass
example
=
new
ExampleClass();
example.publicVariable
=
5;
example.publicMethod();
Is Accessible through Inheritance?
Can
we
access
the
super
class
variables
and
methods
from
a
Sub
Class?
public
class
SubClass
extends
ExampleClass
{
void
subClassMethod(){
publicVariable
=
5;
protectedVariable
=
5;
}
}
Important Access Things to Remember A sub class trying to access through reference/instance variables, will have the same access as a normal class (non sub class). Access modifiers cannot be applied to local variables
public
class
ExampleClass
{
int
defaultVariable;
public
int
publicVariable;
private
int
privateVariable;
protected
int
protectedVariable;
void
defaultMethod(){
}
public
void
publicMethod(){
}
private
void
privateMethod(){
}
protected
void
protectedMethod(){
}
}
default
or
package
a. Default variables and methods can be accessed in the same package Classes. b. Default variables and methods from SuperClass are available only to SubClasses in same package.
protected
a. Protected variables and methods can be accessed in the same package Classes. b. Protected variables and methods from SuperClass are available to SubClass in any package
public
a. Public variables and methods can be accessed from every other Java classes. b. Public variables and methods from SuperClass are all available directly in the SubClass
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
publicVariable = 5; publicMethod(); //privateVariable is not visible to SubClass //Below Line, uncommented, would give compiler error //privateVariable=5; //COMPILE ERROR //privateMethod(); protectedVariable = 5; protectedMethod(); defaultVariable = 5; defaultMethod(); } }
Final
modifier
Final
class
cannot
be
extended
Consider
the
class
below
which
is
declared
as
final.
final
public
class
FinalClass
{
}
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
strictfp
volatile
Volatile can only be applied to instance variables. A volatile variable is one whose value is always written to and read from "main memory". Each thread has its own cache in Java. The volatile variable will not be stored on a Thread cache.
native
Can be applied only to methods. These methods are implemented in native languages (like C)
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
In instance methods, both static and instance variables are accessible. public void instanceMethod() { instanceVariable = 10; staticVariable = 10; }
Instance
variables
and
methods
are
only
accessible
through
object
references.
example.instanceVariable
=
10;
example.instanceMethod();
//StaticModifierExamples.instanceVariable
=
10;//COMPILER
ERROR
//StaticModifierExamples.instanceMethod();//COMPILER
ERROR
Static
variables
and
methods
are
accessible
through
object
references
and
Class
Name.
example.staticVariable
=
10;
example.staticMethod();
StaticModifierExamples.staticVariable
=
10;
StaticModifierExamples.staticMethod();
It is always recommended to use Class Name to access a static variable or method. This is because static methods are class level methods. It is not appropriate to use instance references to call static methods (even though it compiles and works).
} JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Class
Contents
A Java Source File can contain 0 or 1 Public Classes 0 or 1 or More Non Public Classes Order should be Package Statement Imports Class Declarations Comments can be anywhere in the file. If there is a public class, file name should the (name of public class) + ".java". If name of public class is Scorer, name of file should be Scorer.java. If there is no public class, there are no restrictions on file name.
Example
Class
/*
Comments
Anywhere*/
package
com.rithus.classcontent;
class
DefaultClass1{
}
/*
Comments
Anywhere*/
class
DefaultClass2{
}
/*
Comments
Anywhere*/
public
class
PublicClass1
{
}
/*
Cannot
have
another
Public
Class.
public
class
PublicClass2
{
}
*/
Nested
Class
Nested
Classes
are
classes
which
are
declared
inside
other
classes.
}
}
Inner Class Generally the term inner class is used to refer to a non-static class declared directly inside another class. Consider the example of class named InnerClass. Static Inner Class A class declared directly inside another class and declared as static. In the example above, class name StaticNestedClass is a static inner class. Method Inner Class A class declared directly inside a method. In the example above, class name MethodLocalInnerClass is a method inner class.
Inner
Class
Consider
the
following
Example:
class
OuterClass
{
private
int
outerClassInstanceVariable;
public
class
InnerClass
{
private
int
innerClassVariable;
public
int
getInnerClassVariable()
{
return
innerClassVariable;
}
public
void
setInnerClassVariable(
int
innerClassVariable)
{
this.innerClassVariable
=
innerClassVariable;
}
public
void
privateVariablesOfOuterClassAreAvailable()
{
outerClassInstanceVariable
=
5;
//
we
can
access
the
value
System.out.println("Inner
class
ref
is
"
+
this);
//Accessing
outer
class
reference
variable
System.out.println("Outer
class
ref
is
"
+
OuterClass.this);
}
}
public
void
createInnerClass(){
//Just
use
the
inner
class
name
to
create
it
InnerClass
inner
=
new
InnerClass();
}
}
public
class
InnerClassExamples
{
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Creating
an
Inner
Class
instance
in
outer
class
Consider
the
method
createInnerClass
from
the
example
above:
This
method
shows
how
to
create
an
inner
class
instance.
public
void
createInnerClass(){
//Just
use
the
inner
class
name
to
create
it
InnerClass
inner
=
new
InnerClass();
}
Instance
variables
of
Outer
Class
are
available
in
inner
class
Consider
the
method
privateVariablesOfOuterClassAreAvailable
from
InnerClass
declared
above:
public
void
privateVariablesOfOuterClassAreAvailable()
{
outerClassInstanceVariable
=
5;
//
we
can
access
the
value
System.out.println("Inner
class
ref
is
"
+
this);
//Accessing
outer
class
reference
variable
System.out.println("Outer
class
ref
is
"
+
OuterClass.this);
}
} public void setStaticNestedClassVariable( int staticNestedClassVariable) { this.staticNestedClassVariable = staticNestedClassVariable; } public void privateVariablesOfOuterClassAreNOTAvailable() { // outerClassInstanceVariable = 5; //COMPILE ERROR } } } public class InnerClassExamples { public static void main(String[] args) { // Static Nested Class can be created without needing to create its // parent. Without creating NestedClassesExample, we created // StaticNestedClass OuterClass.StaticNestedClass staticNestedClass1 = OuterClass.StaticNestedClass(); staticNestedClass1.setStaticNestedClassVariable(5); OuterClass.StaticNestedClass staticNestedClass2 = OuterClass.StaticNestedClass(); staticNestedClass2.setStaticNestedClassVariable(10); // Static Nested Class member variables are not static. They can have // different values. System.out.println(staticNestedClass1 .getStaticNestedClassVariable()); //5 System.out.println(staticNestedClass2 .getStaticNestedClassVariable()); //10 } }
new
new
Creating
Static
Nested
Class
Static
Nested
Class
can
be
created
without
needing
to
create
its
parent.
Without
creating
NestedClassesExample,
we
createdStaticNestedClass.
OuterClass.StaticNestedClass
staticNestedClass1
=
new
OuterClass.StaticNestedClass();
Member
variables
are
not
static
Static
Nested
Class
member
variables
are
not
static.
They
can
have
different
values.
System.out.println(staticNestedClass1
.getStaticNestedClassVariable());
//5
System.out.println(staticNestedClass2
.getStaticNestedClassVariable());
//10
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Method
inner
class
is
not
accessible
outside
the
method
Look
at
the
commented
code
below
exampleMethod.
MethodLocalInnerClass
can
be
instantiated
only
in
the
method
where
it
is
declared.
Method
inner
class
can
access
class
instance
variables
//Can
access
class
instance
variables
System.out.println(outerClassInstanceVariable);
Variable
Arguments
Variable Arguments allow calling a method with different number of parameters.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Exception
Handling
In
this
tutorial,
lets
understand
the
need
for
exception
handling
and
learn
how
to
handle
exceptions.
Program
Output
Exception in thread "main" java.lang.NullPointerException at com.rithus.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:1 5) at com.rithus.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:1 0) at com.rithus.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:6) Look at the stack trace. Exception which is thrown in method2 is propagating to method1 and then to main. This is because there is no exception handling in all 3 methods - main, method1 and method2
method1(); System.out.println("Line after Exception - Main"); } private static void method1() { method2(); System.out.println("Line after Exception - Method 1"); } private static void method2() { String str = null; str.toString(); System.out.println("Line after Exception - Method 2"); }
Code
Output
Exception in thread "main" java.lang.NullPointerException at com.rithus.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:1 8) at com.rithus.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:1 2) at com.rithus.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:7) Note that none of the lines with text "Line after Exception - ****" are executed. If an exception occurs, lines after the line where exception occurred are not executed. Since all three methods main, method1() and method2() do not have any Exception Handling, exception propagates from method2 to method1 to main.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
connection.close(); } catch (Exception e) { // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE System.out.println("Exception Handled - Method 2"); } } } Output Connection Opened Exception Handled - Method 2 Line after Exception - Method 1 Line after Exception - Main Connection that is opened is not closed. Because an exception has occurred in method2, connection.close() is not run. This results in a dangling (un-closed) connection.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
try
{
//
LOGIC
String
str
=
null;
str.toString();
}//COMPILER
ERROR!!
}
Errors
Error is used in situations when there is nothing a programmer can do about an error. Ex: StackOverflowError, OutOfMemoryError.
Exception
Exception is used when a programmer can handle the exception.
Un-Checked
Exception
RuntimeException and classes that extend RuntimeException are called unchecked exceptions. For Example: RuntimeException,UnCheckedException,UnCheckedException2 are unchecked or RunTime Exceptions. There are subclasses of RuntimeException (which means they are subclasses of Exception also.)
Checked
Exception
Other Exception Classes (which dont fit the earlier definition). These are also called Checked Exceptions. Exception, CheckedException1,CheckedException2 are checked exceptions. They are subclasses of Exception which are not subclasses of RuntimeException.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Output
Exception in thread "main" java.lang.RuntimeException: Currencies don't match at com.rithus.exceptionhandling.AmountAdder.addAmounts(ExceptionHandlingExample2.java:17) at com.rithus.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:28) Exception message shows the type of exception(java.lang.RuntimeException) and the string message passed to the RuntimeException constructor("Currencies don't match");
class AmountAdder { static Amount addAmounts(Amount amount1, Amount amount2) { if (!amount1.currency.equals(amount2.currency)) { throw new Exception("Currencies don't match");// COMPILER ERROR! // Unhandled exception type Exception } return new Amount(amount1.currency, amount1.amount + amount2.amount); } } All classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown. Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the method should declare that it throws the exception
throw new Exception("Currencies don't match"); } return new Amount(amount1.currency, amount1.amount + amount2.amount); } } Look at the line "static Amount addAmounts(Amount amount1, Amount amount2) throws Exception". This is how we declare that a method throws Exception. This results in compilation error in main method. This is because Main method is calling a method which is declaring that it might throw Exception. Main method again has two options a. Throw b. Handle Code with main method throwing the exception below public static void main(String[] args) throws Exception { AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("DOLLAR", 5)); }
Output
Exception in thread "main" java.lang.Exception: Currencies don't match at com.rithus.exceptionhandling.AmountAdder.addAmounts(ExceptionHandlingExample2.java:17) at com.rithus.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:28)
Handling
an
Exception
main can also handle the exception instead of declaring throws. Code for it below. public
static
void
main(String[]
args)
{
try
{
AmountAdder.addAmounts(new
Amount("RUPEE",
5),
new
Amount("DOLLAR",5));
}
catch
(Exception
e)
{
System.out.println("Exception
Handled
in
Main");
}
}
Output
Exception Handled in Main
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Extend
RuntimeException
Lets change the class CurrenciesDoNotMatchException to extend RuntimeException instead of Exception class
CurrenciesDoNotMatchException
extends
RuntimeException{
}
Output: Exception Handled in Mainclass com.rithus.exceptionhandling.CurrenciesDoNotMatchException Change methods addAmounts CurrenciesDoNotMatchException" in AmountAdder to remove the declaration " throws
No compilation error occurs since RuntimeException and subclasses of RuntimeException are not Checked Exception's. So, they don't need to be handled or declared. If you are interested in handling them, go ahead and handle them. But, java does not require you to handle them. Remove try catch from main method. It is not necessary since CurrenciesDoNotMatchException is now a RuntimeException.
public class ExceptionHandlingExample2 { public static void main(String[] args) { AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("DOLLAR", 5)); } } Output: Exception in thread "main" com.rithus.exceptionhandling.CurrenciesDoNotMatchException at com.rithus.exceptionhandling.AmountAdder.addAmounts(ExceptionHandlingExample2.java:21) at com.rithus.exceptionhandling.ExceptionHandlingExample2.main(ExceptionHandlingExample2.java:30)
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Console
Console is used to read input from keyboard and write output.
Format
or
Printf
Format/Printf
Examples
Let's look at a few examples to quickly understand printf function. System.out.printf("%d", 5);//5 System.out.printf("My name is %s", "Rithu");//My name is Rithu System.out.printf("%s is %d Years old", "Rithu", 5);//Rithu is 5 Years old In the simplest form, string to be formatted starts with % followed by conversion indicator => b - boolean c - char d - integer f - floating point s - string.
For
floating
point
numbers,
precision
can
be
specified
after
dot(.).
Below
example
uses
a
precision
of
2,
so
.5678
gets
changed
to
.57
System.out.printf("%5.2f",
1234.5678);
//prints
1234.57
An
error
in
specifying
would
give
a
RuntimeException.
In
below
example
a
string
is
passed
to
%d
argument.
System.out.printf("%5d","Test");
//Throws
java.util.IllegalFormatConversionException
//To
change
the
order
of
printing
and
passing
of
arguments,
argument
index
can
be
used
System.out.printf("%3$.1f
%2$s
%1$d",
123,
"Test",
123.4);
//prints
123.4
Test
123
//format
method
has
the
same
behavior
as
printf
method
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Method
Chaining
All
functions
also
return
a
reference
to
the
object
after
modifying
it.This
allows
a
concept
called
method
chaining.
StringBuilder
sb3
=
new
StringBuilder("abcdefgh");
System.out.println(sb3.reverse().delete(5,
6).insert(3,
"---"));//hgf---edba
Date
Date is no longer the class Java recommends for storing and manipulating date and time. Most of methods in Date are deprecated. Use Calendar class instead. Date internally represents date-time as number of milliseconds (a long value) since 1st Jan 1970.
Lets now look at adding a few hours to a date object. All date manipulation to date needs to be done by adding milliseconds to the date. For example, if we want to add 6 hour, we convert 6 hours into millseconds. 6 hours = 6 * 60 * 60 * 1000 milliseconds. Below examples shows specific code. Date date = new Date(); //Increase time by 6 hrs date.setTime(date.getTime() + 6 * 60 * 60 * 1000); System.out.println(date); //Decrease time by 6 hrs date = new Date(); date.setTime(date.getTime() - 6 * 60 * 60 * 1000); System.out.println(date);
Formatting
Dates
Formatting
Dates
is
done
by
using
DateFormat
class.
Lets
look
at
a
few
examples.
//Formatting
Dates
System.out.println(DateFormat.getInstance().format(
date));//10/16/12
5:18
AM
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Default
Locale
Locale
defaultLocale
=
Locale.getDefault();
System.out.println(defaultLocale
.getDisplayCountry());//United
States
System.out.println(defaultLocale
.getDisplayLanguage());//English
Calendar
Calendar
class
is
used
in
Java
to
manipulate
Dates.
Calendar
class
provides
easy
ways
to
add
or
reduce
days,
months
or
years
from
a
date.
It
also
provide
lot
of
details
about
a
date
(which
day
of
the
year?
Which
week
of
the
year?
etc.)
Calendar
is
abstract
Calendar
class
cannot
be
created
by
using
new
Calendar.
The
best
way
to
get
an
instance
of
Calendar
class
is
by
using
getInstance()
static
method
in
Calendar.
//Calendar
calendar
=
new
Calendar();
//COMPILER
ERROR
Calendar
calendar
=
Calendar.getInstance();
Roll
method
Roll
method
will
only
the
change
the
value
being
modified.
YEAR
remains
unaffected
when
MONTH
is
changed,
for
instance.
calendar.roll(Calendar.MONTH,
5);
System.out.println(calendar.getTime());//Mon
Mar
29
2012
Number
Format
Number format is used to format a number to different locales and different formats.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Collection
Interfaces
Arrays
are
not
dynamic.
Once
an
array
of
a
particular
size
is
declared,
the
size
cannot
be
modified.
To
add
a
new
element
to
the
array,
a
new
array
has
to
be
created
with
bigger
size
and
all
the
elements
from
the
old
array
copied
to
new
array.
Collections
are
used
in
situations
where
data
is
dynamic.
Collections
allow
adding
an
element,
deleting
an
element
and
host
of
other
operations.
There
are
a
number
of
Collections
in
Java
allowing
to
choose
the
right
Collection
for
the
right
context.
Before
looking
into
Collection
classes,
lets
take
a
quick
look
at
all
the
important
collection
interfaces
and
the
operations
they
allow.
Collection
Interface
Most
important
methods
declared
in
the
collection
interface
are
the
methods
to
add
and
remove
an
element.
add
method
allows
adding
an
element
to
a
collection
and
delete
method
allows
deleting
an
element
from
a
collection.
size()
methods
returns
number
of
elements
in
the
collection.
Other
important
methods
defined
as
part
of
collection
interface
are
shown
below.
interface
Collection<E>
extends
Iterable<E>
{
boolean
add(E
paramE);
boolean
remove(Object
paramObject);
int
size();
boolean
isEmpty();
void
clear();
boolean contains(Object paramObject); boolean containsAll(Collection<?> paramCollection); boolean addAll(Collection<? extends E> paramCollection); boolean removeAll(Collection<?> paramCollection); boolean retainAll(Collection<?> paramCollection); Iterator<E> iterator(); //A NUMBER OF OTHER METHODS AS WELL.. }
List
Interface
List
interface
extends
Collection
interface.
So,
it
contains
all
methods
defined
in
the
Collection
interface.
In
addition,
List
interface
allows
operation
specifying
the
position
of
the
element
in
the
Collection.
Any
implementation
of
the
List
interface
would
maintain
the
insertion
order.
When
a
new
element
is
inserted,
it
is
inserted
at
the
end
of
the
list
of
elements.
We
can
also
use
the
void
add(int
paramInt,
E
paramE);
method
to
insert
an
element
at
a
specific
position.
We
can
also
set
and
get
the
elements
at
a
particular
index
in
the
list
using
corresponding
methods.
Other
important
methods
are
listed
below:
interface
List<E>
extends
Collection<E>
{
boolean
addAll(int
paramInt,
Collection<?
extends
E>
paramCollection);
E
get(int
paramInt);
E
set(int
paramInt,
E
paramE);
void
add(int
paramInt,
E
paramE);
E
remove(int
paramInt);
int
indexOf(Object
paramObject);
int
lastIndexOf(Object
paramObject);
ListIterator<E>
listIterator();
ListIterator<E>
listIterator(int
paramInt);
List<E>
subList(int
paramInt1,
int
paramInt2);
}
Map
Interface
First
and
foremost,
Map
interface
does
not
extend
Collection
interface.
So,
it
does
not
inherit
any
of
the
methods
from
the
Collection
interface.
A
Map
interface
supports
Collections
that
use
a
key
value
pair.
A
key-value
pair
is
a
set
of
linked
data
items:
a
key,
which
is
a
unique
identifier
for
some
item
of
data,
and
the
value,
which
is
either
the
data
or
a
pointer
to
the
data.
Key-value
pairs
are
used
in
lookup
tables,
hash
tables
and
configuration
files.
A
key
value
pair
in
a
Map
interface
is
called
an
Entry.
JAVA
SPRING,
STRUTS,
AJAX
&
MORE
-
Videos,
Interview
Questions,
Projects
ON
RITHUS.COM
Get
method
allows
to
get
a
value
from
the
Map
based
on
the
key.
V
get(Object
paramObject);
Set
Interface
Set
Interface
extends
Collection
Interface.
Set
interface
only
contains
the
methods
from
the
Collection
interface
with
added
restriction
that
it
cannot
contain
duplicates.
//
Unique
things
only
-
Does
not
allow
duplication.
//
If
obj1.equals(obj2)
then
only
one
of
them
can
be
in
the
Set.
interface
Set<E>
extends
Collection<E>
{
}
SortedSet
Interface
SortedSet
Interface
extends
the
Set
Interface.
So,
it
does
not
allow
duplicates.
Java
Tutorial
For
Beginners
Rithus.com
1 1
1
In
addition,
an
implementation
of
SortedSet
interface
maintains
its
elements
in
a
sorted
order.
It
adds
operations
that
allow
getting
a
range
of
values
(subSet,
headSet,
tailSet).
Important
Operations
listed
below:
public
interface
SortedSet<E>
extends
Set<E>
{
SortedSet<E>
subSet(E
fromElement,
E
toElement);
SortedSet<E>
headSet(E
toElement);
SortedSet<E>
tailSet(E
fromElement);
E
first();
E
last();
Comparator<?
super
E>
comparator();
}
SortedMap
Interface
SortedMap
interface
extends
the
Map
interface.
In
addition,
an
implementation
of
SortedMap
interface
maintains
keys
in
a
sorted
order.
Methods
are
available
in
the
interface
to
get
a
ranges
of
values
based
on
their
keys.
public
interface
SortedMap<K,
V>
extends
Map<K,
V>
{
Comparator<?
super
K>
comparator();
SortedMap<K,
V>
subMap(K
fromKey,
K
toKey);
SortedMap<K,
V>
headMap(K
toKey);
SortedMap<K,
V>
tailMap(K
fromKey);
K
firstKey();
K
lastKey();
}
Queue
Interface
Queue
Interface
extends
Collection
interface.
Queue
Interface
is
typically
used
for
implementation
holding
elements
in
order
for
some
processing.
Queue
interface
offers
methods
peek()
and
poll()
which
get
the
element
at
head
of
the
queue.
The
difference
is
that
poll()
method
removes
the
head
from
queue
also.
peek()
would
keep
head
of
the
queue
unchanged.
interface
Queue<E>
extends
Collection<E>
{
boolean
offer(E
paramE);
E
remove();
E
poll();
E
element();
E
peek();
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Iterator
interface
Iterator
interface
enables
us
to
iterate
(loop
around)
a
collection.
All
collections
define
a
method
iterator()
that
gets
an
iterator
of
the
collection.
hasNext()
checks
if
there
is
another
element
in
the
collection
being
iterated.
next()
gets
the
next
element.
public
interface
Iterator<E>
{
boolean
hasNext();
E
next();
}
Collections
ArrayList
ArrayList
implements
the
list
interface.
So,
ArrayList
stores
the
elements
in
insertion
order
(by
default).
Elements
can
be
inserted
into
and
removed
from
ArrayList
based
on
their
position.
Lets
look
at
how
to
instantiate
an
ArrayList
of
integers.
List<Integer>
integers
=
new
ArrayList<Integer>();
Code
like
below
is
permitted
because
of
auto
boxing.
5
is
auto
boxed
into
Integer
object
and
stored
in
ArrayList.
integers.add(5);//new
Integer(5)
Add
method
(by
default)
adds
the
element
at
the
end
of
the
list.
ArrayList
of
String
Example
Below
example
shows
how
to
create
and
use
a
String
ArrayList.
ArrayList
can
have
duplicates
(since
List
can
have
duplicates).
size()
method
gets
number
of
elements
in
the
ArrayList.
contains(Object)
method
checks
if
an
element
is
present
in
the
arraylist.
List<String>
arraylist
=
new
ArrayList<String>();
//adds
at
the
end
of
list
arraylist.add("Sachin");//[Sachin]
//adds
at
the
end
of
list
arraylist.add("Dravid");//[Sachin,
Dravid]
//adds
at
the
index
0
arraylist.add(0,
"Ganguly");//[Ganguly,
Sachin,
Dravid]
//List allows duplicates - Sachin is present in the list twice arraylist.add("Sachin");//[ Ganguly, Sachin, Dravid, Sachin] System.out.println(arraylist.size());//4 System.out.println(arraylist.contains("Dravid"));//true
Other
ArrayList
(List)
methods
indexOf()
function
-
returns
index
of
element
if
element
is
found.
Negative
number
otherwise.
//example1
-
value
is
present
System.out.println(arraylist.indexOf("Dravid"));//2
//example2
-
value
is
not
present
System.out.println(arraylist.indexOf("Bradman"));//-1
Sorting
Collections
List<String>
numbers
=
new
ArrayList<String>();
numbers.add("one");
numbers.add("two");
numbers.add("three");
numbers.add("four");
System.out.println(numbers);//[one,
two,
three,
four]
//Strings
-
By
Default
-
are
sorted
alphabetically
Collections.sort(numbers);
System.out.println(numbers);//[four,
one,
three,
two]
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
We
get
a
compiler
error
since
Cricketer
class
does
not
implement
Comparable
interface.
We
were
able
to
sort
numbers
in
earlier
example
because
String
class
implements
Comparable.
Lets
make
the
Cricketer
class
implement
the
Comparable
Interface.
class
Cricketer
implements
Comparable<Cricketer>
{
//OTHER
CODE/PROGRAM
same
as
previous
//compareTo
takes
an
argument
of
the
same
type
of
the
class
//compareTo
returns
-1
if
this
<
that
//
1
if
this
>
that
//
0
if
this
=
that
@Override
public
int
compareTo(Cricketer
that)
{
if
(this.runs
>
that.runs)
{
return
1;
}
if
(this.runs
<
that.runs)
{
return
-1;
}
return
0;
}
}
Other
option
to
sort
collections
is
by
creating
a
separate
class
which
implements
Comparator
interface.
Example
below:
class
DescendingSorter
implements
Comparator<Cricketer>
{
//compareTo
returns
-1
if
cricketer1
<
cricketer2
//
1
if
cricketer1
>
cricketer2
//
0
if
cricketer1
=
cricketer2
//Since
we
want
to
sort
in
descending
order,
//we
should
return
-1
when
runs
are
more
@Override
public
int
compare(Cricketer
cricketer1,
Cricketer
cricketer2)
{
if
(cricketer1.runs
>
cricketer2.runs)
{
return
-1;
}
if
(cricketer1.runs
<
cricketer2.runs)
{
return
1;
}
return
0;
}
}
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Other
is
to
use
toArray()
function.
Example
below.
This
creates
an
array
of
Objects.
Object[]
numbers1ObjArray
=
numbers1.toArray();
System.out.println(Arrays
.toString(numbers1ObjArray));
//[one,
two,
three,
four]
Set
Interface
HashSet,
LinkedHashSet
and
TreeSet
implement
the
Set
interface.
Lets
look
at
examples
of
these
collection
classes.
HashSet
HashSet
implements
set
interface.
Sets
do
not
allow
duplicates.
HashSet
does
not
support
ordering.
HashSet
Example
Set<String>
hashset
=
new
HashSet<String>();
hashset.add("Sachin");
System.out.println(hashset);//[Sachin]
hashset.add("Dravid");
Lets
try
to
add
Sachin
to
the
Set
now.
Sachin
is
Duplicate.
So
will
not
be
added.
returns
false.
hashset.add("Sachin");//returns
false
since
element
is
not
added
System.out.println(hashset);//[Sachin,
Dravid]
LinkedHashSet
LinkedHashSet
implements
set
interface
and
exposes
similar
operations
to
a
HashSet.
Difference
is
that
LinkedHashSet
maintains
insertion
order.
When
we
iterate
a
LinkedHashSet,
we
would
get
the
elements
back
in
the
order
in
which
they
were
inserted.
TreeSet
TreeSet
implements
Set,
SortedSet
and
NavigableSet
interfaces.TreeSet
is
similar
to
HashSet
except
that
it
stores
elements
in
Sorted
Order.
Set<String>
treeSet
=
new
TreeSet<String>();
treeSet.add("Sachin");
System.out.println(treeSet);//[Sachin]
Objects
that
are
inserted
into
a
TreeSet
should
be
comparable.
TreeSet
-
NavigableSet
interface
examples
1
TreeSet
implements
this
interface.
Let's
look
at
an
example
with
TreeSet.
Note
that
elements
in
TreeSet
are
sorted.
TreeSet<Integer>
numbersTreeSet
=
new
TreeSet<Integer>();
numbersTreeSet.add(55);
numbersTreeSet.add(25);
numbersTreeSet.add(35);
numbersTreeSet.add(5);
numbersTreeSet.add(45);
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
All
the
three
methods
-
subSet,headSet,tailSet
-
are
inclusive
with
Lower
Limit
and
NOT
inclusive
with
higher
limit.
In
the
sub
set
below,
Lower
Limit
is
inclusive
-
25
included.
Higher
limit
is
not
inclusive
-
55
excluded.
//Get
sub
set
with
values
>=25
and
<55
SortedSet<Integer>
subTreeSet
=
exampleTreeSet
.subSet(25,
55);
System.out.println(subTreeSet);//[25,
35]
All
the
sub
set
methods
-
subSet,headSet,tailSet
-
return
dynamic
sub
sets.
When
original
set
is
modified
(addition
or
deletion),
corresponding
changes
can
affect
the
sub
sets
as
well.
System.out.println(exampleTreeSet);//[5,
25,
35,
55,
105]
System.out.println(subTreeSet);//[25,
35]
System.out.println(headTreeSet);//[5,
25,
35]
System.out.println(tailTreeSet);//[35,
55,
105]
Let's
now
insert
a
value
30
into
the
exampleTreeSet.
Remember
that
subTreeSet,
headTreeSet,
tailTreeSet
are
sub
sets
of
exampleTreeSet.
exampleTreeSet.add(30);
System.out.println(exampleTreeSet);//[5,
25,
30,
35,
55,
105]
System.out.println(subTreeSet);//[25,
30,
35]
System.out.println(headTreeSet);//[5,
30,
25,
35]
System.out.println(tailTreeSet);//[35,
55,
105]
30
is
in
the
range
of
subTreeSet
and
headTreeSet.
So,
it
is
printed
as
part
of
exampleTreeSet,
subTreeSet
and
headTreeSet.
//Lets
now
add
65
to
the
set
exampleTreeSet.add(65);
System.out.println(exampleTreeSet);//[5,
25,
30,
35,
55,
65,
105]
System.out.println(subTreeSet);//[25,
30,
35]
System.out.println(headTreeSet);//[5,
30,
25,
35]
System.out.println(tailTreeSet);//[35,
55,
65,
105]
65 is printed as part of exampleTreeSet and tailTreeSet. Key thing to remember is that all the sub sets are dynamic. If you modify the original set,the sub set might be affected.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
pollFirst
returns
the
first
element
and
removes
it
from
the
set.
System.out.println(treeSetOrig);//[5,
25,
35,
55]
System.out.println(treeSetOrig.pollFirst());//5
System.out.println(treeSetOrig);//[25,
35,
55]
//In
above
example
element
5
is
removed
from
the
set
and
also
removed
from
the
tree
set.
pollLast
returns
the
last
element
and
removes
it
from
the
set.
System.out.println(treeSetOrig);//[25,
35,
55]
System.out.println(treeSetOrig.pollLast());//55
System.out.println(treeSetOrig);//[25,
35]
Map
Interface
Lets
take
a
look
at
different
implementations
of
the
Map
interface.
HashMap
HashMap
implements
Map
interface
there
by
supporting
key
value
pairs.
Lets
look
at
an
example.
HashMap
Example
Map<String,
Cricketer>
hashmap
=
new
HashMap<String,
Cricketer>();
hashmap.put("sachin",
new
Cricketer("Sachin",
14000));
hashmap.put("dravid",
new
Cricketer("Dravid",
12000));
hashmap.put("ponting",
new
Cricketer("Ponting",
11500));
hashmap.put("bradman",
new
Cricketer("Bradman",
9996));
Hash
Map
Methods
get
method
gets
the
value
of
the
matching
key.
System.out.println(hashmap.get("ponting"));//Ponting
11500
//if
key
is
not
found,
returns
null.
System.out.println(hashmap.get("lara"));//null
If
existing
key
is
reused,
it
would
replace
existing
value
with
the
new
value
passed
in.
//In
the
example
below,
an
entry
with
key
"ponting"
is
already
present.
//Runs
are
updated
to
11800.
hashmap.put("ponting",
new
Cricketer("Ponting",
11800));
//gets
the
recently
updated
value
System.out.println(hashmap.get("ponting"));//Ponting
11800
TreeMap
TreeMap
is
similar
to
HashMap
except
that
it
stores
keys
in
sorted
order.
It
implements
NavigableMap
interface
and
SortedMap
interfaces
along
with
the
Map
interface.
Map<String,
Cricketer>
treemap
=
new
TreeMap<String,
Cricketer>();
treemap.put("sachin",
new
Cricketer("Sachin",
14000));
System.out.println(treemap);
//{sachin=Sachin
14000}
We
will
now
insert
a
Cricketer
with
key
dravid.
In
sorted
order,dravid
comes
before
sachin.
So,
the
value
with
key
dravid
is
inserted
at
the
start
of
the
Map.
treemap.put("dravid",
new
Cricketer("Dravid",
12000));
System.out.println(treemap);
//{dravid=Dravid
12000,
sachin=Sachin
14000}
We
will
now
insert
a
Cricketer
with
key
ponting.
In
sorted
order,
ponting
fits
in
between
dravid
and
sachin.
treemap.put("ponting",
new
Cricketer("Ponting",
11500));
System.out.println(treemap);
//{dravid=Dravid
12000,
ponting=Ponting
11500,
sachin=Sachin
14000}
treemap.put("bradman",
new
Cricketer("Bradman",
9996));
System.out.println(treemap);
//{bradman=Bradman
9996,
dravid=Dravid
12000,
ponting=Ponting
11500,
sachin=Sachin
14000}
NavigableMap Interface Examples (TreeMap) Set I Let's look at an example with TreeMap. Note that keys in TreeMap are sorted.
TreeMap<Integer, Cricketer> numbersTreeMap = new TreeMap<Integer, Cricketer>(); numbersTreeMap.put(55, new Cricketer("Sachin", 14000)); numbersTreeMap.put(25, new Cricketer("Dravid", 12000)); numbersTreeMap.put(35, new Cricketer("Ponting",
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
lowerKey
method
finds
the
highest
key
lower
than
specified
key.
floorKey
method
finds
the
highest
key
lower
than
or
equal
to
specified
key.
Corresponding
methods
for
finding
lowest
key
higher
than
specified
key
are
higher
and
ceiling.
A
few
examples
using
the
Map
created
earlier
below.
//Find
the
highest
key
which
is
lower
than
25
System.out.println(numbersTreeMap.lowerKey(25));//5
//Find
the
highest
key
which
is
lower
than
or
equal
to
25
System.out.println(numbersTreeMap.floorKey(25));//25
//Find
the
lowest
key
higher
than
25
System.out.println(numbersTreeMap.higherKey(25));//35
//Find
the
lowest
key
higher
than
or
equal
to
25
System.out.println(numbersTreeMap.ceilingKey(25));//25
NavigableMap
Interface
Examples
(TreeMap)
Set
II
Methods
similar
to
subSet,headSet,tailSet
(of
TreeSet)
are
available
in
TreeMap
as
well.
They
are
called
subMap,
headMap,
tailMap.They
have
the
similar
signatures
and
results
as
the
corresponding
TreeSet
Methods.
They
are
inclusive
with
Lower
Limit
and
NOT
inclusive
with
higher
limit
-
unless
the
(optional)
inclusive
flag
is
passed.
The
resultant
sub
map's
are
dynamic.
If
original
map
get
modified,
the
sub
map
might
be
affected
as
well.
TreeMap<Integer,
Cricketer>
exampleTreeMap
=
new
TreeMap<Integer,
Cricketer>();
exampleTreeMap.put(55,
new
Cricketer("Sachin",
14000));
exampleTreeMap.put(25,
new
Cricketer("Dravid",
12000));
exampleTreeMap.put(5,
new
Cricketer("Bradman",
9996));
exampleTreeMap
.put(45,
new
Cricketer("Lara",
10000));
//Lower
limit
(5)
inclusive,
Uppper
Limit(25)
NOT
inclusive
System.out.println(exampleTreeMap.subMap(5,
25));//{5=Bradman
9996}
System.out.println(exampleTreeMap.headMap(30));
//{5=Bradman
9996,
25=Dravid
12000}
System.out.println(exampleTreeMap.tailMap(25));
//{25=Dravid
12000,
45=Lara
10000,
55=Sachin
14000}
NavigableMap
Interface
Examples
(TreeMap)
Set
III
Consider
the
next
set
of
method
examples
below:
TreeMap<Integer,
Cricketer>
treeMapOrig
=
new
TreeMap<Integer,
Cricketer>();
pollFirstEntry
returns
the
first
entry
in
the
map
and
removes
it
from
the
map.
System.out.println(treeMapOrig);
//{5=Bradman
9996,
25=Dravid
12000,
45=Lara
10000,
55=Sachin
14000}
System.out.println(treeMapOrig.pollFirstEntry());//5=Bradman
9996
System.out.println(treeMapOrig);
//{25=Dravid
12000,
45=Lara
10000,
55=Sachin
14000}
//In
above
example
element
5
is
removed
from
the
set
and
also
removed
from
the
tree
set.
pollLastEntry
returns
the
last
entry
from
the
map
and
removes
it
from
the
map.
System.out.println(treeMapOrig);
//{25=Dravid
12000,
45=Lara
10000,
55=Sachin
14000}
System.out.println(treeMapOrig.pollLastEntry());//55=Sachin
14000
System.out.println(treeMapOrig);
//{25=Dravid
12000,
45=Lara
10000}
PriorityQueue
PriorityQueue
implements
the
Queue
interface.
//Using
default
constructor
-
uses
natural
ordering
of
numbers
//Smaller
numbers
have
higher
priority
PriorityQueue<Integer>
priorityQueue
=
new
PriorityQueue<Integer>();
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Generics
Generics
are
used
to
create
Generic
Classes
and
Generic
methods
which
can
work
with
different
Types(Classes).
class
MyList
{
private
List<String>
values;
void
add(String
value)
{
values.add(value);
}
void
remove(String
value)
{
values.remove(value);
}
}
To store integers, we need to create a new class. This is problem that Generics solve. Instead of hard- coding String class as the only type the class can work with, we make the class type a parameter to the class.
Generics
Example
Lets
replace
String
with
T
and
create
a
new
class.
class
MyListGeneric<T>
{
private
List<T>
values;
void
add(T
value)
{
values.add(value);
}
void
remove(T
value)
{
values.remove(value);
}
T
get(int
index)
{
return
values.get(index);
}
}
Instead of T, We can use any valid identifier If a generic is declared as part of class declaration, it can be used any where a type can be used in a class - method (return type or argument), member variable etc. For Example: See how T is used as a parameter and return type in the class MyListGeneric. Now the MyListGeneric class can be used to create a list of Integers or a list of Strings JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Generics
Restrictions
In
MyListGeneric,
Type
T
is
defined
as
part
of
class
declaration.
Any
Java
Type
can
be
used
a
type
for
this
class.
If
we
would
want
to
restrict
the
types
allowed
for
a
Generic
Type,
we
can
use
a
Generic
Restrictions.
Consider
the
example
class
below:
class
MyListRestricted<T
extends
Number>
{
private
List<T>
values;
void
add(T
value)
{
values.add(value);
}
void
remove(T
value)
{
values.remove(value);
}
T
get(int
index)
{
return
values.get(index);
}
}
In
declaration
of
the
class,
we
specified
a
constraint
"T
extends
Number".
We
can
use
the
class
MyListRestricted
with
any
class
extending
Number
-
Float,
Integer,
Double
etc.
MyListRestricted<Integer>
restrictedListInteger
=
new
MyListRestricted<Integer>();
restrictedListInteger.add(1);
restrictedListInteger.add(2);
The
method
can
now
be
called
with
any
Class
type
extend
Number.
Integer
i
=
5;
Integer
k
=
doSomething(i);
List
method
works
with
List<Animal>.
Gives
compilation
error
with
List<Dog>.
doSomethingList(animalsList);
//List<Dog>
not
compatible
with
List<Animal>
//doSomethingList(dogsList);//COMPILER
ERROR
Summary : List<Dog> not compatible with List<Animal> even thought Dog extends Animal. However, Dog[] is compatible with Animal[].
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Method
declared
with
List<?
extends
Animal>
compiles
with
both
List<Animal>
and
List<Dog>
doSomethingListModified(animalsList);
doSomethingListModified(dogsList);
List
of
any
super
class
of
Dog
is
fine.
List
of
any
Subclass
of
Dog
is
not
valid
parameter.
doSomethingListModifiedSuper(animalsList);
doSomethingListModifiedSuper(dogsList);
/*
even
for
interfaces
extends
keyword
should
be
used
*/
Java
Tutorial
For
Beginners
Rithus.com
1 2
9
List<?
extends
Animal>
listAnimals
=
new
ArrayList<Dog>();
//COMPILES
//List<?>
genericList
=
new
ArrayList<?
extends
Animal>();
//COMPILER
ERROR
We
are
passing
a
ArrayList<Integer>
to
a
method
accepting
ArrayList
as
parameter.
We
are
trying
to
a
add
a
string
to
it
as
well,
inside
the
method.
Compiling
this
class
would
give
a
warning:
javac
gives
warning
because
multiplyNumbersBy2(ArrayList)
is
invoked
with
a
Specific
ArrayList<Integer>
and
in
the
method
addElement
an
element
is
added
to
ArrayList.
//com/rithus/generics/GenericsExamples.java
uses
unchecked
or
unsafe
operations.
//Recompile
with
-Xlint:unchecked
for
details.
To
get
more
details
run
javac
specifying
the
parameter
Xlint:unchecked.
javac
-Xlint:unchecked
com/rithus/generics/GenericsExamples.java
//com/rithus/generics/GenericsExamples.java:21:
warning:
[unchecked]
//unchecked
call
to
add(E)
as
a
member
of
the
raw
type
java.util.ArrayList
//something.add(new
String("String"));
//
^
Files
Let us first look at the File class which helps us to create and delete files and directories. File class cannot be used to modify the content of a file.
File
Class
Create
a
File
Object
File
file
=
new
File("FileName.txt");
File basic Methods Check if the file exists. JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
If
file
does
not
exist
creates
it
and
returns
true.
If
file
exists,
returns
false.
System.out.println(file.createNewFile());
Renaming
a
file
File
fileWithNewName
=
new
File("NewFileName.txt");
file.renameTo(fileWithNewName);
//There
is
no
method
file.renameTo("NewFileName.txt");
Creating
a
directory
File
newDirectory
=
new
File("newfolder");
System.out.println(newDirectory.mkdir());//true
-
First
Time
Implementations of Writer and Reader abstract classes help us to write and read (content of) files.
FileWriter
Class
We
can
write
to
a
file
using
FileWriter
class.
Write
a
string
to
a
file
using
FileWriter
//FileWriter
helps
to
write
stuff
into
the
file
FileWriter
fileWriter
=
new
FileWriter(file);
fileWriter.write("How
are
you
doing?");
//Always
flush
before
close.
Writing
to
file
uses
Buffering.
fileWriter.flush();
fileWriter.close();
FileWriter
Constructors
FileWriter
Constructors
can
accept
file(File)
or
the
path
to
file
(String)
as
argument.
When
a
writer
object
is
created,
it
creates
the
file
-
if
it
does
not
exist.
FileWriter
fileWriter2
=
new
FileWriter("FileName.txt");
fileWriter2.write("How
are
you
doing
Buddy?");
//Always
flush
before
close.
Writing
to
file
uses
Buffering.
fileWriter2.flush();
fileWriter2.close();
FileReader
Class
File
Reader
can
be
used
to
read
entire
content
from
a
file
at
one
go.
Read
from
file
using
FileReader
FileReader
fileReader
=
new
FileReader(file);
char[]
temp
=
new
char[25];
//fileReader
reads
entire
file
and
stores
it
into
temp
System.out.println(fileReader.read(temp));//18
-
No
of
characters
Read
from
file
System.out.println(Arrays.toString(temp));//output
below
//[H,
o,
w,
,
a,
r,
e,
,
y,
o,
u,
,
d,
o,
i,
n,
g,
?,
,
,
,
,
,]
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
FileReader
Constructors
FileReader
constructors
can
accept
file(File)
or
the
path
to
file
(String)
as
argument.
FileReader
fileReader2
=
new
FileReader("FileName.txt");
System.out.println(fileReader2.read(temp));//24
System.out.println(Arrays.toString(temp));//output
below
BufferedWriter
Class
BufferedWriter
class
helps
writing
to
a
class
with
better
buffering
than
FileWriter.
BufferedWriter
Constructors
BufferedWriter
Constructors
only
accept
another
Writer
as
argument
FileWriter
fileWriter3
=
new
FileWriter("BufferedFileName.txt");
BufferedWriter
bufferedWriter
=
new
BufferedWriter(fileWriter3);
BufferedReader
Class
BufferedReader
helps
to
read
the
file
line
by
line
BufferedReader
Constructors
BufferedReader
Constructors
only
accept
another
Reader
as
argument.
FileReader
fileReader3
=
new
FileReader("BufferedFileName.txt");
BufferedReader
bufferedReader
=
new
BufferedReader(fileReader3);
PrintWriter
PrintWriter
constructors
PrintWriter provides advanced methods to write formatted text to the file. It supports printf function.
PrintWriter
constructors
supports
varied
kinds
of
arguments
File,
String
(File
Path)
and
Writer.
PrintWriter
printWriter
=
new
PrintWriter("PrintWriterFileName.txt");
Serialization
Serialization helps us to save and retrieve the state of an object. Serialization => Convert object state to some internal object representation. De-Serialization => The reverse. Convert internal representation to object. Two important methods ObjectOutputStream.writeObject() // serialize and write to file ObjectInputStream.readObject() // read from file and deserialize
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
System.out.println(rectangle.length);//
5
System.out.println(rectangle.breadth);//
6
System.out.println(rectangle.area);//
0
Note that the value of rectangle.area is set to 0. Variable area is marked transient. So, it is not stored into the serialized file. And when de-serialization happens area value is set to default value i.e. 0.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Java
Tutorial
For
Beginners
Rithus.com
1 3
7
Serialization
Program
2:
Make
Wall
implement
Serializable
class
Wall
implements
Serializable
{
int
length;
int
breadth;
int
color;
}
With both these programs, earlier main method would run without throwing an exception. If you try de-serializing, In Example2, state of wall object is retained whereas in Example1, state of wall object is lost.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Code executes successfully but after de-serialization, the values of super class instance variables are not retained. They are set to their initial values. When subclass is serializable and superclass is not, the state of subclass variables is retained. However, for the super class, initialization (constructors and initializers) happens again.
Threads
Threads
allow
Java
code
to
run
in
parallel.
Lets
first
understand
the
need
for
threading
and
then
look
into
how
to
create
a
thread
and
what
is
synchronization?
Steps I, II and III are independent and can be run in parallel to each other. Run individually this program takes 160 minutes. We would want to run this program in lesser time. Threads can be a solution to this problem. Threads allow us to run STEP I, II and III in parallel and run Step IV when all Steps I, II and III are completed. Need for Threads Example Below example shows the way we would write code usually without using Threads.
downloadAndStoreBowlingStatistics starts only after downloadAndStoreBattingStatistics completes execution. downloadAndStoreFieldingStatistics starts only after downloadAndStoreBowlingStatistics completes execution. What if I want to run them in parallel without waiting for the others to complete? This is where Threads come into picture.
Creating
a
Thread
by
Implementing
Runnable
interface
Thread
class
can
also
be
created
by
implementing
Runnable
interface
and
implementing
the
method
declared
in
Runnable
interface
public
void
run().
Example
below
shows
the
Batting
Statistics
Thread
implemented
by
implementing
Runnable
interface.
class
BowlingStatisticsThread
implements
Runnable
{
//run
method
without
parameters
public
void
run()
{
for
(int
i
=
0;
i
<
1000;
i++)
System.out
.println("Running
Bowling
Statistics
Thread
"
+
i);
}
}
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Running
a
Thread
Running
a
Thread
in
Java
is
slightly
different
based
on
the
approach
used
to
create
the
thread.
Thread
created
Extending
Thread
class
When
using
inheritance,
An
object
of
the
thread
needs
be
created
and
start()
method
on
the
thread
needs
to
be
called.
Remember
that
the
method
that
needs
to
be
called
is
not
run()
but
it
is
start().
BattingStatisticsThread
battingThread1
=
new
BattingStatisticsThread();
battingThread1.start();
Thread created implementing RunnableInterface. Three steps involved. Create an object of the BowlingStatisticsThread(class implementing Runnable). Create a Thread object with the earlier object as constructor argument. Call the start method on the thread.
BowlingStatisticsThread battingInterfaceImpl = new BowlingStatisticsThread(); Thread battingThread2 = new Thread( battingInterfaceImpl); battingThread2.start();
Program Output: Running Batting Statistics Thread 0 Running Batting Statistics Thread 1 .. .. Running Batting Statistics Thread 10 Running Bowling Statistics Thread 0 .. .. Running Bowling Statistics Thread 948 Running Bowling Statistics Thread 949 Running Batting Statistics Thread 11 Running Batting Statistics Thread 12 .. .. Running Batting Statistics Thread 383 Running Batting Statistics Thread 384 Running Bowling Statistics Thread 950 Running Bowling Statistics Thread 951 .. Running Bowling Statistics Thread 998 Running Bowling Statistics Thread 999 Running Batting Statistics Thread 385 .. Running Batting Statistics Thread 998 Running Batting Statistics Thread 999 Discussion about Thread Example Above output shows sample execution of the thread. The output will not be the same with every run. We can notice that Batting Statistics Thread and the Bowling Statistics Threads are alternating in execution. Batting Statistics Thread runs upto 10, then Bowling Statistics Thread runs upto 949, Batting Statistics Thread picks up next and runs up to 384 and so on. There is no usual set pattern when Threads run (especially when they have same priority more about this later..). JVM decides which Thread to run at which time. If a Thread is waiting for user input or a network connection, JVM runs the other waiting Threads.
Thread
Synchronization
Since
Threads
run
in
parallel,
a
new
problem
arises.
i.e.
What
if
thread1
modifies
data
which
is
being
accessed
by
thread2?
How
do
we
ensure
that
different
threads
dont
leave
the
system
in
an
inconsistent
state?
This
problem
is
usually
called
Thread
Synchronization
Problem.
Lets
first
look
at
an
example
where
this
problem
can
occur.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Serial
Run
Lets
first
run
the
above
example
in
a
serial
way
and
see
what
the
output
would
be.
public
static
void
main(String[]
args)
{
SpreadSheet
spreadSheet
=
new
SpreadSheet();
for
(int
i
=
0;
i
<
4;
i++)
{
System.out.print(spreadSheet.setandGetSum(i,
i
*
2,
i
*
3)
+
"
");
}
}
Program
Output
0
6
12
18
Output
would
contain
a
multiple
of
6
always
because
we
are
calling
with
i,
i*2
and
i*3
and
summing
up.
So,
the
result
should
generally
be
i*6
with
i
running
from
0
to
3.
Example
Program
using
Threads
Lets
now
run
the
SpreadSheet
class
in
a
Thread.
Example
Code
below:
public
class
ThreadExampleSynchronized
implements
Runnable
{
SpreadSheet
spreadSheet
=
new
SpreadSheet();
public
void
run()
{
for
(int
i
=
0;
i
<
4;
i++)
{
System.out.print(
We
are
creating
2
instances
of
the
Thread
using
the
interface
one
and
two.
And
start
method
is
invoked
to
run
the
thread.
Both
threads
share
the
instance
of
SpreadSheet
class
spreadsheet.
Program
Output
FIRST
RUN
:
0
1
6
9
12
15
18
18
SECOND
RUN
:
0
3
6
6
12
15
18
18
THIRD
RUN
:
0
3
6
9
12
15
18
18
Program
Output
Discussion
What
we
see
is
that
different
runs
have
different
results.
Thats
expected
with
threads.
What
is
not
expected
is
to
see
numbers
like
1,
9,
15
and
3
in
the
output.
We
are
expecting
to
see
multiples
of
6
in
the
output(as
in
the
earlier
serial
run)
but
we
see
numbers
which
are
not
multiples
of
6.
Why
is
this
happening?
This
is
a
result
of
having
two
threads
run
in
parallel
without
synchronization.
Consider
the
code
in
the
setAndGetSum
method.
int
setandGetSum(int
a1,
int
a2,
int
a3)
{
cell1
=
a1;
sleepForSomeTime();
cell2
=
a2;
sleepForSomeTime();
cell3
=
a3;
sleepForSomeTime();
return
cell1
+
cell2
+
cell3;
}
After setting the value to each cell, there is a call for the Thread to sleep for some time. After Thread 1 sets the value of cell1, it goes to Sleep. So, Thread2 starts executing. If Thread 2 is executing return cell1 + cell2 + cell3;, it uses cell1 value set by Thread 1 and cell2 and cell3 values set by Thread 2. This results in the unexpected results that we see when the method is run in parallel. What is explained is one possible scenario. There are several such scenarios possible.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Output of the program now is 0 0 6 6 12 12 18 18. This is expected output all numbers are multiples of 6.
Static and non static synchronized methods and blocks Static methods and block are synchronized on the class. Instance methods and blocks are synchronized on the instance of the class i.e. an object of the class. Static synchronized methods and instance synchronized methods dont affect each other. This is because they are synchronized on two different things.
States
of
a
Thread
Different
states
that
a
thread
can
be
in
are
defined
the
class
State.
NEW;
RUNNABLE;
RUNNING;
BLOCKED/WAITING;
TERMINATED/DEAD;
Program Output Running Batting Statistics Thread 0 Running Batting Statistics Thread 1 .. .. Running Batting Statistics Thread 10 Running Bowling Statistics Thread 0 .. .. Running Bowling Statistics Thread 948 Running Bowling Statistics Thread 949 Running Batting Statistics Thread 11 Running Batting Statistics Thread 12 .. .. Running Batting Statistics Thread 383 Running Batting Statistics Thread 384 Running Bowling Statistics Thread 950 Running Bowling Statistics Thread 951 .. Running Bowling Statistics Thread 998 JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Thread
Priority
Scheduler
can
be
requested
to
allot
more
CPU
to
a
thread
by
increasing
the
threads
priority.
Each
thread
in
Java
is
assigned
a
default
Priority
5.
This
priority
can
be
increased
or
decreased
(Range
1
to
10).
If
two
threads
are
waiting,
the
scheduler
picks
the
thread
with
highest
priority
to
be
run.
If
all
threads
have
equal
priority,
the
scheduler
then
picks
one
of
them
randomly.
Design
programs
so
that
they
don't
depend
on
priority.
Thread
Priority
Example
Consider
the
thread
example
declared
below:
class
ThreadExample
extends
Thread
{
public
void
run()
{
for
(int
i
=
0;
i
<
1000;
i++)
System.out
.println(
this.getName()
+
"
Running
"
+
i);
}
}
Java also provides predefined constants Thread.MAX_PRIORITY(10), Thread.MIN_PRIORITY(1), Thread.NORM_PRIORITY(5) which can be used to assign priority to a thread.
Lets
say
we
would
want
to
run
thread2
and
thread3
in
parallel
but
thread4
can
only
run
when
thread3
is
finished.
This
can
be
achieved
using
join
method.
Join
method
example
Look
at
the
example
code
below:
thread3.start();
thread2.start();
thread3.join();//wait
for
thread
3
to
complete
System.out.println("Thread3
is
completed.");
thread4.start();
thread3.join()
method
call
force
the
execution
of
main
method
to
stop
until
thread3
completes
execution.
After
that,
thread4.start()
method
is
invoked,
putting
thread4
into
a
Runnable
State.
Overloaded
Join
method
Join
method
also
has
an
overloaded
method
accepting
time
in
milliseconds
as
a
parameter.
thread4.join(2000);
In above example, main method thread would wait for 2000 ms or the end of execution of thread4, whichever is minimum.
Java
Tutorial
For
Beginners
Rithus.com
1 4
9
Method1
executes
some
code
on
resource1
first
and
then
executes
some
code
on
resource2.
Method2
does
the
reverse.
We
use
the
sleep
method
call
to
simulate
the
fact
that
these
operation
could
take
some
time
to
complete.
Lets
create
two
threads
sharing
the
above
operation
using
the
code
below:
Threads
one
and
two
now
share
object
operation.
The
thread
code
runs
both
operations
method1
and
method2.
public
class
ThreadDeadlock
implements
Runnable
{
SomeOperation
operation
=
new
SomeOperation();
@Override
public
void
run()
{
try
{
operation.method1();
operation.method2();
}
catch
(InterruptedException
e)
{
e.printStackTrace();
}
}
public
static
void
main(String[]
args)
{
ThreadDeadlock
r
=
new
ThreadDeadlock();
Thread
one
=
new
Thread(r);
Thread
two
=
new
Thread(r);
one.start();
two.start();
}
}
When
executed
this
program
just
hangs,
because
of
a
deadlock.
To
make
what
is
happening
behind
the
screens
more
clear,
Lets
add
in
a
few
sysouts
in
the
Operation
class.
class
SomeOperation
{
Resource
resource1
=
new
Resource();
Resource
resource2
=
new
Resource();
void
method1()
throws
InterruptedException
{
synchronized
(resource1)
{
System.out.println("Method1
-
got
resource1");
Thread.sleep(1000);
//code
using
resource1
System.out.println("Method1
-
waiting
for
resource2");
synchronized
(resource2)
{
System.out.println("Method1
-
got
resource2");
//code
using
resource2
}
}
}
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Output:
Method1
-
got
resource1
Method1
-
waiting
for
resource2
Method1
-
got
resource2
Method1
-
got
resource1
Method2
-
got
resource2
Method1
-
waiting
for
resource2
Method2
-
waiting
for
resource1
HANGS Now we have two threads waiting for resources held by one another. This results in a deadlock.
Java
Tutorial
For
Beginners
Rithus.com
1 5
1
public
static
void
main(String[]
args)
{
Calculator
thread
=
new
Calculator();
thread.start();
System.out.println(thread.sumUptoMillion);
}
}
Output
0
Output
printed
is
0.
This
is
because
the
thread
has
not
finished
calculating
the
value
of
sumUptoMillion
when
the
main
method
prints
the
value
to
the
output.
We
have
to
find
a
way
to
stop
the
main
method
from
running
until
sumUptoMillion
is
calculated.
One
option
is
to
use
the
join
method.
But,
join
method
would
make
the
main
method
wait
until
both
the
operations
(sumUptoMillion
and
sumUptoTenMillion)
are
completed.
But,
we
want
main
method
to
wait
only
for
sumUptoMillion.
We
can
achieve
this
using
wait
and
notify
methods.
wait
and
notify
methods
can
only
be
used
in
a
synchronized
context.
Example
with
wait
and
notify
methods
package
com.rithus.threads;
class
Calculator
extends
Thread
{
long
sumUptoMillion;
long
sumUptoTenMillion;
public
void
run()
{
synchronized
(this)
{
calculateSumUptoMillion();
notify();
}
calculateSumUptoTenMillion();
}
private
void
calculateSumUptoMillion()
{
for
(int
i
=
0;
i
<
1000000;
i++)
{
sumUptoMillion
+=
i;
}
System.out.println("Million
done");
}
private
void
calculateSumUptoTenMillion()
{
for
(int
i
=
0;
i
<
10000000;
i++)
{
sumUptoTenMillion
+=
i;
}
System.out.println("Ten
Million
done");
}
}
public
class
ThreadWaitAndNotify
{
public
static
void
main(String[]
args)
throws
InterruptedException
{
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Output
Million
done
499999500000
Ten
Million
done
Wait
method
example
Below
snippet
shows
how
wait
is
used
in
earlier
program.
wait
method
is
defined
in
the
Object
class.
This
causes
the
thread
to
wait
until
it
is
notified.
synchronized(thread){
thread.start();
thread.wait();
}
Notify
method
example
Below
snippet
shows
how
notify
is
used
in
earlier
program.
notify
method
is
defined
in
the
Object
class.
This
causes
the
object
to
notify
other
waiting
threads.
synchronized
(this)
{
calculateSumUptoMillion();
notify();
}
A combination of wait and notify methods make the main method to wait until the sum of million is calculated. However, not the main method does not wait for Sum of Ten Million to be calculated. notifyAll method If more than one thread is waiting for an object, we can notify all the threads by using notifyAll method. thread.notifyAll();
Asserts
Assertions are introduced in Java 1.4. They enable you to validate assumptions. If an assert fails (i.e. returns false), AssertionError is thrown (if assertions are enabled). assert is a keyword in java since 1.4. Before 1.4, assert can be used as identifier. To compile code using 1.3 you can use the command below javac -source 1.3 OldCode.java => assert can be used as identifier with -source 1.4,1.5,5,1.6,6 => assert cannot be used as identifier
Assertions
can
easily
be
enabled
and
disabled.
Assertions
are
disabled
by
default.
Enabling
Assertions
Enable assertions: java -ea com.rithus.AssertExamples (OR) java -enableassertions com.rithus.AssertExamples
Disable
Assertions
Disable assertions: java -da com.rithus.AssertExamples (OR) java -disableassertions com.rithus.AssertExamples
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Garbage
Collection
Garbage Collection is a name given to automatic memory management in Java. Aim of Garbage Collection is to Keep as much of heap available (free) for the program as possible. JVM removes objects on the heap which no longer have references from the heap.
Initialization
Blocks
Initialization Blocks - Code which runs when an object is created or a class is loaded There are two types of Initialization Blocks Static Initializer: Code that runs when a class is loaded. Instance Initializer: Code that runs when a new object is created.
Static
Initializer
Look at the example below:
public
class
InitializerExamples
{
static
int
count;
int
i;
static{ //This is a static initializers. Run only when Class is first loaded. //Only static variables can be accessed System.out.println("Static Initializer"); //i = 6;//COMPILER ERROR System.out.println("Count when Static Initializer is run is " + count); } public static void main(String[] args) { InitializerExamples example = new InitializerExamples(); InitializerExamples example2 = new InitializerExamples(); InitializerExamples example3 = new InitializerExamples(); } }
Code
within
static{
and
}
is
called
a
static
initializer.
This
is
run
only
when
class
is
first
loaded.
Only
static
variables
can
be
accessed
in
a
static
initializer.
Example
Output
Static
Initializer
Count
when
Static
Initializer
is
run
is
0
Even though three instances are created static initializer is run only once.
Example
Output
Instance
Initializer
Count
when
Instance
Initializer
is
run
is
1
Instance
Initializer
Count
when
Instance
Initializer
is
run
is
2
Instance
Initializer
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Examples
public
String
getName()
{
return
name;
}
public
boolean
isGood()
{
return
good;
}
public
void
setName(String
name)
{
this.name
=
name;
}
public
void
setGood(boolean
isGood)
{
this.good
=
isGood;
}
Methods
to
de-register/remove
a
listener
should
use
prefix
"remove"
and
suffix
"Listener".
They
should
accept
1
parameter
-
the
listener
object
to
be
removed
Example
public
void
removeSomeListener(MyListener
listener){
}
Regular
Expressions
Regular
Expressions
make
parsing,
scanning
and
splitting
a
string
very
easy.
We
will
first
look
at
how
you
can
evaluate
a
regular
expressions
in
Java
using
Patter,
Matcher
and
Scanner
classes.
We
will
then
look
into
how
to
write
a
regular
expression.
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Examples
Lets run this method with a regular expression to search for 12 in the string 122345612. regex("12", "122345612"); Output [0<12>, 7<12>] Output shows the matching strings 12, 12. Also, shown in the output is the starting index of each match. First 12 is present starting at index 0. The next 12 in the string starts at index 7.
Certain
characters
escaped
by
\
have
special
meaning
in
regular
expressions.
For
example,
/s
matches
a
whitespace
character.
Remember
that
to
represent
\
in
a
string,
we
should
prepend
\
to
it.
Let
us
see
a
few
examples
below.
System.out.println("\\");//prints
\
(only
one
slash)
Space
character
-
\s
regex("\\s",
"12
1234
123
");//[2<
>,
7<
>,
11<
>]
Digit
-
\d
regex("\\d",
"12
12");//[0<1>,
1<2>,
3<1>,
4<2>]
Square
brackets
are
used
in
regular
expressions
to
search
for
a
range
of
characters.
Few
examples
below.
look
for
a,b,c,d,1,2,3,4
=>Note
that
this
does
not
look
for
capital
A,B,C,D
regex("[a-d1-4]",
"azbkdm
15AB");//[0<a>,
2<b>,
4<d>,
7<1>]
regex("[a-dA-D]",
"abyzCD");//[0<a>,
1<b>,
4<C>,
5<D>]
Regular
Expressions
Multiple
Characters
+
is
used
in
regular
expression
to
look
for
1
or
more
characters.
For
example
a+
looks
for
1
or
more
character
a's.
regex("a+",
"aaabaayza");//[0<aaa>,
4<aa>,
8<a>]
*
-
0
or
more
repetitions.
Below
expression
looks
for
1
or
more
a's
followed
by
0
or
more
b's
followed
by
1
or
more
c's.
abc
=>
match.
ac=>
match
(since
we
used
*
for
b).
ab
=>
does
not
match.
regex("a+b*c+",
"abcdacdabdbc");//[0<abc>,
4<ac>]
?
-
0
or
1
repetitions.
a+b*c?
looks
for
1
or
more
a's
followed
by
0
or
more
b's
followed
by
0
or
1
c's.
a
=>
matches.
ab
=>
matches.
abc=>matches.
abcc
=>
does
not
match
(only
0
or
1
c's)
regex("a+b*c?",
"adabdabcdabccd");//[0<a>,
2<ab>,
5<abc>,
9<abc>]
[^abcd]+a
looks
for
anything
which
is
not
a
or
b
or
c
or
d,
repeated
0
or
more
times,
followed
by
a
regex("[^abcd]+a",
"efgazyazyzb");//[0<efga>,
4<zya>]
.
matches
any
character
a.c
looks
for
a
followed
by
any
character
followed
by
c.
abc
=>
match
abbc
=>
no
match
(.
matches
1
character
only)
regex("a.c",
"abca
ca!cabbc");//[0<abc>,
3<a
c>,
6<a!c>]
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM
Similarly
*?
is
reluctant
match
for
the
greedy
*
If
you
want
to
look
for
characters
.
or
*
in
a
regular
expression,
then
you
should
escape
them.
Example:
If
I
want
to
look
for
...(3
dots),
we
should
use
\.\.\.
To
represent
\.\.\.
as
string
we
should
put
two
\'s
instead
of
1.
regex("\\.\\.\\.",
"...a....b...c");//[0<...>,
4<...>,
9<...>]
Example
regexUsingScanner("a+?",
"aaaaab");//[a,
a,
a,
a,
a]
Tokenizing
Tokenizing
means
splitting
a
string
into
several
sub
strings
based
on
delimiters.
For
example,
delimiter
;
splits
the
string
ac;bd;def;e
into
four
sub
strings
ac,
bd,
def
and
e.
Delimiter
can
in
itself
be
any
of
the
regular
expression(s)
we
looked
at
earlier.
String.split(regex)
function
takes
regex
as
an
argument.
Example:
tokenize("ac;bd;def;e",";");//[ac,
bd,
def,
e]
private static void tokenizeUsingScanner(String string,String regex) { Scanner scanner = new Scanner(string); scanner.useDelimiter(regex); List<String> matches = new ArrayList<String>(); while(scanner.hasNext()){ matches.add(scanner.next()); } System.out.println(matches); }
Example:
tokenizeUsingScanner("ac;bd;def;e",";");//[ac,
bd,
def,
e]
Scanner
has
more
useful
functions
other
than
just
looking
delimiterlookForDifferentThingsUsingScanner("true
false
12
3
abc
true
154");
Output
//Found
Boolean:true
//Found
Boolean:false
//Found
Integer:12
//Found
Integer:3
//Different
thing:abc
//Found
Boolean:true
//Found
Integer:154
for
JAVA SPRING, STRUTS, AJAX & MORE - Videos, Interview Questions, Projects ON RITHUS.COM