1 - Core Java (TOC)
1 - Core Java (TOC)
Table of Contents:
1. Introduction
Installing JDK
Tokens
Explain how java is platform independent?
3. Operators
4. Control Statements
Selection Statements
If:
Nested ifs:
if-else-if Ladder:
Switch
Nested switch Statements:
Jump Statements
break.
continue.
return.
Iteration Statements
for
while
do-while.
5. Methods
7. Method Overloading
8. Constructor(Overloading)
Why Contructor?
Types of Constructor:
Default Constructor:
No-Arguments Constructor:
Differences Methods and Constructor:
Constructor Overloading:
9. Inheritance(this+Super)
Developer-Tester
Core Java JyothiShankar Mahakul 2
13. Interfaces
Explain how multiple inheritance can be achieved through interface in java?
What is Marker interface?
Difference: Abstract class & Interface
16. Polymorphism
Compile-Time Polymorphism.
Run-Time Polymorphism.
17. Abstraction
18. Encapsulation
21. IIB
22. SIB
24. Assert
Developer-Tester
Core Java JyothiShankar Mahakul 3
26. Arrays
Types of Arrays:
Primitive Array:
Derived Array:
34. Generics
Developer-Tester
Core Java JyothiShankar Mahakul 4
1. INTRODUCTION:
Installing JDK
2) Compilation:Converting the java program written in high level language into byte code by using
java compiler is called as Compilation.
Note: All the byte code will be stored as .class Extension
3) Execution: Converting the byte code into machine level language or processor understandable
instructions using JVM is called as Execution(JVM is an Interpreter).
1) Keywords: This are pre-defined words in the programming language which will have some
pre-defined meaning.
Example: class, public, static, void, etc.,
There are approximately 50 keywords.
Rules to Write keywords: All keywords must be written in lower case.
3) Literals: Literals are values used in the programs. There are 4 literals,
A) Numeric Literals:
Any number represented in java program will fall under numeric literals category.
B) Character Literals:
Any character of the keyboards enclosed within single quote and 1 character within single quote
is called as character literals. Example: A, I,9.
Developer-Tester
Core Java JyothiShankar Mahakul 5
C) String Literals:
Anything which is enclosed within double quotes are considered as String literals.
Example: hello, hello123.
D) Boolean Literals:
There are only 2 Boolean literals True and False. To take decision we will use Boolean literals.
Note:
1)True and False are also called as Reserved words.
2)0 and 1 are not Boolean literals.
3)Using System.out.println();, we can print Literals
Rule:
1) While writing java program, programmer should follow the condition of java programming
language if the programmer is not following rules and conditions of java programs then java compiler
will deploy Compile Time Error(CTE).
2) If the program results in compile time error, .class file wont be generated.
---------------------------------------------------------------------------------------------------------------------------------------
Whenever we compile a Java Program using java compile we will get the byte code which is also
called as Intermediate code which can be understood by JVM, i.e., byte code is not with respect to
and Platform it is with respect to JVM.
JVM will convert the byte code into underlying platform standards on which it is installed.
Developer-Tester
Core Java JyothiShankar Mahakul 6
Java is a strongly typed language. This means that every variable must have a declared type.
There are eight primitive types in Java.
1) Four of them are integer types.
2) Two are floating-point number types.
3) One is the character type char.
4) Boolean type for truth values.
1) Integer Types: The integer types are for numbers without fractional parts. Negative values are
allowed.
The width of an integer type should not be thought of as the amount of storage it consumes, but
rather as the behavior it defines for variables and expressions of that type.
Name Width Range
1) byte:
1) The smallest integer type is byte. This is a signed 8-bit type that has a range from 128 to 127.
2) Variables of type byte are especially useful when youre working with a stream of data from a
network or file.
3) They are also useful when youre working with raw binary data that may not be directly compatible
with Javas other built-in types.
4) byte variables are declared by use of the byte keyword.
Example: byte b, c;
2) short:
1) short is a signed 16-bit type. It has a range from 32,768 to 32,767.
2) It is probably the least-used Java type.
Example: short s; short t;
Developer-Tester
Core Java JyothiShankar Mahakul 7
3) int:
1) The commonly used integer type is int. It is a signed 32-bit type that has a range from
2,147,483,648 to 2,147,483,647.
2) Variables of type int are commonly employed to control loops and to index arrays.
When byte and short values are used in an expression they are promoted to int when the expression
is evaluated.
4) long:
1) long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value.
2) The range of a long is quite large. This makes it useful when big, whole numbers are needed.
Example:
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days+ " days light will travel about " +distance + " miles.");
}
}
Output: In 1000 days light will travel about 16070400000000 miles.
---------------------------------------------------------------------------------------------------------------------------------------
2) Floating-Point Types: The floating-point(also known as real numbers,) types denote numbers with
fractional parts. They are used when evaluating expressions that require fractional precision.
There are two kinds of floating-point types, float and double, which represent single- and
double-precision numbers, respectively.
5) float:
1) The type float specifies a single-precision value that uses 32 bits of storage.
2) Single precision is faster on some processors and takes half as much space as double precision, but
will become imprecise when the values are either very large or very small.
3) Variables of type float are useful when you need a fractional component.
Example: float hightemp, lowtemp;
6) double:
1)Double precision, as denoted by the double keyword, uses 64 bits to store a value.
2)Double precision is actually faster than single precision.
3)All transcendental math functions, such as sin( ), cos( ), and sqrt( ) return double values.
Example: program that uses double variables to compute the area of a circle:
class Area {
public static void main(String args[]{
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 8
3) Character-Types:
1) The data type used to store characters is char.char is a 16-bit type.
2) The range of a char is 0 to 65,536. There are no negative chars.
3) The standard set of characters known as ASCII still ranges from 0 to 127 and the extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255.
Example:
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output:
ch1 and ch2: X Y
---------------------------------------------------------------------------------------------------------------------------------------
4) Boolean:
1) Java has a primitive type, called Boolean, for logical values.
2) It can have only one of two possible values, true or false. T
3) his is the type returned by all relational operators, as in the case of a < b.
4) Boolean is also the type required by the conditional expressions that govern the control
statements such as if and for.
Example:
class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b)
System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Output:
b is false
b is true
This is executed.
10 > 9 is true
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 9
Variables
1) Declaring a Variable:
a) In Java, all variables must be declared before they can be used.
b) Declaration means Creation.
c) Syntax:
type identifier [ = value][, identifier [= value] ...] ;
type: is one of Javas atomic types, or the name of a class or interface.
Identifier: is the name of the variable.
Note: To declare more than one variable of the specified type, use a comma separated list.
2) Initialization:
a) It means storing a value inside the varibales.
b) Syntax:
Variables name=value;
Example: A=90;
3) Utilization:
a) Using the value stored in the variable for some purpose is called as Utilization.
b) Using System.out.println(); we can print the value stored in the variables.
Example:
public class Simple1
{
public static void main(String[] args)
{
int stdId; //Declration
double stdPercent;
boolean passed;
stdId=10; //Initialization
stdPercent=99.9;
passed=true;
System.out.println(stdId); ////Utilization
System.out.println(stdPercent);
System.out.println(passed);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 10
Output:
10
99.9
true
Example:
class Simple2
{
public static void main(String[] args)
{
int empId;
double empSal;
char empGrade;
empId=7;
empSal=900000;
empGrade='A';
Output:
Employee Id:7
Employee Salary:900000.0
Employee Grade:A
Example:
class Simple3
{
public static void main(String[] args)
{
int a;//Declaration
a=90;//Initialization
System.out.println(a);//Utilization
System.out.println(a);//Re-itilization
}
}
Output:
90
190
Example:
class Simple7
{
public static void main(String[] args)
{
int a=90;
int a=190;
System.out.println(a);
}
}
Output:
Uncompilable source code - variable a is already defined in method main(java.lang.String[])
Developer-Tester
Core Java JyothiShankar Mahakul 11
Note:
1) Primitive variables: The variables which are declared using any one of the 8 primitive data type are
called as Primitive variables.
2) Strng is not a primitive data type, it is a Bult-in class.
Example: int a; double d;
3) We cannot create 2 variable with the same name, inside a same method or block.
4) Character values has to be enclosed with single quote. Example: A.
5) Assignement is done at the RHS, RHS operation is evaluated and stored in LHS as result.
Developer-Tester
Core Java JyothiShankar Mahakul 12
Example: Print the word fizz if number is completely divisible by 3 between the range of number 1
to 10.
class Fizz
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i%3==0)
{
System.out.println("fizz=" +i);
}
}
}
}
Output:
fizz=3
fizz=6
fizz=9
Developer-Tester
Core Java JyothiShankar Mahakul 13
Example: Print Fizz if the number is completely divisible by 3, and print buzz if divisible by 5 and
print FizzBuzz if the number is divisible bu both 3 and 5 between the range of 1 till 20.
class FizzBuzz
{ // first print the FizzBuzz condition because I%3==0 && I%5==0 may skip the 2nd condition.
public static void main(String[] args)
{
for(int i=1;i<=20;i++)
{
if(i%3==0 && i%5==0)
{
System.out.println("FizzBuzz" +i);
}
else if(i%3==0)
{
System.out.println("Fizz" +i);
}
else if(i%5==0)
{
System.out.println("Buzz" +i);
}
}
}
}
Output:
Fizz3
Buzz5
Fizz6
Fizz9
Buzz10
Fizz12
FizzBuzz15
Fizz18
Buzz20
Example:
class Simple17
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)//Outer Loop
{
for(int j=1;j<=i;j++)//Inner Loop
{
System.out.print("*");//Printing *
}
System.out.println("");//Number of rows
}
}
}
Output:
*
**
***
****
*****
Developer-Tester
Core Java JyothiShankar Mahakul 14
Note:
1) Outer For loop should concentrate on Number of Rows.
2) Inner For loop should concentrate on Printing *.
Execution:
Step 1:
when i=1, is 1<=5? true then Goto Inner loop when j<=i, i.e., 1<=1? true
print *
now 2<=1? false then Goto Outer loop
Step 2:
when i=2, is 2<=5? true then Goto Inner loop when j<=i, i.e., 1<=2? true and 2<=2? true
print * *
now 3<=2? false then Goto Outer loop
Step 3:
when i=3, is 3<=5? true then Goto Inner loop when j<=i, i.e., 1<=3? true and 2<=3? true 3<=3?true
print * * *
now 4<=3? false then Goto Outer loop
Step 4:
when i=4, is 4<=5? true then Goto Inner loop when j<=i, i.e., 1<=4? true and 2<=4? true 3<=4?true
4<=4? true print * * * *
now 5<=4? false then Goto Outer loop
Step 5:
when i=5, is 5<=5? true then Goto Inner loop when j<=i, i.e., 1<=5? true and 2<=5? true 3<=5?true
4<=5? true 5<=5 true print * * * * *
Exit
Example:
class Simple18
{
public static void main(String[] args)
{
int a=1; //2 //3 //4
for(int i=1;i<5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(a );
a++;
}
System.out.println();
}
}
}
Output:
1
23
456
78910
Developer-Tester
Core Java JyothiShankar Mahakul 15
Developer-Tester
Core Java JyothiShankar Mahakul 16
Example:
class Simple22
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print((i+j)%2);
}
System.out.println();
}
}
}
Output:
0
10
010
1010
01010
Note:
i=1;j=1=>System.out.print((1+1)/2)
i=2;j=1->2=>System.out.print((2+1)/2)
Developer-Tester
Core Java JyothiShankar Mahakul 17
Example:
class Simple23
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=0;j<i;j++)
{
System.out.print((i+j)%2);
}
System.out.println();
}
}
}
Output:
1
01
101
0101
10101
Example:
1) int a, b, c; // declares three ints, a, b, and c.
2) int d = 3, e, f = 5; // declares three more ints, initializing // d and f.
3) byte z = 22; // initializes z.
4) double pi = 3.14159; // declares an approximation of pi.
5) char x = 'x'; // the variable x has the value 'x'.
---------------------------------------------------------------------------------------------------------------------------------------
Constants
Example:
public class Constants
{
public static void main(String[] args)
{
final double CM_PER_INCH = 2.54;
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " +
paperHeight * CM_PER_INCH);
}
}
Note:
1) The keyword final indicates that you can assign to the variable once, and then its value is set once
and for all. It is customary to name constants in all uppercase.
2) It is probably more common in Java to create a constant so its available to multiple methods
inside a single class. These are usually called class constants.
3) Set up a class constant with the keywords static final.
Developer-Tester
Core Java JyothiShankar Mahakul 18
Java allows variables to be initialized dynamically, using any expression valid at the time the variable
is declared.
Example: program that computes the length of the hypotenuse of a right triangle given the lengths of
its two opposing sides:
Class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Note:
1) Here, three local variablesa, b, and care declared.
2) The first two, a and b, are initialized by constants.
3) However, c is initialized dynamically to the length of the hypotenuse.
4) The program uses another of Javas built-in methods, sqrt( ), which is a member of the Math class,
to compute the square root of its argument.
5) The key point here is that the initialization expression may use any element valid at the time of the
initialization, including calls to methods, other variables, or literals.
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 19
Rule:
1) Variables declared inside a scope are not visible (that is, accessible) to code that is defined outside
that scope.
2) Thus, when you declare a variable within a scope, you are localizing that variable and protecting it
from unauthorized access and/or modification.
3) Indeed, the scope rules provide the foundation for encapsulation. Scopes can be nested.
4) Each time you create a block of code, you are creating a new, nested scope. When this occurs, the
outer scope encloses the inner scope.
5) This means that objects declared in the outer scope will be visible to code within the inner scope.
6) The reverse is not true. Objects declared within the inner scope will not be visible outside it.
Example:
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block // x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}// y = 100; // Error! y not known here, x is still known here.
System.out.println("x is " + x);
}
}
Note:
1) Variables are created when their scope is entered, and destroyed when their scope is left.
2) This means that a variable will not hold its value once it has gone out of scope.
3) Therefore, variables declared within a method will not hold their values between calls to that
method. Also, a variable declared within a block will lose its value when the block is left.
4) If a variable declaration includes an initializer, then that variable will be reinitialized each time the
block in which it is declared is entered.
Developer-Tester
Core Java JyothiShankar Mahakul 20
1) Local Variables:
a) Variables which are declared inside a method or block are called as Local Variables.
b) Local Variables scope/Visibility is only inside a method in which it is declared, i.e., Local Variables
cannot be accessed outside the method in which it is created/declared.
c) Access modifiers cannot be used for local variables.
d) Local var are implemented at stack level internally & executed when method enters the
stack.
e) Local variables cannot be categorized into static or non-static variables.
Developer-Tester
Core Java JyothiShankar Mahakul 21
3. OPERATORS
1) Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra.
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
Note:
1)The operands of the arithmetic operators must be of a numeric type.
2) You cannot use them on Boolean types, but you can use them on char types.
Developer-Tester
Core Java JyothiShankar Mahakul 22
Output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
---------------------------------------------------------------------------------------------------------------------------------------
2) Modulus Operator:
The modulus operator, %, returns the remainder of a division operation.
It can be applied to floating-point types as well as integer types.
Example:// Demonstrate the % operator.
class Modulus
{
public static void main(String args[])
{
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Output:
x mod 10 = 2
y mod 10 = 2.25
---------------------------------------------------------------------------------------------------------------------------------------
3) Arithmetic Compound Assignment Operators:
Java provides special operators that can be used to combine an arithmetic operation with
an assignment.
Example:
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
This version uses the += compound assignment operator. Both statements perform the same
action,they increase the value of a by 4.
Example:
a = a % 2;
which can be expressed as
a %= 2;
In this case, the %= obtains the remainder of a/2 and puts that result back into a.
There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form
var = var op expression;
can be rewritten as
var op= expression;
Developer-Tester
Core Java JyothiShankar Mahakul 23
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Output:
a=6
b=8
c=3
---------------------------------------------------------------------------------------------------------------------------------------
4) Increment and Decrement:
Example:
a) x = x + 1;
can be rewritten like this by use of the increment operator:
b) x++;
Similarly, this statement:
c) x = x - 1;
is equivalent to
x--;
Note:
In prefix form, the operand is incremented or decremented before the value is obtained for use
in the expression.
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the increment occurs before x is assigned to y.
Thus, the line y = ++x; is the equivalent of these two statements:
x = x +1;
y = x;
In postfix form, the previous value is obtained for use in the expression, and then the operand
is modified.
x = 42;
y = x++;
In this case, value of x is obtained before the increment operator is executed, so the value of y is 42.
Of course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these two
statements:
y = x;
x = x + 1;
Developer-Tester
Core Java JyothiShankar Mahakul 24
Output:
a = 2
b = 3
c = 4
d = 1
-----------------------------------------------------------------------
5)Bitwise Operators:
Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands.
Operator Result
| Bitwise OR
^ Bitwise exclusive OR
|= Bitwise OR assignment
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 25
Example:
00101010 42
& 00001111 15
00001010 10
Developer-Tester
Core Java JyothiShankar Mahakul 26
5) b. Left Shift:
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
Syntax:
value << num
Here,
num specifies the number of positions to left-shift the value in value.
That is, the << moves all of the bits in the specified value to the left by the number of bit positions
specified by num.
For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on the right.
This means that when a left shift is applied to an int operand, bits are lost once they are shifted past
bit position 31. If the operand is a long, then bits are lost after bit position 63.
5) b. Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times.
Syntax:
value >> num
Here,
num specifies the number of positions to right-shift the value in value.
That is, the >> moves all of the bits in the specified value to the right the number of bit positions
specified by num.
The following code fragment shifts the value 32 to the right by two positions, resulting
in a being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
When a value has bits that are shifted off, those bits are lost.
For example, the next code fragment shifts the value 35 to the right two positions, which causes the
two low-order
bits to be lost, resulting again in a being set to 8.
int a = 35;
a = a >> 2; // a still contains 8
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 27
6) Relational Operators:
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.
The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop statements.
Operator Result
== Equal to
!= Not equal to
Operator Result
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
Developer-Tester
Core Java JyothiShankar Mahakul 28
Example: Here is a program that is almost the same as the BitLogic example shown earlier, but it
operates on boolean logical values instead of binary bits:
class BoolLogic
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
After running this program, you will see that the same logical rules apply to boolean values as they did
to bits.
Output: the string representation of a Java boolean value is one of the literal values true or false:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
---------------------------------------------------------------------------------------------------------------------------------------
8) Assignment Operator:
The assignment operator is the single equal sign, =. The assignment operator works in Java much
as it does in any other computer language.
Syntax:
var = expression;
Here, the type of var must be compatible with the type of expression.
The assignment operator does have one interesting attribute that you may not be familiar with:
it allows you to create a chain of assignments.
Example:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.
This works because the = is an operator that yields the value of the right-hand expression.
Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x.
Using a chain of assignment is an easy way to set a group of variables to a common value.
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 29
9) ? Operator:
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements.
This operator is the ?. It can seem somewhat confusing at first, but the ? can be used very effectively
once mastered.
Syntax:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value.
If expression1 is rue, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the ? operation is that of the expression evaluated.
Both expression2 and expression3 are required to return the same type, which cant be void.
Example: Demonstrate ?.
class Ternary
{
public static void main(String args[])
{
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Output:
Absolute value of 10 is 10
Absolute value of -10 is 10
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 30
4. CONTROL STATEMENTS
Javas program control statements can be put into the following categories:
1) Selection.
2) Iteration.
3) jump.
1) Selection statements: allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
2) Iteration statements: enable program execution to repeat one or more statements (that is,
iteration statements form loops).
3) Jump statements: allow your program to execute in a nonlinear fashion.
Selection Statements
A) I. If:
The if statement is Javas conditional branch statement. It can be used to route program execution
Syntax:
if (condition)
statement1;
else
statement2;
Here:
each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block).
The condition is any expression that returns a boolean value. The else
clause is optional.
Working:
If the condition is true, then statement1 is executed.
Otherwise, statement2 (if it exists) is executed.
In no case will both statements be executed.
int a, b;
// ...
if(a < b)
a = 0;
else
b = 0; //Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero
Developer-Tester
Core Java JyothiShankar Mahakul 31
Here,
as the comments indicate, the final else is not associated with if(j<20) because it is not
in the same block (even though it is the nearest if without an else).
Rather, the final else is associated with if(i==10).
The inner else refers to if(k>100) because it is the closest if within the same block.
Developer-Tester
Core Java JyothiShankar Mahakul 32
B) I. switch
The switch statement is Javas multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression.
Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
Rules:
1) The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression.
2) Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate
case values are not allowed.
Working:
1) The value of the expression is compared with each of the literal values in the case statements.
2) If a match is found, the code sequence following that case statement is executed.
3) If none of the constants matches the value of the expression, then the default statement is
executed.
4) However, the default statement is optional. If no case matches and no default is present, then no
further action is taken.
Note:
The break statement is used inside the switch to terminate a statement sequence.
When a break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of jumping out of the switch.
Developer-Tester
Core Java JyothiShankar Mahakul 33
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Summary:
there are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can evaluate
any type of Boolean expression. That is, the switch looks only for a match between the value of the
expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a switch
statement and an enclosing outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.
Developer-Tester
Core Java JyothiShankar Mahakul 34
Jump Statements
A) break:
In Java, the break statement has three uses.
1) It terminates a statement sequence in a switch statement.
2) It can be used to exit a loop.
3) It can be used as a civilized form of goto.
Working:
Although the for loop is designed to run from 0 to 99, the break statement causes it to terminate
early, when i equals 10.
The break statement can be used with any of Javas loops, including intentionally infinite loops.
Developer-Tester
Core Java JyothiShankar Mahakul 35
Points to remember:
First, more than one break statement may appear in a loop. However, be careful. Too many
break statements have the tendency to destruct your code.
Second, the break that terminates a switch statement affects only that switch statement and not
any enclosing loops.
Developer-Tester
Core Java JyothiShankar Mahakul 36
Output:
Before the break.
This is after second block.
Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 37
B) continue:
In while and do-while loops, a continue statement causes control to be transferred directly to
the conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and then to the
conditional expression.
For all three loops, any intermediate code is bypassed.
Developer-Tester
Core Java JyothiShankar Mahakul 38
Output:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
---------------------------------------------------------------------------------------------------------------------------------------
C) return:
The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
At any time in a method the return statement can be used to cause execution to branch back to
the caller of the method.
Thus, the return statement immediately terminates the method in which it is executed.
1) while:
It repeats a statement or block while its controlling expression is true.
Syntax:
while(condition)
{
// body of loop
}
Here,
The condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional expression is true.
When condition becomes false, control passes to the next line of code immediately following the loop.
The curly braces are unnecessary if only a single statement is being repeated.
Developer-Tester
Core Java JyothiShankar Mahakul 39
Example: while loop that counts down from 10, printing exactly ten lines of tick:
class While
{
public static void main(String args[])
{
int n = 10;
while(n > 0)
{
System.out.println("tick " + n);
n--;
}
}
}
Output: When you run this program, it will tick ten times:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Note:Since the while loop evaluates its conditional expression at the top of the loop, the body
of the loop will not execute even once if the condition is false to begin with.
---------------------------------------------------------------------------------------------------------------------------------------
2) do-while:
The do-while loop always executes its body at least once, because its conditional expression is at
the bottom of the loop.
Syntax:
do
{
// body of loop
}
while (condition);
Note:
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop terminates.
As with all of Javas loops, condition must be a Boolean expression.
Example:
class DoWhile
{
public static void main(String args[])
{
int n = 10;
do
{
System.out.println("tick " + n);
n--;
}
while(n > 0);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 40
/*The loop in the preceding program, while technically correct, can be written more efficiently as
follows:*/
do
{
System.out.println("tick " + n);
}
while(--n > 0);
Usage: The do-while loop is especially useful when you process a menu selection, because you
will usually want the body of a menu loop to execute at least once.
Developer-Tester
Core Java JyothiShankar Mahakul 41
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Output:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);
---------------------------------------------------------------------------------------------------------------------------------------
3) for:
Beginning with JDK 5, there are two forms of the for loop.
A) for form.
B) for-each form.
Syntax:
for(initialization; condition; iteration)
{
}
3. A) for loop:
1) When the loop first starts, the initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which acts as a counter that controls the
loop. It is important to understand that the initialization expression is only executed once.
2) Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control
variable against a target value. If this expression is true, then the body of the loop is executed. If it is
false, the loop terminates.
3) Next, the iteration portion of the loop is executed. This is usually an expression that increments or
decrements the loop control variable. The loop then iterates, first evaluating the conditional
expression, then executing the body of the loop, and then executing the iteration expression with
each pass.
This process repeats until the controlling expression is false.
Developer-Tester
Core Java JyothiShankar Mahakul 42
3. B) for-Each:
A for-each style loop is designed to cycle through a collection of objects, such as an array, in
strictly sequential fashion, from start to finish.
The advantage of this approach is that no new keyword is required, and no preexisting code is broken.
Syntax:
NOTE:
1. Enhanced for loop was designed in JDK 1.5.
2. To fetch the element stored in array and collections without any condition, we can use extended
for loop.
3. Enhanced for loop is also called as for-each loop because each and every element will be fetched
without fail.
4. Enhanced for loop can be used only for arrays and collections.
5. If you want to perform a common operation on all the elements stored in a array or collection then
best approach is using enhanced for loop
Syntax:
Developer-Tester
Core Java JyothiShankar Mahakul 43
3. C) Nested loops:
Like all other programming languages, Java allows loops to be nested. That is, one loop may
be inside another. For example, here is a program that nests for loops:
Output:
..........
.........
........
.......
......
.....
....
...
..
.
Developer-Tester
Core Java JyothiShankar Mahakul 44
6. METHODS
Introduction
Definition: A Java Method is a collection of statements that are grouped together to perform an
operation and executed whenever called or invoked.
Why methods?
Re-Usability
Syntax:
Access-level modifier return-type method-name(arguments)
{
Body of method
}
Program Execution:
someMethod(type
Variable) Some Class
{
}
ClassLoader return();
(someMethod) Main method Some-method()
main()
Call
Java Virtual Machine
call
Garbage Collector
Part-1:
Developer-Tester
Core Java JyothiShankar Mahakul 45
Part-2:
1) JVM will check the availability of main method in the static pool, if its available, JVM will load the
main method for execution purpose.
2) JVM will pass the control to main method so that main method can execute its statement.
Part-3:
1) From main method, some method is called by using static pool name i.e.,
Classname.someMethod(1);
2) someMethod() will be loaded onto the stack.
3) Control will pass to the someMethod(), so it can executes its statement.
4) someMethod() after its execution will return the control back to main method.
5) someMethod() will be erased from the stack.
6) Main method resume its execution and finally it will return the control back to JVM.
7) Main method will be erased from stack.
8) JVM will call Garbage Collector(Daemon Thread).
9) Garbage Collector will clear the contents from the HEAP memory.
10) JVM will exit from the stack.
Example:
public class Simple1
{
static void square(int num)
{
int sq = num*num;
System.out.println("Result is" +sq);
return;
}
public static void main(String[] args)
{
Simple1.square(2);//Method invocation
}
}
Output:
4
Example:
public class Simple2
{
static void cube(int num)
{
int c=num*num*num;
System.out.println("Result is: " +c);
}
public static void main(String[] args)
{
Simple2.cube(3);
}
}
Output:
Result is: 27
Developer-Tester
Core Java JyothiShankar Mahakul 46
Note:
1) void means return no value but return control.
2) If the method return-type is void, then that method cannot return any value after processing.
3) If any methods return-type is void, then developing return statement is not mandatory.
4) If any methods return-type is void and if the programmer has not developed to return statement
then compiler will develop return statement automatically at compile time.
5) Developing methods with arguments is not mandatory i.e., we can develop methods without
arguments.
6) The methods without arguments cannot receive any input at the time of method invocation.
Output:
CTE
Return type required
Note:
Can we develop a method without return type?
No, we cannot develop any method without return type, return type is mandatory should be
either a primitive data type or Derived Data-type or void, but arguments for a method is not
mandatory
Output:
Result is :81
Developer-Tester
Core Java JyothiShankar Mahakul 47
Example:
public class Simple7
{
static int test()
{
return 90;
}
public static void main(String[] args)
{
int res=Simple7.test();
System.out.println("Result is :" +res);
}
}
Output:
Result is :90
Example:
public class Simple8
{
static double test()
{
return 90.5;
}
public static void main(String[] args)
{
System.out.println(Simple8.test());
}
}
Output:
90.5
Note:
In System.out.println we cannot call the method of type void, which cannot return value.
We can call only non-void method.
Output:
Erroneous tree type:
Developer-Tester
Core Java JyothiShankar Mahakul 48
Note:
If the methods Return type is void, we cannot call it in System.out.println or having the
System.out.println we can only call those methods which will return some value(non-void method).
When we opt for void method?
Whenever we are not expecting any return value from the method agter processing then we should
develop those method with return type.
When we opt for non-void method?
Whenever we are expecting the return value from the method and based on that return value if we
want to do further processing then we should choose non-void method.
Example: Given 2 integers return true(boolean) if sum of them is 30 or one of them is 30.
public class Simple10
{
static boolean test(int n1,int n2)
{
if(n1+n2==30||n1==30||n2==30)
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
System.out.println("Result is " +Simple10.test(10, 20));
System.out.println("Result is " +Simple10.test(20, 20));
}
}
Output:
Result is true
Result is false
Example: Given 2 integers return twice there sum if both are same otherwise return their sum.
public class Simple11
{
static int twiceSum(int a,int b)
{
if(a==b)
{
return 2*(a+b);
}
else
return (a+b);
}
public static void main(String[] args)
{
System.out.println("Result is :" +Simple11.twiceSum(10,20));
System.out.println("Result is :" +Simple11.twiceSum(10,20));
System.out.println("Result is :" +Simple11.twiceSum(10,10));
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 49
Output:
Result is :30
Result is :30
Result is :40
Example: There are 2 monkeys, if both the monkeys are smiling then we are in trouble, if both the
monkeys are not smiling then also we are in trouble, Return true if we are in trouble.
public class Simple12
{
static boolean trouble(boolean a, boolean b)
{
if(a==true && b==true)
{
return true;
}
else if(a==false && b==false)
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
System.out.println("Result is:" +Simple12.trouble(true, true));
System.out.println("Result is:" +Simple12.trouble(false, false));
System.out.println("Result is:" +Simple12.trouble(true, false));
System.out.println("Result is:" +Simple12.trouble(false, true));
}
}
Output:
Result is:true
Result is:true
Result is:false
Result is:false
Developer-Tester
Core Java JyothiShankar Mahakul 50
Class
Syntax:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
Member of a class
The methods and variables defined within a class are called members of the class.
There are 2 types of members:
a) Static Members.
b) Non-Static Members.
a) Static Members:
a) Any Members declared with the keyword Static is called as Static Members.
b) Static Members include Static Variables, static Methods and Static Initialization Block(SIB).
c) To access the Static members of a class we should use classname.staticmembername,
because static members will be loaded onto static pool by class loader and the static pool
name would be similar to class name.
b) Non-Static Members:
a) Any members declared without the keyword Static keyword is called as Non-Static
Members.
b) Non-Static Members includes Non-static Variables, Non-static Methods and Non-static
blocks or Instance Initialization Block(IIB).
c) To access the non-static members of a class we should Create Object of a class or we
should create instance of a class or we should Instantiate the class.
d) To access the Non-Static members of a class we should use
Class-name reference-variables = new Class-name(
Developer-Tester
Core Java JyothiShankar Mahakul 51
Output:
Running test method()
Note:
1) New operator is used to create new address space or non-static pool somewhere in the heap
Memory.
2) Class-name() will load all the non-static members of class onto the address space created by new
operator.
3) Reference variables will store the address of the object so that we can refer the object.
4) Class-name is a reference variable type i.e., reference variable(rv) is a reference variable of Class.
Example:
public class Simple2
{
void test()
{
System.out.println("Runnig test method");
}
public static void main(String[] args)
{
Simple2 s2=new Simple2();
s2.test();
Simple2 s22=new Simple2();
s22.test();
}
}
Output:
Runnig test method
Runnig test method
Developer-Tester
Core Java JyothiShankar Mahakul 52
Output:
Running Test method
Value of a9
Example: Static Members, need not create reference variable, just access using
Clasname.staticmember-name
public class Simple4
{
static int a=90;//Static variable
static void test()//static member
{
System.out.println("Runnig test method");
}
public static void main(String[] args)
{
System.out.println("Value of a is " +Simple4.a);
Simple4.test();
}
}
Output:
Value of a is 90
Running test method
Simple5 s5=new Simple5(); //first create new address space and create a reference
s5.test2(); //reference varibale used to access the non-static method which is in heap
memory
System.out.println("Value of b is " +s5.b);
}
}
Output:
Running test method
Value of a is 10
Running test2 method
Value of b is 20
Developer-Tester
Core Java JyothiShankar Mahakul 53
Note:
1) We can have Single copy of static members.
2) If you want to have only one copy of any member e should declare the member with keyword
static.
3) If the requirements is fixed then we should go for static members.
4) Ex: addition() logic.
5)
1) Whenever we need to have multiple copy of any member we should go for non-static.
2) If the requirements is not fixed then we should go for non-static members
3) Ex: salary(), percentage()
Note:
1) Method arguments are also Local Variables.
2) We can call a method by supplying the value through variables.
3) Local variables can have same name across different methods.
4) Local variables are method members and created when method enter into stack and destroyed
when method leaves the stack after execution.
Example: Program to perform swapping of 2 numbers stored in the variables using temp variable.
public class Simple7
{
static void swap(int num1,int num2)
{
int temp=num1;
num1=num2;
num2=temp;
System.out.println("number1: " +num1);
System.out.println("number2: " +num2);
}
public static void main(String[] args)
{
int num1=10;
int num2=20;
System.out.println("number1:" +num1);
System.out.println("number2:" +num2);
Simple7.swap(num1, num2);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 54
Output:
number1:10
number2:20
number1: 20
number2: 10
Example: Program to perform swapping of 2 numbers stored in the variables without using temp
variable.
public class Simple8
{
static void swap(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
System.out.println("a=" +a);
System.out.println("b=" +b);
}
public static void main(String[] args)
{
int a=10;
int b=20;
System.out.println("Before Swapping");
System.out.println("a=" +a);
System.out.println("b=" +b);
System.out.println("After Swapping");
Simple8.swap(a, b);
}
}
Output:
Before Swapping
a=10
b=20
After Swapping
a=20
b=10
Example: Program to perform swapping of 2 numbers stored in the variables without using temp
variable.
public class Simple9 {
static void swap(int a, int b) {
a=(b-a)+(b=a);
System.out.println("a=" +a);
System.out.println("b=" +b);
}
public static void main(String[] args)
{
int a=10;
int b=30;
System.out.println("Before Swapping");
System.out.println("a= " +a);
System.out.println("b= " +b);
System.out.println("Aftwr Swapping");
Simple9.swap(a, b);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 55
Output:
Before Swapping
a= 10
b= 30
Aftwr Swapping
a=30
b=10
Note:
1) Global variables will reside in the heap memory, it will be there till the end of program.
2) If its STATIC , will be in static pool(class Variable).
3) If its NON-STATIC, will be in Object space(Instance Variable).
Example:
public class Simple10
{
static int count=0;
static void click()
{
System.out.println("Button clicked");
Simple10.count++;
}
public static void main(String[] args)
{
System.out.println("Total clicks: " +Simple10.count);
Simple10.click();
Simple10.click();
System.out.println("Total clicks: " +Simple10.count);
Simple10.click();
Simple10.click();
System.out.println("Total clicks: " +Simple10.count);
}
}
Output:
Total clicks: 0
Button clicked
Button clicked
Total clicks: 2
Button clicked
Button clicked
Total clicks: 4
Note:
1) By default, local variables value is not assigned. Programmer should assign it.
2) Before using any variables it should have some value.
3) Global variables will be assigned with default value.
4) Local variables will not be assigned with default value.
5) Global variables can b e used without initializing it explicitly.
6) Local variables should be initialized before usage.
7) Static means 1 copy, non-static means multiple copy.
8) Any kind of variables(static.non-static) can be FINAL.
Developer-Tester
Core Java JyothiShankar Mahakul 56
Output:
variable a might not have been initialized
Example:
public class Simple12
{
public static void main(String[] args) {
{
int a;
System.out.println("Done");
}
}
}
Output:
Done
Example:
public class Simple13
{
public static void main(String[] args) {
int a;
System.out.println("a++");//a++ is treated as String varibale
}
}
Output:
a++
---------------------------------------------------------------------------------------------------------------------------------------
FINAL
1) Final is a keyword.
2) If you want to declare constant variable where-in value cannot be changed then those variable
should be declared with the keyword Final.
3) Final variable value cannot be changed or overridden.
4) Both local and global variable can be Final.
5) Global Final variables should be initialized at the time of declaration itself.
6) Local Final variables can be declared once and initialized later.
Note:
1) Static members of the same class can be accessed directly.
2) Local variables will be given preference over Global Variables.
Developer-Tester
Core Java JyothiShankar Mahakul 57
Example:
public class Simple1
{
final static double PI=3.14;
public static void main(String[] args)
{
System.out.println("PI value" +Simple1.PI);
Simple1.PI=9.36;//cannot assign a value to final varibale
{
System.out.println("PI vlaue" +Simple1.PI);
}
}
}
Output:
cannot assign a value to final variable PI
Example:
public class Simple2
{
final static double PI;//Global final should be initialized at declaration itself
public static void main(String[] args)
{
System.out.println("Value of PI is" +Simple2.PI);
}
}
Output:
variable PI not initialized in the default constructor
Example: If local and Global variables have the same name, then we should use class-name to
access the global varibale
public class Simple3
{
static int a=10;//Global varibale
public static void main(String[] args)
{
int a=20;//Local Varibale
System.out.println("local a=" +a);
System.out.println("Global a=" +Simple3.a);
}
Output:
local a=20
Global a=10
NOTE:
1) Static members of the same class can be access directly from Static context.
2) Static members of the same class can be accessed directly from non-static also.
3) Non-Static members can be accessed directly from another Non-Static context .
4) Non-Static members cannot be accessed directly from Static context, we should create object and
we should use object reference.
Developer-Tester
Core Java JyothiShankar Mahakul 58
Example:
public class Bank
{
int balance;//non-static varibale
void balance()//non-static method
{
System.out.println("Current balance is " +balance);
}
void deposit(int damount)//
{
balance=balance+damount;//non-static members can be accesed directly from another
non-static context
System.out.println("you have deposited" +damount +"Rs");
balance();
}
void withdraw(int wamount)//non-static method
{
if(wamount<=balance)
{
balance=balance-wamount;
System.out.println("you have withdrawn" +wamount+ "Rs");
}
else
{
System.out.println("insufficient balance");
}
balance();
}
public static void main(String[] args)
{
System.out.println("welcome to HDFC bank");
Bank b=new Bank();
b.balance();
System.out.println("Transaction details");
b.deposit(10000);
System.out.println("Transaction details");
b.withdraw(10000);
System.out.println("Transaction details");
b.withdraw(10000);
}
}
Output:
welcome to HDFC bank
Current balance is :0
Transaction details
you have deposited :10000Rs
Current balance is :10000
Transaction details
you have withdrawn :10000Rs
Current balance is :0
Transaction details
insufficient balance :
Current balance is :0
Developer-Tester
Core Java JyothiShankar Mahakul 59
7. METHOD OVERLOADING
Definition:
Developing multiple methods with the same name, but variations in the arguments list.
Variations in the arguments list can be:-
1) Number of arguments.
2) Types of arguments.
3) Position/order of arguments
Whenever we want to perform the common operation or task with the variations in the inputs, we
should choose Method Overloading.
Example:
If you want to write th eprogrsm to perform addition of 2 numbers and 3 numbers, then we
should develop 2 method with 1 to receive 2 inputs and 1 more to receive 3 inputs. Instead of
developing this methods with different names, we can develop with same name add.
Example:
If you are developing an application and you are giving 2 options for the user name and
password and another with the mobile numbers and password. Here also we should develop 2
methods with the variation in the inputs instead of developing this methods with different name the
operation is common, we can develop it with the same name.
Interview Questions:
1) Can we overload main method?
Yes, we can but the program execution starts with main method having arguments as (String[]
args)Other versions of the main program should be invoked by the programmer explicitly.
2) Can we overload Non-static method?
Yes.
3) Can the return type differ while overloading?
Yes.
Example:
public class Simple1
{
void greet()
{
System.out.println("Welcome to Home");
}
void greeting(String name)
{
System.out.println("Welcome to Home: " +name);
}
public static void main(String[] args)
{
Simple1 s=new Simple1();
s.greet();
s.greeting("JSM");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 60
Output:
Welcome to Home
Welcome to Home: JSM
Example:
public class Calculate
{
static void area(int side)
{
int a=side*side;
System.out.println("Area of square is" +a);
}
static void area(int length, int breadth)
{
int a=length*breadth;
System.out.println("Area of rectangle is" +a);
}
static void area(double radius)
{
double d=3.14*radius*radius;
System.out.println("Area of circle is" +d);
}
public static void main(String[] args)
{
area(2);
area(2,3);
area(3.0);
}
}
Output:
Area of square is4
Area of rectangle is6
Area of circle is28.2599999999999
Example:
public class Simple2
{
static void show(int a)
{
System.out.println("input recieved is: " +a);
}
void show(double d)
{
System.out.println("input received is: " +d);
}
public static void main(String[] args)
{
show(10);
Simple2 s2=new Simple2();
s2.show(20.5);
}
}
Output:
input recieved is: 10
input received is: 20.5
Developer-Tester
Core Java JyothiShankar Mahakul 61
Example:
public class Simple3
{
static void test(int a)
{
System.out.println("Running test(int a)");
}
static void test(int b)
{
System.out.println("Running test(int a)");
}
public static void main(String[] args) {
{
test(10);
}
}
}
Output:
method test(int) is already defined in class
Example:
public class OverloadingMain
{
public static void main(int a)
{
System.out.println("Main(int a)");
}
public static void main(double a)
{
System.out.println("Main(double a)");
}
public static void main(String[] args) //Oroginal Main
{
main(10);
main(10.5);
}
}
Output:
Main(int a)
Main(double a)
Developer-Tester
Core Java JyothiShankar Mahakul 62
9. INHERITANCE
Definition:
Getting the features or properties of one class from another class is called as Inheritance.
-> The class from which other class acquires the features is called as Super class or Parent class or
Base class.
-> The class which acquires the features or properties is called as Sub class or Child class or Derived
Class.
Through Inheritance we can achieve,
1. Extensibility.
2. Code Optimization.
3. Code Re-usability.
4. Code Maintainability.
To Achieve inheritance between classes, we should use Extends keyword.
1. Single Level inheritance: One class inheriting from only one Super class.
2. Multilevel inheritance: One class inheriting from another Sub class.
3. Hybrid Inheritance: Two or more class inheriting from common Super class.
4. Multiple inheritance: One class inheriting from multiple immediate Super class.
Note: Multiple inheritance is not possible is java through Classes instead happens through Interfaces
Note: Only non-static members of a class will be involved in Inheritance.
Developer-Tester
Core Java JyothiShankar Mahakul 63
Output:
Main Starts
Running Test1
Running Test2
Running Test3
Running Test1
Running Test2
Main Ends
Developer-Tester
Core Java JyothiShankar Mahakul 64
super keyword
Definition:
super keyword is used to access super class non-static members in case of inheritance between
classes.
1) Has Effective use in method overriding than inheritance.
2) Due to method overriding super class implementation will be masked in the sub class.
3) To get the original/masked implementation in sub class we can use super keyword.
4) To avoid overrriding use Final keyword.
5) Declare class as Final then no method can be overridden.
Example: Super
class A
{
A()
{
System.out.println("Constructor of A class");
}
}
class B extends A
{
B()
{
super();
System.out.println("Constructor of B class");
}
}
class C extends B
{
C()
{
super();
System.out.println("Constructor of C class");
}
}
class SuperMain
{
public static void main(String[] args)
{
System.out.println("Main Starts");
C rv=new C();
System.out.println("Main Ends");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 65
Output:
Main Starts
Constructor of A class
Constructor of B class
Constructor of C class
Main Ends
Note: If there is inheritance between classes and if the Programmer has not developed super classing
statement inside the constructor then there will be a default Super calling constructor statement
developed by the Compiler
i.e.,Super();Default Super calling statement will always be without Arguments
Super(parameter): This will call the immediate super class constructor with the matching arguments.
Example:
class H
{
H(int a)
{
System.out.println(" from H(int a) constructor");
}
}
class I extends H
{
I()
{
Developer-Tester
Core Java JyothiShankar Mahakul 66
Example:
class M
{
M()
{
System.out.println("From M()");
}
}
class N extends M
{
N(int a)
{
System.out.println("From N()" +a);
}
N()
{
this(10);
System.out.println("From N()");
}
}
class O extends N
{
O()
{
System.out.println("From O()");
}
}
class SuperMain3
{
public static void main(String[] args)
{
O rv=new O();
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 67
Output:
From M()
From N()10
From N()
From O()
Differences
this callin statement super Calling Statement
1. Is used to call Current class constructor. 1. Is used to call Super class Constructor.
2. will be used in case of Constructor Overloading. 2. Will be used in case of inheritance.
3. will be no default this calling statement by 3. Compiler develops a default Super Calling
compiler Statement(if there is inheritance).
4.Through this calling statement we can utilize 4.Through Super Calling Statement we can
initialization code of another constructor. achieve Constructor chaining.
5. this calling statement is not mandatory. 5. Super Calling Statement is mandatory in case
of inheritance.
Example:
class Sample//Sample is Super class
{
int empid;
Sample(int empid)//Constructor
{
this.empid=empid;
}
}
class Demo extends Sample// Demo is Sub class
{
Demo(int empid)//Constructor
{
super(empid);
}
}
class SuperMain4
{
public static void main(String[] args)
{
Demo rv1=new Demo(1);
System.out.println("The value of Empid is: " +rv1.empid);
Demo rv2=new Demo(2);
System.out.println("The value of Empid is: " +rv2.empid);
}
}
Output:
The value of Empid is: 1
The value of Empid is: 2
---------------------------------------------------------------------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 68
Object class
A B
C
Multiple Inheritance is not possible bcz, in case of MI as 1 class(sub class) will be inheriting from
Multiple immediate Super classes then to maintain chaining we should develop 2 or more super
calling statement in sub class which is against the rule of java.
Multiple Inheritance
1. Multiple Inheritance means One class inheriting from multiple immediate Super class.
2. If there is inheritance between classes, constructor chaining is mandatory.
3. Constructor chaining can be achieved through Super calling statement.
Object class
clone()
C(Sub Class)
clone()
Developer-Tester
Core Java JyothiShankar Mahakul 69
8. CONSTRUCTOR
Definition:
Constructor is a special method which is used to construct a object or create a objectmfor a class
and cannot return or does not have Return type.
Whenever a object or class is created using new operator constructor will be executed.
Contructor does not contain arguments.
Why Contructor?
We can use constructor to create object, without constructor we cannot create Object.
Rules to develop constructor:
1) Constructor named should be exactly same as Class name.
2) Constructor should not have return type, should always be non-static should not return any value.
3) Constructor is also called as Non-static initializer, which is iused ti initialize the object of a class.
4) No static and return type allowed.
5) Constructor should b e there for every class.
6) If the programmer has not developed a constructor for class then there will be default constructor
in that class.
Default Constructor:
The constructor developed by the compiler at compile-time is called as Default constructor.
If a programmer has nit developed a for class then compiler will develop the default constructor.
Differences:
Methods Constructor
1) Method can have any name, it can have a class 1) Constructor name Should be similar to the
name also. Class name.
2) Method must have return type atleast Void 2) Constructor should have Return type not even
void.
3) Method can be static or non-static. 3) Constructor should always be non-static
4) Method may or may not return value. 4) Constructor cannot return value.
5) Java does not provide Default Constructor 5) Java provides Default Constructor.
method.
6) Method cannot be used for Object creation. 6) Constructor will be used for object creation
using new operator.
Types of Constructor:
1) Parameterized Constructor: The Constructor which is developed with some arguments.
Example: A(int I)
2) No-Arguments Constructor: The Constructor which is developed without arguemnts.
Example:A()
Default Constructor falls under No-Arguments Constructor.
Developer-Tester
Core Java JyothiShankar Mahakul 70
Note:
1) To create the object for a class we should utilize available Constructor of that ckass.
2) If programmer develops a Constructor for class then java does not provide a default Constructor.
Constructor Overloading:
Developing multiple Constructor for a class with the variation in the Data-type, members and
position of arguemnts is called Constructor overloading.
Example:
public class Simple1
{
Simple1()
{
System.out.println("Running Constructor");
}
public static void main(String[] args)
{
System.out.println("Main Starts");
Simple1 s1=new Simple1();
System.out.println("Main Ends");
}
}
Output:
Main Starts
Running Constructor
Main Ends
Example:
public class Simple2
{
Simple2()
{
System.out.println("Running Demo1 constructor");
}
public static void main(String[] args)
{
System.out.println("Main Starts");
Simple2 s2=new Simple2();
System.out.println("------------");
Simple2 s22=new Simple2();
System.out.println("Main Ends");
}
}
Output:
Main Starts
Running Demo1 constructor
------------
Running Demo1 constructor
Main Ends
Developer-Tester
Core Java JyothiShankar Mahakul 71
Example:
public class Simple3
{
/* DefaultConstructor
Simple3()
{
}
*/
public static void main(String[] args)
{
System.out.println("Main Starts");
Simple3 s3=new Simple3(); //Call to default constructor
System.out.println("Main Ends");
}
}
Output:
Main Starts
Main Ends
Example:
public class Simple4
{
void Simple4()
{
System.out.println("Constructor ?");//MEthod with class name.
}
public static void main(String[] args)
{
System.out.println("Main Starts");
Simple4 s4=new Simple4();
System.out.println("Main Ends");
System.out.println("-----------");
}
}
Output:
Main Starts
Main Ends
-----------
Example:
public class Simple5
{
int stdId;
Simple5()
{
System.out.println("Running Constructor");
}
public static void main(String[] args)
{
System.out.println("Main Starts");
Simple5 s5=new Simple5();
System.out.println("Value of stdId is :" +s5.stdId);
System.out.println("--------------------");
Simple5 s55=new Simple5();
System.out.println("Value of stdId is :" +s55.stdId);
System.out.println("Main Ends");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 72
Output:
Main Starts
Running Constructor
Value of stdId is :0
--------------------
Running Constructor
Value of stdId is :0
Main Ends
Example:
public class Simple7
{
int stdId;
String stdName;
Simple7(int id,String name)
{
stdId=id;
stdName=name;
}
public static void main(String[] args)
{
System.out.println("Main Starts");
Simple7 s7= new Simple7(1,"JSM");
System.out.println("1st student id is:" +s7.stdId);
System.out.println("1st student name is:" +s7.stdName);
System.out.println("-------------------------");
Simple7 s77= new Simple7(1,"SMP");
System.out.println("1st student id is:" +s77.stdId);
System.out.println("1st student name is:" +s77.stdName);
System.out.println("Main Ends");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 73
Output:
Main Starts
1st student id is:1
1st student name is:JSM
-------------------------
1st student id is:1
1st student name is:SMP
Main Ends
Example:
public class Circle
{
double radius;
Circle(double r)
{
radius=r;
double a=3.14*radius*radius;
System.out.println("Area is:" +a);
}
public static void main(String[] args)
{
Circle c1=new Circle(2.3);
Circle c2=new Circle(5.2);
}
}
Output:
Area is:16.610599999999998
Area is:84.90560000000002
Example:
public class Simple8
{
int stdId;
Simple8(int id)
{
stdId=id;
}
public static void main(String[] args)
{
Simple8 s8=new Simple8(10);
//If no arguments specified, actaul and formal arguemnts will differ
System.out.println("Value of stdId is: " +s8.stdId);
}
}
Output:
Value of stdId is: 10
Example:
public class A
{
A()
{
System.out.println("From A()");
}
A(int a)
{
Developer-Tester
Core Java JyothiShankar Mahakul 74
Example:
public class Student
{
String stdName;
int stdId;
int age;
Student(String name, int id, int a)
{
stdName=name;
stdId=id;
age=a;
}
Student(String name, int id)
{
stdName=name;
stdId=id;
}
public static void main(String[] args)
{
Student s1=new Student("JSM", 10,90);
System.out.println("1st student id is:" +s1.stdId);
System.out.println("1st student Name is:" +s1.stdName);
System.out.println("1st student age is:" +s1.age);
Developer-Tester
Core Java JyothiShankar Mahakul 75
Output:
1st student id is:10
1st student Name is:JSM
1st student age is:90
1st student id is:20
1st student Name is:SMP
Developer-Tester
Core Java JyothiShankar Mahakul 76
Definition:
Changing the implementation of super class method in the sub class according to the needs of
the sub class is called Method overriding.
To achieve Method Overriding 3 things are mandatory,
1. Inheritance.
2. Non-Static Methods.
3. Signature or Methods Declaration should be same.
Whenever we perform Method overriding super class implementation ofthat method will be lost
or masked in the sub class I.e., we will get he latest implementation of sub class.
Example:
class C
{
void test1()
{
System.out.println("Running test1 of A class");
}
}
class D extends C
{
void test1()
{
System.out.println("Running test1 of B class");
}
}
class Main1
{
public static void main(String[] args)
{
System.out.println("Main Starts");
D rv=new D();
rv.test1();
System.out.println("Main Ends");
}
}
Output:
Main Starts
Running test1 of B class
Main Ends
Note:
1. Always Overridden methods will be a original method of super class, just implementation will be
changed in the class.
2. While object creation itself overriding happens. Later objects address will be assigned to the
reference(ex:A rv=new A())
Developer-Tester
Core Java JyothiShankar Mahakul 77
Example:
class A
{
void test1()
{
System.out.println("Super class Implementation");
}
}
class B extends A
{
void test1()
{
super.test1();
System.out.println("Sub class Implementation");
}
}
public class Main2
{
public static void main(String[] args)
{
A rv=new B();
rv.test1();
}
}
Output:
Super class Implementation
Sub class Implementation
Example:
class Person
{
String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
void display()
{
System.out.println("The name is:" +name);
System.out.println("The age is:" +age);
}
}
class Trainer extends Person
{
String subject;
double salary;
Trainer(String name,int age,String subject,double salary)
{
super(name,age);
this.subject=subject;
this.salary=salary;
}
Developer-Tester
Core Java JyothiShankar Mahakul 78
void display()
{
super.display();
System.out.println("The subject is:" +subject);
System.out.println("The salary is:" +salary);
}
}
public class Main3
{
public static void main(String[] args)
{
Output:
The name is:Jo
The age is:90
The subject is:Java
The salary is:500000.0
The name is:J
The age is:90
The subject is:SQL
The salary is:500000.0
this Keyword:
1) this is a keyword.
2) this will be pointing to the current object under execution.
3) this will be holding the current object address.
4) To access current instance members or object members we should use this keyword.
5) This is also called as Default Reference variable of java.
6) To differentiate Global variable with the local variable we can use this keyword.
7) Ex: if a local variable and a Global variable is having the same name Empid, then to access the
global variable we should use this keyword.
8) This keyword can be used only in non-static context.
Developer-Tester
Core Java JyothiShankar Mahakul 79
Advantage:
If we cant to use the initialization code written is another constructor of the same class , then we
make use of tcs.
Example:
public class Z
{
Z()//Constructor
{
System.out.println("from A()");
}
Z(int a)//Constructor
{
this();//tcs
System.out.println("from A(int a)");
}
public static void main(String[] args)
{
Z rv=new Z(90);
}
}
Output:
from A()
from A(int a)
Example:
public class Demo
{
Demo()
{
System.out.println("From demo()");
}
Demo(int a)
{
this();
System.out.println("From demo(int a)");
}
Demo(int a, double d)
{
this(90); //when no parameter given, above Demo(int a) constructor will not be called.
/*But other two constructor will be called, when this(90) constructor is not mentioned here, then
current constructor will be executed not the above 2*/
System.out.println("From demo(int a, double d)");
}
public static void main(String[] args)
{
Demo rv = new Demo(20, 20.5);
} }
Developer-Tester
Core Java JyothiShankar Mahakul 80
Output:
From demo()
From demo(int a)
From demo(int a, double d)
Example:
public class Sample
{
Sample(int a)//Constructor
{
System.out.println("from sample(int a)" +a);
}
Sample(int a, double d)//Constructor Overloaded
{
this(a);
System.out.println("From Sample(int a, double d)" +a + d);
}
public static void main(String[] args)
{
Sample rv=new Sample(90,20.5);
}
}
Output:
from sample(int a)90
From Sample(int a, double d)90 20.5
Example:
public class Student
{
String stdName;
int stdId;
int age;
Student(String name, int id)
{
stdName=name;
stdId=id;
}
Student(String name, int id, int a)
{
this(name,id);
age=a;
}
public static void main(String[] args)
{
Student rv1=new Student("J", 10,90);
System.out.println("1st student id is: " +rv1.stdId);
System.out.println("1st student Name is: " +rv1.stdName);
System.out.println("1st student age is: " +rv1.age);
}
}
Output:
1st student id is: 10
1st student Name is: J
1st student age is: 90
Developer-Tester
Core Java JyothiShankar Mahakul 81
Example:
public class Box
{
int length;
int breadth;
int height;
Box(int l,int b,int h)//parameterized Constructor
{
height=h;
length=l;
breadth=b;
}
Box(int side)//parameterized & Constructor Overloading
{
this(side,side,side); //this is calling above constructor of the same class due to Constructor
Overloading
}
void volume()//Method
{
int v=length*breadth*height;
System.out.println("Voulme is" +v);
}
public static void main(String[] args)
{
Box b1=new Box(2,3,4);
b1.volume();
Box b2=new Box(2);
/*Volume is 8, bcz this() in Box(int side) is calling the 1st Box and executing
the Voulume();*/
b2.volume();
}
}
Output:
Voulme is 24
Voulme is 8
Example:
package MethodOverRiding;
public class Sample1
{
Sample1()
{
System.out.println("From sample1()");
}
Sample1(int a)
{
System.out.println("from sample(int a)");
this(); // Call to this, must be the first statement in constructor
}
public static void main(String[] args)
{
Sample1 S=new Sample1(10);
}
}
Output:
call to this must be first statement in constructor
Developer-Tester
Core Java JyothiShankar Mahakul 82
Example:
public class Sample2
{
int stdId;// Variable
void test(int stdId)//Method
{
System.out.println(stdId);
System.out.println(this.stdId);//Tcs, inside SOP
}
public static void main(String[] args)
{
Sample2 s=new Sample2();
s.test(10);
}
}
Output
10
0
Example:
public class Sample3
{
String name;
void t(String name)
{
System.out.println(name);
this.name=name;
System.out.println(this.name);
}
public static void main(String[] args)
{
Sample3 s3=new Sample3();
s3.t("ramesh");
}
}
Output:
ramesh ramesh
Example:
class Demo1
{
int c; int j;
Demo1(int c,int j)//Constructor
{
this.c=c; this.j=j;
}
public static void main(String[] args)
{
Demo1 d=new Demo1(10,20);
System.out.println("d.c=" +d.c);
System.out.println("d.j=" +d.j);
Developer-Tester
Core Java JyothiShankar Mahakul 83
Output:
d.c=10
d.j=20
d.c=50
d.j=60
Note: We can compile a program without main(), but we cannot execute the program without main().
Differences:
Static Members Non-Static Members
1) It has only one copy of instance variables 1) It has its own copy of instance variables.
that share among all objects of the class.
2) A static method belongs to the class itself.
2) Non-static methods belongs to each object that is
generated from that class.
3) No need to create object, we can directly 3) Need to create a object.
call classname.methodname() Classname obj=new Classname();
Obj.methodname();
4) It includes static variables, methods and 4) It includes non-static variables, methods,
Static Initialization Block(SIB). constructor and Instance Initialization Block(IIB).
Differences:
Method Overloading Method Overriding
Developer-Tester
Core Java JyothiShankar Mahakul 84
Concrete method: The method which will have declaration and definition together is called as
Concrete methods.
Ex: void test()
{
-----------;
-----------;
}
Concrete class: The class in which we can develop concrete methods is called as Concrete class.
Ex: class A
{
void test()
{
--------;
--------;
}
}
Abstract method: The method with just the declaration without definition is called as Abstract
method.
Ex: abstract void test()
Abstract class: The class in which we have an option to develop Abstract method is called as an
Abstract class.
Note: The Abstract class and Abstract method should be declared with the keyword abstract.
Ex: abstract class A
{
abstract void test();
}
I.Q: We cannot create object of the abstract class or in other words abstract class cannot be
instantiated.
Note: Abstract class should always have a sub class and the sub class should give the implementation
or definition of the inherited abstract class.
Note: Giving implementation or a new definition to the inherited abstract class in the sub class is also
called as Method overriding.
Example:
abstract class A
{
abstract void test1();//only declaration
abstract void test2();//only declaration
}
class B extends A//inheriting abstract class A
{
@Override
void test1()//Declaration
{
Developer-Tester
Core Java JyothiShankar Mahakul 85
Output:
Main Starts
test1() is overridden in class B
test2() is overridden in class B
Demonstration:
A(abstract class)
test1()_void
test2()_void
test1(){ }
Test2(){ }
B(sub class)
test1()_void
test2()_void
Example:
abstract class Animal
{
abstract void move();
abstract void sound();
}
class dog extends Animal
{
@Override
void move()
{
System.out.println("dog moves");
}
@Override
void sound()
{
System.out.println("bow bow");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 86
Output:
dog moves
bow bow
cat moves
meow meow
Example:
abstract class college
{
abstract void gridview();
}
class faculty extends college
{
String name;
int yoe;
faculty(String name, int yoe)// abstract class can have a constructor
{
this.name = name;
this.yoe = yoe;
}
@Override
void gridview()
{
System.out.println("the name is " +name);
System.out.println("the total exp is " +yoe);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 87
Output:
the name is JSM
the total exp is 2
Example:
abstract class Sample
{
abstract void test1();
abstract void test2();
}
class Demo extends Sample// sub class Demo should implement all the methods of abstract methods
{
void test1()
{
System.out.println("Test1() overridden in demo class");
}
}
//void test2() is not inherited and implemented, so CTE.
public class Tester4
{
public static void main(String[] args)
{
Demo d1=new Demo();
d1.test1();
d1.test2();
}
}
Output:
Abstract_Class.Demo is not abstract and does not override abstract method test2() in
Abstract_Class.Sample
Developer-Tester
Core Java JyothiShankar Mahakul 88
Ex1: Animal is a concept and it defines the standard characteristics which should be a part of all
animal types. All the type of animal will have the standard characteristics with slight variation In
behavior.
In this scenario we can go for Abstract class i.e., every animal will have moment and sound
characteristics, but implementation differ.
Ex2:While developing the project , all the standard features should be developed with abstract
method in abstract class and underlying related class will be implement the standard features based
on variation. Here through abstract class we can put a restriction for all the sub class to give the
implementation for the standard features.
Developer-Tester
Core Java JyothiShankar Mahakul 89
4) Enumeration:
They are used to group the fix number of constants.
Ex: Days in a week, keys of keyboard,months in year.
Through enumeration we can achieve uniformity.
Syntax:
enum enumname
{
}
Example: enum months;
{
5) Annotation:
Definition: Instructions given by programmer to compiler specifying what a compiler should do during
compilation.
or
They are used to give implementation to the developer, compiler and run time environment.
1) @override:
Helps us to check whether we are overriding a method or not.
Example:
public class H
{
public void test()
{
System.out.println("from test()");
}
}
public class I extends H
{
@override //complier will help in typo
public void test1()
{
System.out.println("hello");
}
public static void main(String[] args)
{
I i1=new I();
i1.test();
}
Developer-Tester
Core Java JyothiShankar Mahakul 90
Output:
from test()
2) @Supresswarnings
Helps us to suppress warning messages in the program
Example:
public class G
{
@SuppressWarnings("unused")
public static void main(String[] args)
{
int i;
}
}
public class F
{
//@SuppressWarnings("unused");
public static void main(String[] args)
{
int i;
}
}
3) Deprecated:
Helps us to notify that a particular method is not in use.
Example:
public class E
{
public static void main(String[] args)
{
E e1=new E();
e1.test();
}
@Deprecated
public void test()
{
System.out.println("From test");
}
}
Output:
From test
Syntax:
@interface annotationname
{
Developer-Tester
Core Java JyothiShankar Mahakul 91
Example:
@interface A
{
Example:
interface A
{
void test1();
void test2();
}
class B implements A
{
@Override
public void test1()
{
System.out.println("test1() overridden in Class B");
}
@Override
public void test2()
{
System.out.println("test2() overridden in Class B");
}
}
public class Tester1
{
public static void main(String[] args)
{
//A rv=new A();//we cannot create objects of interface and A is abstract and cannot be
instantiated
B b1=new B();
b1.test1();
b1.test2();
}
}
Output:
test1() overridden in Class B
test2() overridden in Class B
Example:
interface TV
{
void display();
void sound();
void remote(int channel);
}
class sony implements TV
{
@Override
public void display()
{
System.out.println("sony led display");
}
@Override
public void remote(int channel)
Developer-Tester
Core Java JyothiShankar Mahakul 92
{
System.out.println("Sony is in channel number" +channel);
}
@Override
public void sound()
{
System.out.println("sony dts sound system");
}
}
public class Tester2
{
public static void main(String[] args)
{
sony s1=new sony();
s1.display();
s1.remote(10);
s1.sound();
}
}
Output:
sony led display
Sony is in channel number10
sony dts sound system
Example:
interface D
{
void test1();
}
interface E
{
void test2();
}
class F implements D, E
{
public void test1()
{
System.out.println("test1() overridden in test1()");
}
public void test2()
{
System.out.println("test2() overridden in test2()");
}
}
public class Tester3
{
public static void main(String[] args)
{
F f1=new F();
f1.test1();
f1.test2();
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 93
Output:
test1() overridden in test1()
test2() overridden in test2()
Example:
class G
{
void test1()
{
System.out.println("test1() of class F");
}
}
interface H
{
void test2();
}
class I extends G implements H
{
@Override
public void test2()
{
System.out.println("test2() overridden in class H");
}
}
public class Tester4
{
public static void main(String[] args)
{
I i1=new I();
i1.test1();
i1.test2();
}
}
Output:
test1() of class F
test2() overridden in class H
Example:
interface exam
{
void percentage();
}
class student
{
String name;
int m1,m2,m3;
student(String name,int m1,int m2,int m3)
{
this.name=name;
this.m1=m1;
this.m2=m2;
this.m3=m3;
}
void display()
{
System.out.println("the name is " +name);
System.out.println("the marks1 is: " +m1);
Developer-Tester
Core Java JyothiShankar Mahakul 94
Output:
the name is JSM
the marks1 is: 99
the marks2 is: 99
the marks2 is: 99
percentage ofJSM is: 99
Developer-Tester
Core Java JyothiShankar Mahakul 95
13. INTERFACES
This is a Java type which is 100% abstract. Through interface we can achieve multiple inheritance
in java up-to some extent.
Through interface we can achieve standardization and abstraction.
Through interface we can achieve 100% abstraction (because interface is abstract).
We can create Object of Interface.
Interface should always have sub class and the sub class should follow 2 contract or rule.
Rule 1: The sub class should override all the method of interface.
Rule 2: If the sub class does not override all the method of interface, then the sub class should be
declared as abstract.
Note:
1) If a class is inheriting from a interface then we should use implements keyword.
2) In interface all the methods will be automatically abstract i.e., no need to use abstract keyword.
3) In interface all the methods will be automatically public.
4) In interface we can develop abstract method.
5) Interface will not have constructor because constructor cannot be abstract.
6) Interface will not inherit from object class.
7) If a class is inheriting from interface, no need of constructor chaining(because constructor will
not be there)
Note:
1) If a class is inheriting from another class we should use extends keyword(and to represent the
inheritance through diagram we should use solid line).
2) If a class is inheriting from interface, we should use implements keyword(we should use dotted
line to represent inheritance through diagram).
3) If a interface in inheriting from another interface we should use extends keyword(we should use
solid line to represent the interfaces).
I.Q: Can one interface inherit from concrete class or abstract class?
No, because interface is 100% abstract and in this case it might inherit concrete methods.
Developer-Tester
Core Java JyothiShankar Mahakul 96
Difference:
Abstract class Interface
1) Abstract class is not 100% abstract. 1) Interface is 100% abstract.
2) In Abstract class we can have constructor. 2) Interface will not have any constructor.
3) Abstract class will inherit from object class. 3) Interface will not inherit from object class.
4) Through Abstract class we cannot achieve 4) through interface we can achieve multiple
multiple inheritance. inheritance.
5) If a class is inheriting from abstract class we 5) if a class is inheriting from interface then we
should use extends keyword. should use implements keyword.
6) in abstract class, Abstract methods should be 6) In interface we need not declare abstract
declared with the keyword Abstract. methods with keyword abstract(because it will
be automatically abstract)
7) in Abstract class, method will have 7) In interface, all the methods will be public.
programmer level access.
8) in Abstract class, variables will not be 8) In interface, all the variables will be
automatically Final. automatically public static and final.
9) In Abstract class , we can declare a variable 9)In interface, variables should be initialized
and initialize later. while declaration itself
10) In Abstract class, we can develop concrete 10) In interface we cannot develop concrete
method and that concrete methods can be static methods i.e., we can develop only abstract
so in abstract class we can develop static method method. Abstract methods cannot be static so in
also. interface we cannot develop static members.
11) In Abstract methods, we can develop 11) In Interface we cannot develop final methods
concrete methods and those concrete methods because it is pure abstract and abstract methods
can be final. So in abstract class we can develop cannot be final.
final methods.
12) If a class is inheriting from abstract class 12) If a class is inheriting from an interface
constructor chaining is required. constructor chaining is not required.
Note:
1) Method can return an object as output.
2) While developing program if you want to return an object from a method then that methods
return type should be class name.
3) In other words, if a method return type is a class name it should or will return the object address
of that particular class name.
Ex: if the methods return type is Sample then it should or will return the object of Sample class.
Developer-Tester
Core Java JyothiShankar Mahakul 97
1) Call by Value: Calling the method by supplying the primitive data or simple data like 10, 10.5 etc.,
is called as Cal by value type of Method invocation.
Ex: test(90);//Supplying the value directly.
int a=90;
Test(a);// supplying the value via variable.
2) Call by Reference: Calling a method by supplying the object reference is called as call by reference
type of method invocation.
Ex: A rv=new A();
Test(rv);
Note:
1) Methods can also receive objects as input and it can perform the operation on the contents of the
object.
2) If any methods arguments is reference variable of sub class then we should supply the object
address(reference) of that particular class.
Developer-Tester
Core Java JyothiShankar Mahakul 98
1) Primitive Casting:
Definition: Casting the data from one type to another primitive type is called as Primitive Casting.
Ex: double a=(int) 10.5;
Here we are converting the primitive double data into integer type which is called as Primitive
Casting.
Example:
public class A
{
public static void main(String[] args)
{
int a=(int) 10.9;
System.out.println("value of a is " +a);
double d=(double) 10;
System.out.println("value of d is " +d);
}
}
Output:
value of a is 10
value of d is 10.0
Note:
1) Out of 8 primitive data type all the 6 number related data types will support for Primitive casting.
2) There will be one ASCII conversion between char and int.
3) Boolean will not support any type of casting.
Developer-Tester
Core Java JyothiShankar Mahakul 99
2) Narrowing Operation:
Converting the data from higher primitive type to anyone of the lower primitive type is called as
Narrowing operation.
a. Explicit-Widening Operation: Programmer performing the narrowing operation explicitly
while developing the code is called as Explicit Narrowing.
b. Auto-Narrowing Operation: There is no concept of Auto-Narrowing, i.e., compiler will not
perform narrowing operation automatically because might be loss of data.
Example:
public class B
{
public static void main(String[] args)
{
double d=10;
System.out.println("value of d is " +d);
int a=(int)10.5;
System.out.println("Value of a is " +a);
}
}
Output:
value of d is 10.0
Value of a is 10
Example:
public class C
{
static int test()
{
double d=10.5;
return(int)d;
}
public static void main(String[] args)
{
System.out.println(test());
}
}
Output:
10
Note:
1. In case of Method overloading, appropriate version of the method will be called.
2. If appropriate version is not available then method with Higher version will be called (widening).
Example:
public class D
{
static void test(int a)
{
System.out.println("test(int a)");
}
static void test(double d)
{
System.out.println("test(double d)");
}
Developer-Tester
Core Java JyothiShankar Mahakul 100
test(10);
}
}
Output:
test(int a)
Example:
public class E
{
static void test(int a, double d)
{
System.out.println("test(int a, double d)");
}
static void test(double d, int a)
{
System.out.println("test(double d, int a");
}
public static void main(String[] args)
{
test(10,10);
test(20.5,20);
}
}
Output:
The method test(int, double) is ambiguous for the type E
Example:
public class F
{
public static void main(String[] args)
{
int a=5;
int b=2;
double res=(double)a/b;
System.out.println("result is " +res);
}
}
Output:
result is 2.5
Example:
public class G
{
static void percentage(int m1,int m2, int m3)
{
int total=m1+m2+m3;
double per=((double)total*100)/300;
System.out.println("percentage=" +per);
}
public static void main(String[] args)
{
percentage(99, 97, 96);
}}
Output:
percentage=97.33333333333333
done
Developer-Tester
Core Java JyothiShankar Mahakul 101
Example:
public class H
{
static void area(double radius)
{
double res=3.14*radius*radius;
System.out.println("result is " +res);
}
public static void main(String[] args)
{
area(2.5);
area(2);
}
}
Output:
result is 19.625
result is 12.56
Example:
public class I
{
static double purchaseAmount=95.5;
static double receivePayment(double payedAmount)
{
double change=payedAmount-purchaseAmount;
return change;
}
public static void main(String[] args)
{
double change=receivePayment(100);
System.out.println("Change to be given to the customer is " +change);
}
}
Output:
Change to be given to the customer is 4.5
Example:
public class J
{
public static void main(String[] args)
{
System.out.println(Integer.MAX_VALUE);
System.out.println(100);
System.out.println(99999);
System.out.println(989893898);
}
}
Output:
2147483647
100
99999
989893898
Developer-Tester
Core Java JyothiShankar Mahakul 102
Example:
public class K
{
public static void main(String[] args)
{
long l=9888983498329L;
System.out.println("the value of l is " +l);
long l1=100;
System.out.println("the value of l1 is " +l1);
}
}
Output:
the value of l is 9888983498329
the value of l1 is 100
Example:
public class L
{
public static void main(String[] args)
{
float f=10F;
System.out.println("value of f is " +f);
}
}
Output:
value of f is 10.0
Example:
public class M
{
public static void main(String[] args)
{
double res=10.0/3;
System.out.println("The result is " +res);
float f=(float)res;// Narrowing double value of res to float
System.out.println("value of f is " +f);
}
}
Output:
The result is 3.3333333333333335
value of f is 3.3333333
Example:
public class N
{
static void test(byte b)
{
System.out.println("test(byte b)");
}
static void test(int a)
{
System.out.println("test(int a)");
}
public static void main(String[] args)
{
test(1);
}
Developer-Tester
Core Java JyothiShankar Mahakul 103
}
Output:
test(int a)
Example:
public class O
{
public static void main(String[] args)
{
char ch='A';
System.out.println("char " +ch);
char ch2=90;
System.out.println("char " +ch2);
int a='c';
System.out.println("int " +a);
int b=4;
System.out.println("int " +b);
System.out.println('A'+'B');
}
}
Output:
char Z
int 99
int 4
131
Example:
public class P
{
public static void main(String[] args)
{
char ch=253;
System.out.println("a" +ch+ "b" +ch);
}
}
Output:
Ab
2) Object Casting
Definition: Casting the object from one class to another class type or interface type is called as Object
Casting.
Through Object casting we can achieve run time Polymorphism and we can develop generic
functions which can receive any input.
To achieve Object-casting there should be is-a relationship or there should be inheritance.
1) Up-casting: Converting the sub-class object to super-class type or interface type is called as
Up-casting.
Whenever we perform up-casting sub-class features will be hidden we can access only
super-class features or parent features.
To achieve Up-casting inheritance is mandatory.
Developer-Tester
Core Java JyothiShankar Mahakul 104
Example:
class Sample1
{
void test1()
{
System.out.println("test1 of super-class sample1");
}
}
class Sample2 extends Sample1
{
void test2()
{
System.out.println("test2 of sub-class sample2");
}
}
class Tester1
{
public static void main(String[] args)
{
Sample1 s1=(Sample1)new Sample2();
s1.test1();
//s1.test2();
}
}
Output:
test1 of super-class sample1
Example:
class Sample3
{
int a=10;
}
class Sample4 extends Sample3
{
double d=10.5;
}
class Sample5 extends Sample4
{
char ch='z';
}
public class Tester2
{
public static void main(String[] args)
{
Sample4 s4=new Sample5();
System.out.println("The value of a is " +s4.a);
//System.out.println("The value of d is " +s4.d);
//System.out.println("The value of ch is " +s4.ch);
Developer-Tester
Core Java JyothiShankar Mahakul 105
Example:
class Sample6
{
void test()
{
System.out.println("test() super class implementation");
}
}
class Sample7 extends Sample6
{
void test()
{
System.out.println("test() of sub class implementation");
}
}
2) Down-Casting: Converting super class object o sub class type is called as Down Casting
Whenever we perform down-casting, sub class features will be hidden.
So to access these hidden features we perform down-casting operation.
To perform Down-casting there should be is-a relationship or there should be inheritance to
the classes.
Direct down-casting is not possible.(It means performing down-casting without up-casting)
There is no concept if Auto Down-casting, Programming should do it. So it is called as Explicit Casting.
Developer-Tester
Core Java JyothiShankar Mahakul 106
Example:
class Sample10
{
void test1()
{
System.out.println("Running test1() of class Sample10");
}
}
class Sample11 extends Sample10
{
void test2()
{
System.out.println("Running test2() of class Sample11");
}
}
public class Tester4
{
public static void main(String[] args)
{
Sample10 s10=new Sample11();
Sample11 s11=(Sample11)s10;
s11.test1();
s11.test2();
}
}
Output:
Running test1() of class Sample10
Running test2() of class Sample11
Example:
class Sample12
{
void test1()
{
System.out.println("test1()");
}
}
class Sample13 extends Sample12
{
void test2()
{
System.out.println("test2()");
}
}
public class Tester5
{
public static void main(String[] args)
{
Sample12 s12=new Sample12();
Sample13 s13=(Sample13)s12;
s13.test1();
s13.test2();
}
}
Output:
java.lang.ClassCastException: objectcasting.Sample12 cannot be cast to objectcasting.Sample13
Developer-Tester
Core Java JyothiShankar Mahakul 107
Example:
class Pendrive implements USBPORT
{
public void read()
{
System.out.println("Reading from Pendrive");
}
public void write()
{
System.out.println("Writing to pendrive");
}
}
class Mobiledevice implements USBPORT
{
public void read()
{
System.out.println("Reading from Mobile-device");
}
public void write()
{
System.out.println("Writing to Mobile-device");
}
}
class Myclass
{
static void demo(USBPORT driver)
{
driver.read();
driver.write();
}
}
class Tester6
{
public static void main(String[] args)
{
Myclass.demo(new Pendrive());
Myclass.demo(new Mobiledevice());
}
}
Output:
Reading from Pendrive
Writing to pendrive
Reading from Mobile-device
Writing to Mobile-device
Developer-Tester
Core Java JyothiShankar Mahakul 108
16. POLYMORPHISM
1) Compile-Time Polymorphism:
Through method overloading we can achieve Compile-Time Polymorphism.
Here method binding happens at compile time, so it is called as Compile-Time Polymorphism.
It is also called as Static Polymorphism or Early binding.
2) Run-Time Polymorphism:
To achieve Run-Time Polymorphism 3 things are mandatory,
a. Inheritance.
b. Method Overriding
c. Auto Up-casting.
Here method binding cannot be performed by compiler because overriding happens at run time,
so it is called as Run-Time Polymorphism.
It is also called as Dynamic Polymorphism or Late binding.
Example:
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name,String address,int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
Developer-Tester
Core Java JyothiShankar Mahakul 109
Developer-Tester
Core Java JyothiShankar Mahakul 110
Output:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Developer-Tester
Core Java JyothiShankar Mahakul 111
17. ABSTRACTION
Definition: Hiding the complexity of the system and exposing required functionality is called as
Abstraction.
Here class implementation will be hidden from user or usage.
Through Interface we can achieve 100% abstraction.
Through Abstract class we achieve up-to 100% abstraction(bcz, it is not 100% abstract).
To achieve abstraction:
1) Group all the common features in a interface or abstract class.
2) Override all the common features based in some variation on the sub classes.
3) Develop a helper method in a helper class which returns the appropriate object based on the
request.
Example1:
When we drive a car, we will not know the internal complex implementation of car, we just will
be exposed to the functionality.
Example2:
While sending mail, one composes and sends a mail, but internally there will be lot of complexity
which will be hidden.
Example3:
Selenium is complete abstraction with lot of built-in functionality. To get the title from web-page
there are lot of complexities, but being the user of selenium to get the title we use getTitle() which is
Abstraction.
Example:
public interface SWITCH
{
void on();
void off();
}
public class Bulb implements SWITCH
{
public void on()
{
System.out.println("bulb is turned on");
}
public void off()
{
System.out.println("bulb is turned off");
}
}
public class Fan implements SWITCH
{
public void on()
{
System.out.println("Fan is turned on");
}
public void off()
{
System.out.println("Fan is turned off");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 112
Output:
Fan is turned on
Fan is turned off
Developer-Tester
Core Java JyothiShankar Mahakul 113
18. ENCAPSULATION
Restricting the direct access to the data members and giving indirect access to the data
members through the getter and setter method is called as Encapsulation.
While performing encapsulation, the data members will be declared as Private and getters and
setters method be declared as Public.
Getter are public method which will give the data and Setter are public method which will manipulate
the data.
Conceptually they are getters and setters, but method name need not to be always get and set.Its a
standard industry convention to name gets and sets with get and set followed by private data
member name.
i.e., get<private data members>
set<private data members>
Ex: getBalance()
setBalance()
Example: Balance of a Account holder should always be developed as private data members in
programs so that code can access it or manipulate it directly(it should happen through getters and
setters method based on Business condition).
Example:
package Encapsulation;
class Z
{
private double empSal;
Z(double empSal)
{
this.empSal=empSal;
}
public double getempSal()//Getters
{
return empSal;
}
Developer-Tester
Core Java JyothiShankar Mahakul 114
Output:
Emp sal is2000.5
Emp sal is9000.5
Example:
package Encapsulation;
public class Sample
{
private int a;
private double d;
Sample(int a, double d)
{
this.a=a;
this.d=d;
}
public int getA()
{
return a;
}
public void setA(int a)
{
this.a=a;
}
public double getD()
{
return d;
}
public void setD(double d)
{
this.d=d;
}
}
class Tester2
{
public static void main(String[] args)
{
Sample s=new Sample(10,10.5);
System.out.println("value of a " +s.getA());
Developer-Tester
Core Java JyothiShankar Mahakul 115
Example:
package Encapsulation;
class Account
{
private double balance=5000;
public double getBalance()
{
return balance;
}
public void setBalance(double tamount)
{
if (tamount>0)
{
balance+=tamount;
System.out.println("Transferred" +tamount);
}
else
{
System.out.println("Invalid amount");
}
}
}
class Tester3
{
public static void main(String[] args)
{
Account a=new Account();
System.out.println("Balance=" +a.getBalance());
a.setBalance(1000);
System.out.println("Balance=" +a.getBalance() +"Rs");
a.setBalance(-6000);
System.out.println("Balance" +a.getBalance() +"Rs");
}
}
Output:
Balance=5000.0
Transferred1000.0
Balance=6000.0Rs
Invalid amount
Balance6000.0Rs
Developer-Tester
Core Java JyothiShankar Mahakul 116
Packages are like folders which are used to group similar kind of programs.
Through packages we can achieve,
1. Encapsulation
2. Logical Division
3. Avoid naming collisions.,i.e., we can have same class name across interfaces/class name.
Note:
1.Package statement should be the first statement in java file.
2.All the source file will be stored in the classes or bin folder.
3.All the sub folder of src are considered packages.
4.Always compilation should be from src folder.
5.Always execution should be from class folder.
Example:
package Package;
public class A
{
public static void main(String[] args)
{
System.out.println("Hello JSM");
}
}
Output:
Hello JSM
Example:
package Package2;
import Package.A;
public class B
{
public static void main(String[] args)
{
System.out.println("hello Smp");
}
}
Output:
hello Smp
Access Levels
Access levels are used to put restrictions on the members and through access levels we can achieve
encapsulation.
There are 4 Access levels,
1. Public
2. Protected
3. Default
4. Private
1. Public: Public members will have application level access i.e., public members can be accessed
from any program of any packages.
Note: Public is the most visible access levels.
2. Default: Default members will have package level access i.e., default members can be accessed
only within the current package programs in which it is created.
Note: If any members is not declared with any others access level then that members will have
default access levels. i.e., there is no keyword to members default.
Developer-Tester
Core Java JyothiShankar Mahakul 117
3. Private: Private members will have class level access i.e., private members can be accessed only
within the class in which it is created.
Note:In other words, private members cannot be accessed outside the class.
Note:Private members will not be involved in inheritance.
4. Protected: Protected members can be accessed within the package like default access level and
it can be accessed outside the package through inheritance.
Public
Protected
Default
Private
Note:
1. To access the members of a class present in other package we should first import the class from
other packages by using import statement.
Ex: import pack1.A
2. Import statement should always be developed after package statement(because
Package statement should be first statement in the file)
3. We can develop multiple import statemnet in one java file in other words we can use members
of different classes available in different package in one file.
Ex: import pack1.A;
Import pack2.sample;
4. If there are lot of classes in one package and if you want to import all the classes of that package
then we should use *..
Ex: import pack1.*;
Note: Protected members can be accessed outside the package only through inheritance and we
should create sub class object.
Note:
1. A class cannot be declared with private and protected access levels.
2. A class can have only two access levels Public and Default.
3. Private and Protected access levels are only for members of a class not for the class itself.
4. Public classes can be imported through import statement but Default classes cannot be
imported.
5. In java file we can develop maximum one public class nand that public class name should be java
file name.(Rule of Java)
I.Q: While overriding a super class method in the sub class, can we change the access level of the
method from default to public.
YES, while overriding we can expand the access level from default to protected or public . BUT
we cannot weaken the access level from public to protected or default
Developer-Tester
Core Java JyothiShankar Mahakul 118
Example:
package Package3;
public class C
{
public void test1()
{
System.out.println("public test1()");
}
protected void test2()
{
System.out.println("protected test2()");
}
void test3()
{
System.out.println(" Test3()");
}
private void test4()
{
System.out.println("Private test4()");
}
}
package Package4;
import Package3.C;
public class D extends C
{
public static void main(String[] args)
{
D d=new D();
d.test1();
d.test2();
}
}
Output:
public test1()
protected test2(
Developer-Tester
Core Java JyothiShankar Mahakul 119
Identifying the best solution for the frequently occurring problem and usung the same solution
henceforth(thereafter) if the same problem is reoccurring is called as Design Pattern.
While Development and Automation there will be some frequently occurring problem for those
frequently occurring problem some solution are designed by other developer in the industry such
type pf solution are called as Design Pattern.
There are lot of Design Pattern some of them are.
1. Singleton class Design Pattern.
2. Doubleton Class Design Pattern.
3. Immutable Class Design Pattern.
1. Singleton class Design Pattern: The class for which only one object can be created such type of
class is called as Singleton class.
To Achieve Singleton class Design Pattern we should follow 2 things,
a. Constructor of that class should be Private.
b. There shoul be public, static method which should return only 1 object of that class.
Note:
a) Singleton means Single object of that class referred by multiple references.
b) Through Singleton class design pattern memory can be managed effectively.
2. Doubleton class Design Pattern:The class for which only 2 object can be created such type of
classes are called as Doubleton class Design Pattern.
3. Immutable Object Design Pattern: The class object for which state can be changed such type of
object are called as Immutable Object Design Pattern.
To achieve Immutable object Design pattern,
a) Data members should be private.
[gets() should be developed without sets()]
b) Variables should be final and that final variable should be initialized through Constructor.
Note:
1. Final Global Variables can be initialized through constructor also.
2. Design PAttern are not any built-in functionality, they are just proposed solution to existing
problem.
Developer-Tester
Core Java JyothiShankar Mahakul 120
else
{
return a1;
}
}
}
public class Tester
{
public static void main(String[] args)
{
A rv1=A.demo();
rv1.m1();
A rv2=A.demo();
rv2.m1();
A rv3=A.demo();
rv3.m1();
}
}
Output:
Running Private Constructor
non-static method
non-static method
non-static method
Developer-Tester
Core Java JyothiShankar Mahakul 121
Output:
rv1.getI()
8
rv2.getJ()
9.5
Developer-Tester
Core Java JyothiShankar Mahakul 122
Definition:
IIB are executed when objects are created, the number of times we create objects same number
of times IIB will be called.
IIB are used to initialize all the instance variable in one place and give us better readability of
code.
IIB purpose is to initialize all non-static members in one place for readability.
Example:
public class Z
{
{
System.out.println("from IIB");
}
public static void main(String[] args)
{
Z z1=new Z();// When object is created
}
}
Output:
from IIB
Example:
public class Y
{
{
System.out.println("from IIB");
}
public static void main(String[] args)
{
}
}
Output:
No output because no object is created
Note:
IIB will be called first because first initialize variable then load into object and then Constructor will be
called.
Example:
public class X
{
X()
{
System.out.println("from Constructor");
}
{
System.out.println("from IIB");
}
public static void main(String[] args)
{
X x1=new X(); // IIB
System.out.println("from main");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 123
Output:
from IIB
from Constructor
from main
Note:
When object is created, initialization begins.
Instance variables can be directly accessed by IIB.
Example:
public class V
{
int i;
{
i=20;
System.out.println(i);//instance variable can be directly accessed by IIB
}
public static void main(String[] args)
{
V v1=new V();
}
}
Output:
20
Note:
We can initialize both static and non-static variable both inside IIB.
Example:
public class U
{
static int i;
{
i=40;
System.out.println(i);
}
public static void main(String[] args)
{
U u1=new U();
}
}
Output:
40
Example:
public class W
{
W()
{
System.out.println("From constructor");
}
{
System.out.println("from IIB-2");
}
{
System.out.println("from IIb-1");
}
Developer-Tester
Core Java JyothiShankar Mahakul 124
Output:
from IIB-2
from IIb-1
From constructor
Developer-Tester
Core Java JyothiShankar Mahakul 125
Static block runs first then main() in the sequence, and it does not require any invoking
statement and runs only once.
Example:
public class T
{
static
{
System.out.println("from SIB");
}
public static void main(String[] args)
{
}
}
Output:
from SIB
Example:
public class S
{
static
{
System.out.println("from SIB");
}
public static void main(String[] args)
{
System.out.println("from main");
}
}
Output:
from SIB
from main
Example:
public class R
{
static
{
System.out.println("from SIB-1");
}
static
{
System.out.println("from SIB-2");
}
public static void main(String[] args)
{
System.out.println("from main");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 126
Output:
from SIB-1
from SIB-2
from main
Note:
1.IIB can initialize both static & non-static variables, but a SIB can use only static variable initialization.
2.Reference variable can access static and non-static variables.
3.Class can access static anything that is static it belongs to class.
4.In SIB, instance variable initialization is not possible.
5.We cannot initialize non-static variable inside SIB.
Example:
public class Q
{
{
System.out.println("IIB");
}
static
{
System.out.println("SIB");
}
public static void main(String[] args)
{
Q q1=new Q();
}
}
Output:
SIB
IIB
Example:
public class P
{
{
System.out.println("IIB");
}
P()
{
System.out.println("P()");
}
static
{
System.out.println("SIB");
}
public static void main(String[] args)
{
new P();
System.out.println("main");
}
}
Output:
SIB
IIB
P()
main
Developer-Tester
Core Java JyothiShankar Mahakul 127
Example:
public class O
{
{
System.out.println("1");
}
{
System.out.println("2");
}
static
{
System.out.println("3");
}
O()
{
System.out.println("4");
}
public static void main(String[] args)
{
O o1=new O();
System.out.println("main");
}
}
Output:
3
1
2
4
main
Example:
public class N
{
{
System.out.println("IIB");
}
static
{
new N();// IIB will be called by using the statement
System.out.println("SIB");
}
N()
{
System.out.println("N()");
}
public static void main(String[] args)
{
//new N();
System.out.println("main");
}
}
Output:
IIB
N()
SIB
main
Developer-Tester
Core Java JyothiShankar Mahakul 128
Example:
public class M
{
static
{
System.out.println("SIB");
}
static
{
System.out.println("Hello");
new M();// IIB will be called
}
{
System.out.println("IIB");
}
public static void main(String[] args)
{
new M();
System.out.println("main");
}
}
Output:
SIB
Hello
IIB
IIB
main
Example:
public class L
{
public void test()
{
System.out.println("test()");
}
public static void main(String[] args)
{
new L().test();
}
{
System.out.println("IIB");
}
L()
{
System.out.println("L()");
}
}
//Execution
1. Object is created.
2. then IIB is called.
3. When object is created, constructor is called so print L
Output:
IIB
L()
test()
Developer-Tester
Core Java JyothiShankar Mahakul 129
Note:
Inside IIB, can we create a object?
Yes, the program will run and stop abruptly without getting error.
Example:
public class K
{
{
System.out.println("IIB");
new K();
}
public static void main(String[] args)
{
K k1=new K();
System.out.println("from main");
}
}
Output:
IIB
IIB
IIB
IIB
IIB
Exception in thread "main" java.lang.StackOverflowError
Example:
public class J
{
{
System.out.println("IIB");
}
static
{
new J(); //run's first
System.out.println("SIB");//run's second
new J();// run's third
}
public static void main(String[] args)
{
System.out.println("from main");
}
}
Output:
IIB
SIB
IIB
from main
Developer-Tester
Core Java JyothiShankar Mahakul 130
4. Notify()
5. notifyAll() public final methods(interthread communication)
6. wait()
7. getclass() Reflections
8. Clone() protected()
9. Finalize() protected()
1. toString()
1. tostring() is a non-static method of object class which will be inherited to every class of java.
2. tostring() will be available to every object of java.
3. tostring() will give the object information in the string form i.e., it will give the string
representation of the object on which it is called.
4. String representation will contain fully qualified class name with converted hexadecimal
numbers for the memory address of object with the separator @.
5. Fully qualified class name means packagename.classname .
6. Whenever we print any reference variable in java, there will be implicit call to tostring() of
that object(implicit call means automatically the method will be called).
7. toString() is a public non-final methos of a object class,
8. Any sub class can over ride toString().
9. toString() will always be over ridden to give the detail information of object including
attribute and its value.
10. toString() return type is String and its signature is
Public string toString()
{
}
Note:
1. Java does not supprt pointers so its very secure.
2. We cannot get the exact memory address of object in java, either we get hexadecimal number or
hash number but not exact memory address.
3. We cannot increment the reference variable i.e.,rv1++(not possible).
Example:
class A
{
public static void main(String[] args)
{
A rv1=new A();
A rv2=new A();
System.out.println(rv1.toString());
System.out.println(rv2.toString());
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 131
Output:
ObjectClass.A@15db9742
ObjectClass.A@6d06d69c
Example:
public class Sample
{
}
class Tester
{
public static void main(String[] args)
{
Sample s=new Sample();
Sample s2=new Sample();
System.out.println(s.toString());
System.out.println(s2.toString());
Sample s3=new Sample();
Sample s4=s3;
System.out.println(s3.toString());
System.out.println(s4.toString());
}
}
Output:
ObjectClass.Sample@15db9742
ObjectClass.Sample@6d06d69c
ObjectClass.Sample@7852e922
ObjectClass.Sample@7852e922
Example:
class Demo
{
}
public class Tester2
{
public static void main(String[] args)
{
Demo d=new Demo();
System.out.println(d);//Implicit call to toString
Demo d2=new Demo();
System.out.println(d2);//Implicit call to toString
}
}
Output:
ObjectClass.Demo@15db9742
ObjectClass.Demo@6d06d69c
Example:
class B
{
public String toString()
{
return "B class Object";
}
}
public class Tester1
{
public static void main(String[] args)
Developer-Tester
Core Java JyothiShankar Mahakul 132
{
B b=new B();
System.out.println(b);
B b1=new B();
System.out.println(b1);
}
}
Output:
B class Object
B class Object
2.equals()
1. equals() is a non-static method of object class which will be inherited to every class of java.
2. equals() will be available to every object of java.
3. equals() will compare 2 objects equality based on memory address, if memory address
are same it returns true otherwise false.
4. equals() is a public non-final methods of object class.
5. Any sub class can override equals().
6. equals() will always be overridden to compare 2 objects equality based on the attributes.
Ex: if you want to compare 2 employee class object based on the employeeId attribute then
equals should be overridden..
7. Basically 2 identify the duplicate, equals() will be overridden.
8. equals() return type is Boolean and the signature is
public boolean equals(object obj)
{
What is the difference between comparison through equals() and comparison operator
overloading(==).
There is no concept of operator overloading in java, i.e., we cannot change the implementation
of operator but there is a concept of overloading i.e., we change the implementation of methods.
So equals() can be overridden based on the attribute or comparison but comparison operator(==)
cannot be overridden.
Example:
package ObjectClass;
class Z
{
}
public class Tester4
{
public static void main(String[] args)
{
Z z=new Z();
Z z2=new Z();
System.out.println(z.equals(z2));
Z z3=new Z();
Z z4=z3;
System.out.println(z3.equals(z4));
}
}
Output:
false
True
Developer-Tester
Core Java JyothiShankar Mahakul 133
Example:
package ObjectClass;
class Employee
{
int empId;
Employee(int empId)
{
this.empId=empId;
}
public boolean equals(Object obj)
{
Employee e=(Employee)obj;
if(this.empId=e.empId)
{
return true;
}
else
{
return false;
}
}
}
public class Tester5
{
public static void main(String[] args) {
{
Employee e1=new Employee(10);
Employee e2=new Employee(10);
System.out.println(e1.equals(e2));
Employee e3=new Employee(30);
Employee e4=new Employee(40);
System.out.println(e3.equals(e4));
}
}
}
Output:
True
False
3. hashcode()
1. hashcode() is a non-static method of object class which will be inherited to every class of
java.
2. hashcode() will be available to every object of java.
3. hashcode() will give a unique integer number based on the memory address of the object
i.e., it will give the integer representation of the object.
4. The unique integer number will be generated by using some hashing algorithm
5. The unique integer number is also called as hash number.
6. Hash code is a public non-final methods of object class so any sub class can override it.
7. Always hashcode() will be overridden to generate the has number by using the attributes of
the object.
8. hashcode() return type is int.
9. hashcode() signature is
public int hashcode()
{
Developer-Tester
Core Java JyothiShankar Mahakul 134
Example:
package ObjectClass;
class N
{
}
public class Tester6
{
public static void main(String[] args)
{
N n=new N();
N n2=new N();
System.out.println(n.hashCode());//Diiferent output
System.out.println(n2.hashCode());
N n3=new N();
N n4=n3;
System.out.println(n3.hashCode());//Same Output
System.out.println(n4.hashCode());
}
}
Output:
366712642
1829164700
2018699554
2018699554
Example:
package ObjectClass;
class M
{
int i;
int j;
M(int i,int j)
{
this.i=i;
this.j=j;
}
public int hashcode()
{
return i+j;
}
}
public class Tester7
{
public static void main(String[] args)
{
Developer-Tester
Core Java JyothiShankar Mahakul 135
M m1=new M(70,70);
System.out.println(m1.hashCode());
M m2=new M(10,10);
System.out.println(m2.hashCode());
}
}
Output:
366712642
1829164700
Developer-Tester
Core Java JyothiShankar Mahakul 136
24. ASSERT
Assert helps to check the business condition only if the Business condition is true then assert will
continue with program execution or else will not execute the program if business condition is false.
Assert was introduced in JDK 1.4.
By default assert will not work. i.e., we cannot use it directly. We need to enable it.
Example:
public class A
{
public static void main(String[] args)
{
int age=10;
assert age>20;
System.out.println("Register your self");
}
}
Output:
Exception in thread "main" java.lang.AssertionError, at asserts.A.main(A.java:8)
Example:
public class A
{
public static void main(String[] args)
{
int age=100;
assert age>20;
System.out.println("Register your self");
}
}
Output:
Register your self
Example:
public class B
{
public static void main(String[] args)
{
int age=100;
try
{
assert age>20;
System.out.println("Register your self");
}
catch(AssertionError e)
{
System.out.println(e);
System.out.println("You are too young");
}
}
}
Output:
Register your self
Developer-Tester
Core Java JyothiShankar Mahakul 137
Note:
1) assert creates an exception when condition fails.
2) assert should be handled using try catch blocks.
3) Conditions used in assert should be Boolean value.
4) Multiple assert statement can be used in same class.
5) Statement following assert will execute when assert is true.
6) Statement following assert will not execute when assert is false.
Example:
public class C
{
public static void main(String[] args)
{
assert true;
System.out.println("hello");
assert false;
System.out.println("Error");
}
}
Output:
hello
Exception in thread "main" java.lang.AssertionError, at asserts.C.main(C.java:9)
Example:
public class D
{
public static void main(String[] args)
{
assert test();
System.out.println("From main()");
}
public static boolean test()
{
System.out.println("from test()");
return false;
}
}
Output:
From main()
Example:
public class E
{
public static void main(String[] args)
{
assert test();
System.out.println("from main");
}
public static boolean test()
{
System.out.println("from test");
return true;
}
}
Output:
from test
from main
Developer-Tester
Core Java JyothiShankar Mahakul 138
NOTE:
1. String variables are reference variables
2. String is a class and even it is also a Sub class to Object class.
3. All the non-static method of object class will be inherited to String class.
4. The 3 non-static methods of Object class, to_String(), equals() and hashcode() are overridden in
String class based on the String values of the object.
5. to_String() is overridden in the String class to give the String value of the Object.
6. equals() has been overridden in the String class to return true if String values are same, otherwise
false(case-sensitive).
7. hashcode() has been overridden in String class to give has# based in the String value of the Object.
Example:
public class Test1
{
public static void main(String[] args)
{
String rv1 = new String("Hello");
String rv2 = new String("hello");
System.out.println(rv1);
System.out.println(rv2);
System.out.println(rv1.equals(rv2));
System.out.println(rv1==rv2);
System.out.println(rv1.hashCode());
System.out.println(rv2.hashCode());
}
}
Output:
Hello
hello
false
false
69609650
99162322
Developer-Tester
Core Java JyothiShankar Mahakul 139
Example:
public class Test2
{
public static void main(String[] args)
{
String rv1="Hey";
String rv2="Hey";
System.out.println(rv1);
System.out.println(rv2);
System.out.println(rv1.equals(rv1));
System.out.println(rv1.hashCode());
System.out.println(rv2.hashCode());
}
}
Output:
Hey
Hey
true
72444
72444
Example:
public class Test3
{
public static void main(String[] args)
{
String rv1 = new String("WateMelon");
String rv2 = "WaterMelon";
String rv3 = "Water";
String rv4 = "Melon";
String rv5 = "Water"+"Melon";
String rv6 = rv3+"Melon"; // new Operator will be used.
System.out.println(rv1==rv2);
System.out.println(rv2==rv5);
System.out.println(rv1==rv6);
}
}
Output:
false
true
false
String Pool:
1. All the String objects will be stored in String pool of the heap memory.
2. String pool is further divided into 2 pools
A) Constant pool:
All the String Objects created by using (double quotes) will be stored in the constant pool.
In constant pool, duplicates are not allowed.
Note: Duplicate means 2 string objects having same string values.
Developer-Tester
Core Java JyothiShankar Mahakul 140
B) Non-Constant pool:
String Objects which are created using new Operator will be stored in non-constant pool.
In non-constant pool, duplicates are allowed.
Note: if reference variables are used for concatenation, then the resultant string will be created using
new Operator.(so it will be stored in non-constant pool)
Ex: String rv1 = water;
String rv2 = rv1 + Melon;
Here, the resultant String watermelon will be created using operator internally so the resultant String
will be stored in on-constant pool
Example:
public class Test4
{
public static void main(String[] args)
{
String rv1 = new String("WaterMelon");
String rv2 = "WaterMelon";
String rv3 = "Water";
String rv4 = "Melon";
String rv5 = "Water" + "Melon";
String rv6 = rv3+"Melon";
System.out.println(rv1.equals(rv2));
System.out.println(rv2.equals(rv3));
System.out.println(rv1.equals(rv6));
}
}
Output:
true
false
true
NOTE: Always we should compare String using equals method, we should not use comparison
operator to compare String value because comparison operator will compare the memory address of
the String reference.
So though String value are same, it returns false.
equals() is best approach because it will compare the String value.
String class is immutable.
Example:
public class Test5
{
public static void main(String[] args)
{
String rv1 = "Subash";
String rv2 = "Subash";
String rv3 = "subash";
System.out.println(rv1);
System.out.println(rv2);
System.out.println(rv3);
System.out.println("------------")
;
rv2="Chandra";
System.out.println(rv1);
System.out.println(rv2);
System.out.println(rv3);
System.out.println("-------------");
Developer-Tester
Core Java JyothiShankar Mahakul 141
rv3="Bose";
System.out.println(rv1);
System.out.println(rv2);
System.out.println(rv3);
}
}
Output:
subash
------------
Subash
Chandra
subash
-------------
Subash
Chandra
Bose
Note:
String class is immutable. Justify?
Existing String Objects String value cannot be changed or modified nor updated. So we say string
class as immutable.
String is a final class.
Example:
public class Test6
{
public static void main(String[] args)
{
String rv = "I love India";
System.out.println(rv.length());
System.out.println(rv.charAt(3));
System.out.println(rv.charAt(8));
System.out.println("---------");
System.out.println(rv.indexOf('v'));
System.out.println(rv.indexOf('I'));
System.out.println("---------------");
System.out.println(rv.toLowerCase());
System.out.println(rv.toUpperCase());
System.out.println(rv.startsWith(" I love"));
System.out.println(rv.endsWith("America"));
System.out.println("------------");
System.out.println(rv.contains("Love"));
System.out.println("-------------");
System.out.println(rv.substring(2));
System.out.println(rv.substring(2, 9));
System.out.println("----------");
System.out.println(rv.isEmpty());
}
}
Output:
12
o
n
---------
4
0
Developer-Tester
Core Java JyothiShankar Mahakul 142
---------------
i love india
I LOVE INDIA
false
false
------------
false
-------------
love India
love In
----------
false
Example:
public class Test7
{
public static void main(String[] args)
{
String rv = " Welcome to World ";
System.out.println(rv);
System.out.println(rv.trim());
}
}
Output:
Welcome to World
Welcome to World
Example:
public class Test8
{
public static void main(String[] args)
{
String rv = "AIDNI";
System.out.println("The original string is " +rv);
System.out.println("the reverse string is ::" );
for(int i=rv.length()-1;i>=0;i--)
{
System.out.print(rv.charAt(i));
}
}
}
Output:
The original string is AIDNI
the reverse string is ::
INDIA
Example:
public class Test9
{
public static void main(String[] args)
{
String rv1 = "DAD";
String rv2 = "";
for(int i=rv1.length()-1;i>=0;i--)
{
rv2=rv2+rv1.charAt(i);
}
Developer-Tester
Core Java JyothiShankar Mahakul 143
Example:
//count of total number of Occurrence of 'A'
public class Test10
{
public static void main(String[] args)
{
String rv = "MALAYALAM";
int count =0;
for(int i=0;i<rv.length();i++)
{
if(rv.charAt(i)=='A')
{
count++;
}
}
System.out.println("the count is " +count);
}
}
Output:
the count is 4
Example:
public class Test11
{
public static void main(String[] args)
{
String rv = "Google";
System.out.println(rv);
rv = rv.replace('G', 'D');
System.out.println(rv);
}
}
Output:
Google
Doogle
Developer-Tester
Core Java JyothiShankar Mahakul 144
26. ARRAYS
Arrays are contiguous memory allocation where-in we can store homogeneous element(similar
kind of element) which will share the common name.
If you want to store the collection of similar data, then we can use arrays.
To store the huge collection of similar data, best approach is arrays because memory allocation
will be continuous due to which processing will be faster.
Ex: If you want to store 100 integer data, best approach is arrays. If arrays are not used then we
have to use 100 different variables.
Example:
rv = new int [5];
10 20 30 40 50
0 1 2 3 4
Primitive Array:
Example:
public class Test1
{
public static void main(String[] args)
{
int[] rv = new int[5]; //Creating an integer array with 5 slots
rv[0] = 10;
rv[1] = 20;
rv[2] = 30;
rv[3] = 40;
rv[4] = 50;
System.out.println("length is:: " +rv.length);
for(int i=0;i<rv.length;i++)
{
System.out.println(i);
}
}
}
Output:
length is:: 5
0
1
2
3
4
Developer-Tester
Core Java JyothiShankar Mahakul 145
Example:
public class Test2
{
public static void main(String[] args)
{
int[] arr = new int[6];
arr[0]=99;
arr[1]=99;
arr[2]=99;
arr[3]=99;
arr[4]=99;
arr[5]=99;
int total = 0;
for(int i=0;i<arr.length;i++)
{
System.out.println("marks in subject number " +(i+1)+ "::" +arr[i]);
total=total+arr[i];
}
System.out.println("----------------");
System.out.println("total marks secured ::" +total);
int avg = total/arr.length;
System.out.println("------------------");
System.out.println("Average marks is ::" +avg);
}
}
Output:
marks in subject number 1::99
marks in subject number 2::99
marks in subject number 3::99
marks in subject number 4::99
marks in subject number 5::99
marks in subject number 6::99
----------------
total marks secured ::594
------------------
Average marks is ::99
Example:
public class Test3
{
public static void main(String[] args)
{
double[] darr = new double[5];
darr[0]=10.1;
darr[1]=10.2;
darr[2]=10.3;
darr[3]=10.4;
darr[4]=10.5;
System.out.println("---Enhanced for loop---");
for(double d:darr)
{
System.out.println(d);
}
System.out.println("------------------");
char[] carr = new char[5];
carr[0] = 'A';
carr[1] = 'B';
Developer-Tester
Core Java JyothiShankar Mahakul 146
carr[2] = 'C';
carr[3] = 'D';
carr[4] = 'E';
for(char c:carr)
{
System.out.println(c);
}
}
}
Output:
---Enhanced for loop---
10.1
10.2
10.3
10.4
10.5
------------------
A
B
C
D
E
Example:
//To find largest element in a given integer array
public class Test4
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
int largest = arr[0]; //Assumption
for(int i=1;i<arr.length;i++)
{
if(largest<arr[i])//Checking the assumption
{
largest = arr[i];
}
}
System.out.println("largest element is " +largest);
}
}
Output:
largest element is 50
Example:
public class Test5
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0] = 50;
Developer-Tester
Core Java JyothiShankar Mahakul 147
arr[1] = 40;
arr[2] = 30;
arr[3] = 20;
arr[4] = 10;
int index=0;
int smallest = arr[0];
for(int i=1;i<arr.length;i++)
{
if(smallest>arr[i])
{
smallest=arr[i];
index=i;
}
}
System.out.println("smallest element "+ smallest +" is available @index "+ index);
}
}
Output:
smallest element 10 is available @index 4
Example:
//search given element in a array is existing or not, if its existing print the index of that element
otherwise print -1
public class Test6
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
int search = 50;
boolean b=true;
for(int i=0;i<arr.length;i++)
{
if(search == arr[i])
{
b=false;
System.out.println("element is available @ index " +i);
break;
}
}
if(b==true)
{
System.out.println("Element is not available " +(-1));
}
}
}
Output:
element is available @ index 4
Developer-Tester
Core Java JyothiShankar Mahakul 148
Example:
//sort the elements of a given array in ascending order
public class Test7
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0]=50;
arr[1]=40;
arr[2]=30;
arr[3]=20;
arr[4]=10;
System.out.println("Before");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]>arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("After");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Output:
Before
50
40
30
20
10
After
10
20
30
40
50
Developer-Tester
Core Java JyothiShankar Mahakul 149
Example:
//to find the sum of even number in a given integer array
public class Test8
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0]=10;
arr[0]=11;
arr[0]=12;
arr[0]=13;
arr[0]=14;
int sum=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
sum=sum+arr[i];
}
}
System.out.println("elements sum is " +sum);
}
}
Output:
elements sum is 14
Derived Array:
Example:
class A
{
}
public class Test1
{
public static void main(String[] args)
{
A[] ref = new A[5];
ref[0] = new A();
ref[1] = new A();
ref[2] = new A();
ref[3] = new A();
ref[4] = new A();
System.out.println("length is " +ref.length);
for(int i=0;i<ref.length;i++)
{
System.out.println(ref[i]);
}
}
}
Output:
length is 5
derivedarray.A@15db9742
derivedarray.A@6d06d69c
derivedarray.A@7852e922
derivedarray.A@4e25154f
derivedarray.A@70dea4e
Developer-Tester
Core Java JyothiShankar Mahakul 150
Example:
class B
{
public String toString()
{
return "B class Object";
}
}
public class Test2
{
public static void main(String[] args)
{
B[] ref = new B[5];
for(int i=0;i<ref.length;i++)
{
ref[i]=new B();
}
for(int i=0;i<ref.length;i++)
{
System.out.println(ref[i]);
}
}
}
Output:
B class Object
B class Object
B class Object
B class Object
B class Object
Example:
class Employee
{
int empid;
double salary;
public Employee(int empid,double salary)
{
this.empid=empid;
this.salary=salary;
}
}
public class Test3
{
public static void main(String[] args)
{
Employee[] ref=new Employee[5];
ref[0] = new Employee(10,100000);
ref[1] = new Employee(20,200000);
ref[2] = new Employee(30,300000);
ref[3] = new Employee(40,400000);
ref[4] = new Employee(50,500000);
for(int i=0;i<ref.length;i++)
{
System.out.println(ref[i].empid + "::" + ref[i].salary);
}
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 151
Output:
10::100000.0
20::200000.0
30::300000.0
40::400000.0
50::500000.0
Example:
public class Test4
{
public static void main(String[] args)
{
Example:
public class Test5
{
public static void main(String[] args)
{
String[] ref = new String[5];
ref[0] = "AB";
ref[1] = "Cd";
ref[2] = "EF";
ref[3] = "GH";
ref[4] = "IJ";
for(int i=0;i<ref.length;i++)
{
ref[i]=ref[i].toUpperCase();
}
Arrays.sort(ref);
for(String s:ref)
{
System.out.println(s);
}
System.out.println(Arrays.binarySearch(ref, "AB"));
System.out.println(Arrays.binarySearch(ref, "AB"));
System.out.println(Arrays.binarySearch(ref, "ABCD"));
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 152
Output:
AB
CD
EF
GH
IJ
0
0
-2
Example:
import java.util.Arrays;
public class Test6
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0] = 50;
arr[1] = 40;
arr[2] = 30;
arr[3] = 20;
arr[4] = 10;
Arrays.sort(arr);
System.out.println(Arrays.binarySearch(arr,40));
System.out.println(Arrays.binarySearch(arr,6));
System.out.println(Arrays.binarySearch(arr,15));
System.out.println(Arrays.binarySearch(arr,45));
}
}
Output:
3
-1
-2
-5
Example:
public class Test7
{
public static void main(String[] args)
{
String rv="We live in Earth";
String[] ref=rv.split(" ");
for(String s:ref)
{
System.out.println(s);
}
System.out.println("length of the String is " +ref.length);
}
}
Output:
We
live
in
Earth
length of the String is 4
Developer-Tester
Core Java JyothiShankar Mahakul 153
Example:
public class Test8
{
public static void main(String[] args)
{
String rv="Customer Relationship Management";
String[] ref=rv.split(" ");
String a = " ";
a = a+ref[0].charAt(0)+ref[1].charAt(0)+ref[2].charAt(0);
System.out.println(a);
}
}
Output:
CRM
Example:
public class Test9
{
public static void main(String[] args)
{
String rv = "Customer Relationship Management, Enterprise Relationship Planning";
String[] ref = rv.split(" ");
String a = " ";
for(int i=0;i<ref.length;i++)
{
a=a+ref[i].charAt(0);
}
System.out.println(a);
}
}
Output:
CRMERP
Limitations of Arrays:
1. Size is fixed i.e., once an array is created with some size it cannot be expanded or compressed i.e.,
arrays size in not flexible.
2. Some times we may waste the memory or sometimes we may need additional memory.
3. In arrays we can store only homogeneous data or elements.
4. There are very less built-in functionality in array.
Developer-Tester
Core Java JyothiShankar Mahakul 154
27. COLLECTION
CollectionI
Linked HashSetI
Navigable SetI
Tree SetC
Collections is a framework or API, in which there are lot of classes, interfaces and built-in
functionality which will serve the common purpose.
1. All the collections framework functionality has been implemented using standard data structure
like(stack, queue, single and doubly list).
2. All the collection framework related class and interfaces are available in java.util package.
3. In collections Size will be dynamic and we can store heterogeneous elements.
4. Collections are called as Dynamic Array.(All the elements added in collections will be stored as an
Object)
5. Collections is a root interface in Collections framework which defines some common features.
6. Collections is a concrete class in collections framework which provides some utility method like
sorting, searching , etc..,.
7. Base on the variations in the requirements, collection is categorized into 4 types.
a. List
b. Queue
c. Set
d. Map
a. List:
1. To maintain the insertion order with indexing we should go for list tyoe of collections.
2. Features of List:
a) List is dynamic
b) In list, we can store heterogeneous data.
c) List is a index type of collection i.e., the elements will be stored upon index with
auto-indexing and sequential indexing.
d) List allows duplicate.
e) List allows Null.
f) As it is a index based collection to fetch the elements we can use index.
Developer-Tester
Core Java JyothiShankar Mahakul 155
1. ArrayList:
Arraylist memory allocation is contiguous, so random access to any element will be faster.
But insertion operation is not good in arraylist because shuffling should happen to rest of
element.
Whenever requirement is more on searching operation or random access to any element
required is more then we should choose ArrayList.
2. VectorList:
Vector class methods are synchronized methods or thread safe methods i.e., when one thread is
executing a vector method another Thread cannot execute the vector method.
Ex: BackButton implementation will be done using _____ to record the navifgation of user in
web page.
3. LinkedList:
LinkedList memory allocation is not contiguous i.e., linkedlist ,memory allocation is exactly like
linkedlist data structure i.e., one element will have linked to the another element.
10 90 20
LinkedList elements will be scattered in the memory.
Insertion operation will be good in LinkedList because one link will be attached to new element
which is inserted.
While coding if insertion operation is more like updating record etc., then we should choose
linkedList.
Random access to any element is not good in LinkedLIst.
Example:
import java.util.ArrayList;
class A
{
}
public class Test1
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add(10);
list.add(10.5);
list.add('A');
list.add("hey");
list.add(true);
list.add(10);
list.add(new A());
System.out.println("list is " +list);
System.out.println("size of array list is " +list.size());
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 156
Output:
list is [10, 10.5, A, hey, true, 10, collection.A@15db9742]
size of array list is 7
10
10.5
A
hey
true
10
collection.A@15db9742
Example:
import java.util.ArrayList;
public class Test2
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add(10);
list.add(10.5);
System.out.println(list);
list.add("Hi");//Appends the given element to the end
System.out.println(list);
list.add(1,90);//Inserts the given element into the given index
System.out.println(list);
list.set(0, true);//modifies the given indexed element with new Element
System.out.println(list);
}
}
Output:
[10, 10.5]
[10, 10.5, Hi]
[10, 90, 10.5, Hi]
[true, 90, 10.5, Hi]
Example:
import java.util.ArrayList;
public class Test3
{
public static void main(String[] args)
{
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
ArrayList list3 = new ArrayList();
list1.add(10);
list1.add(20.5);
list1.add('A');
list2.add(30.3);
list2.add("hi");
list2.add(90);
list3.add('C');
list3.add(true);
list3.add(50);
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
Developer-Tester
Core Java JyothiShankar Mahakul 157
list1.addAll(list2);
System.out.println(list1);
list2.addAll(list3);
System.out.println(list2);
}
}
Output:
[10, 20.5, A]
[30.3, hi, 90]
[C, true, 50]
[10, 20.5, A, 30.3, hi, 90]
[30.3, hi, 90, C, true, 50]
Example:
import java.util.ArrayList;
public class Test4
{
public static void main(String[] args)
{
ArrayList list=new ArrayList();
list.add("Bendakaluru");
list.add("Guwahati");
list.add("Bhubaneswar");
list.add("Pune");
System.out.println(list);
list.remove(0);
System.out.println(list);
list.remove("Pune");
System.out.println(list);
list.clear();
System.out.println(list);
}
}
Output:
[Bendakaluru, Guwahati, Bhubaneswar, Pune]
[Guwahati, Bhubaneswar, Pune]
[Guwahati, Bhubaneswar]
[]
Example:
import java.util.ArrayList;
public class Test5
{
public static void main(String[] args)
{
ArrayList list=new ArrayList();
list.add("Manual");
list.add("SQL");
list.add("Java");
list.add("Selenium");
list.add("AJava");
System.out.println(list.remove(0));
System.out.println(list);
System.out.println(list.remove("SQL"));
System.out.println(list);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 158
Output:
Manual
[SQL, Java, Selenium, AJava]
true
[Java, Selenium, AJava]
Example:
import java.util.ArrayList;
public class Test6
{
public static void main(String[] args)
{
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
ArrayList list3 = new ArrayList();
list1.add(10);
list1.add(20);
list1.add(30);
list1.add(40);
list1.add(50);
list2.add(40);
list2.add(50);
list2.add(60);
list2.add(70);
list2.add(80);
list3.add(60);
list3.add(70);
list3.add(80);
list3.add(90);
list3.add(100);
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
list1.removeAll(list2);
System.out.println(list1);
list2.retainAll(list3);
System.out.println(list2);
}
}
Output:
[10, 20, 30, 40, 50]
[40, 50, 60, 70, 80]
[60, 70, 80, 90, 100]
[10, 20, 30]
[60, 70, 80]
Example:
import java.util.ArrayList;
public class Test7 extends ArrayList
{
public static void main(String[] args)
{
Test7 list = new Test7();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
Developer-Tester
Core Java JyothiShankar Mahakul 159
list.add(50);
list.add(60);
list.add(70);
list.add(80);
list.add(90);
list.add(100);
System.out.println(list);
list.removeRange(2, 7);
System.out.println(list);
}
}
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[10, 20, 80, 90, 100]
Example:
import java.util.ArrayList;
import java.util.Collections;
public class Test8
{
public static void main(String[] args)
{
ArrayList list =new ArrayList();
list.add("Encapsulation");
list.add("TypeCasting");
list.add("Abstraction");
list.add("WrapperCLass");
list.add("Collections");
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}
Output:
[Encapsulation, TypeCasting, Abstraction, WrapperCLass, Collections]
[Abstraction, Collections, Encapsulation, TypeCasting, WrapperCLass]
Example:
import java.util.ArrayList;
import java.util.Collections;
public class Test9
{
public static void main(String[] args)
{
ArrayList list =new ArrayList();
list.add("Encapsulation");
list.add("TypeCasting");
list.add("Abstraction");
list.add("WrapperCLass");
list.add("Collections");
System.out.println("Before: " +list);
Collections.sort(list);
System.out.println("After:" +list);
Collections.reverse(list);
System.out.println("reverse of sort:" +list);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 160
Output:
Before: [Encapsulation, TypeCasting, Abstraction, WrapperCLass, Collections]
After:[Abstraction, Collections, Encapsulation, TypeCasting, WrapperCLass]
reverse of sort:[WrapperCLass, TypeCasting, Encapsulation, Collections, Abstraction]
Example:
import java.util.ArrayList;
import java.util.Collections;
public class Test10
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add('E');
list.add('D');
list.add('C');
list.add('B');
list.add('A');
System.out.println(list);
Collections.sort(list);
System.out.println(list);
System.out.println(Collections.binarySearch(list, 'A'));
System.out.println(Collections.binarySearch(list, 'E'));
}
}
Output:
[E, D, C, B, A]
[A, B, C, D, E]
0
4
Example:
import java.util.ArrayList;
import java.util.Collections;
public class Test11
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add("Mango");
list.add("Apple");
list.add("Gauva");
list.add(90);
list.add("Orange");
list.add("Papaya");
Collections.sort(list);
System.out.println(list);
}
}
Output:
java.lang.String cannot be cast to java.lang.Integer
Developer-Tester
Core Java JyothiShankar Mahakul 161
Example:
import java.util.ArrayList;
import annotations.override;
class Z
{
@override
public String toString()
{
return "Z class Object";
}
}
public class Test12
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add(new Z());
list.add(new String("Hello"));
list.add("hi");
list.add(new Integer(10));
list.add(105);
list.add(true);
list.add('A');
for(Object obj:list)
{
System.out.println(obj);
}
}
}
Output:
Z class Object
Hello
hi
10
105
true
A
Example:
import java.util.ArrayList;
public class Test13
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add("Bendakaluru");
list.add("BBSR");
list.add("Magaluru");
list.add("Hyderabad");
String s1=(String) list.get(0);
System.out.println(s1.toUpperCase());
Developer-Tester
Core Java JyothiShankar Mahakul 162
Example:
import java.util.ArrayList;
class Mobile
{
void Message()
{
System.out.println("Message method");
}
}
public class Test14
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add(new Mobile());
list.add(new Mobile());
list.add(new Mobile());
Mobile m1=(Mobile)list.get(0);
m1.Message();
Mobile m2=(Mobile)list.get(1);
m2.Message();
Mobile m3=(Mobile)list.get(2);
m3.Message();
}
}
Output:
Message method
Message method
Message method
b. Queue:
1.To maintain the General Queue, we go for Queue type of collection.
2.Features of Queue are:
a) It is dynamic.
b) We can store heterogeneous element.
c) Queue is not a indexed type of collections i.e., elements will not be stored upon index.
d) Null is not allowed in Queue.
e) Duplicates are allowed in Queue.
f) As Queue is not a indexed type of collection we cannot fetch element using index.
g) We should use 2 methods - peak() & poll()
Queue is a interface inheriting from another interface, Collection.
There are 2 classes implementing queue interface feature
1. Priority Queue.
2. LinkedList.
Developer-Tester
Core Java JyothiShankar Mahakul 163
Example:
import java.util.PriorityQueue;
public class Test1
{
public static void main(String[] args)
{
PriorityQueue queue = new PriorityQueue();
queue.add(50);
queue.add(40);
queue.add(30);
queue.add(20);
queue.add(10);
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
}
}
Output:
[10, 20, 40, 50, 30]
10
[20, 30, 40, 50]
20
[30, 50, 40]
30
[40, 50]
40
[50]
50
Example:
import java.util.PriorityQueue;
public class Test2
{
public static void main(String[] args)
{
PriorityQueue queue = new PriorityQueue();
queue.add(10.5);
queue.add(10.4);
queue.add(10.3);
queue.add(10.2);
queue.add(10.1);
System.out.println(queue);
System.out.println(queue.peek());
System.out.println(queue);
System.out.println(queue.peek());
System.out.println(queue);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 164
Output:
[10.1, 10.2, 10.4, 10.5, 10.3]
10.1
[10.1, 10.2, 10.4, 10.5, 10.3]
10.1
[10.1, 10.2, 10.4, 10.5, 10.3]
Example:
import java.util.PriorityQueue;
public class Test3
{
public static void main(String[] args)
{
PriorityQueue queue = new PriorityQueue();
queue.add('E');
queue.add('D');
queue.add('C');
queue.add('B');
queue.add('A');
int size=queue.size();
for(int i=1;i<=size;i++)
{
System.out.println(queue.poll());
}
}
}
Output:
A
B
C
D
E
Example:
import java.util.PriorityQueue;
public class Test4
{
public static void main(String[] args)
{
PriorityQueue queue = new PriorityQueue();
queue.add("Mango");
queue.add("Mango");
queue.add("70");
queue.add("Mango");
queue.add("$@");
System.out.println(queue);
}
}
Output:
[$@, 70, Mango, Mango, Mango
Developer-Tester
Core Java JyothiShankar Mahakul 165
C. Set:
1. If you want to store the unique element by avoiding duplicate then we should choose set
type of collection.
2. Features of Set:
a) It is dynamic.
b) We can store heterogeneous element.
c) Duplicates are not allowed.
d) It is not a index based collection.
e) Null is allowed.
f) As it is not a index based collection we cannot fetch the elements using index.
Set is a interface inheriting from another interface collection.
There is 3 classes implementing set:
1. HashSet
2. LinkedList
3. TreeSet
Example:
import java.util.HashSet;
public class Test1
{
public static void main(String[] args)
{
HashSet set = new HashSet();
set.add(10);
set.add(10);
set.add(20.5);
set.add(30);
set.add('A');
set.add(10);
set.add(true);
set.add(null);
System.out.println(set.size());
System.out.println(set);
}
}
Output:
6
[null, A, 20.5, 10, 30, true]
Example:
import java.util.LinkedHashSet;
public class Test2
{
public static void main(String[] args)
{
LinkedHashSet set = new LinkedHashSet();
set.add(10);
set.add(10);
set.add(20.5);
set.add('A');
set.add(10);
set.add(true);
set.add(null);
System.out.println(set.size());
System.out.println(set);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 166
Output:
5
[10, 20.5, A, true, null]
Example:
import java.util.TreeSet;
public class Test3
{
public static void main(String[] args)
{
TreeSet set = new TreeSet();
set.add(10);
set.add(30);
set.add(20);
set.add(40);
set.add(10);
set.add(20);
set.add(60);
set.add(50);
System.out.println(set.size());
System.out.println(set);
}
}
Output:
6
[10, 20, 30, 40, 50, 60]
Example:
import java.util.HashSet;
public class Test4
{
public static void main(String[] args)
{
HashSet set = new HashSet();
System.out.println(set.add(10));
System.out.println(set.add(10));
System.out.println(set.add(20.5));
System.out.println(set.add('A'));
System.out.println(set.add(20.5));
System.out.println(set.add("hi"));
System.out.println(set.add(null));
System.out.println(set.add(20.5));
}
}
Output:
true
false
true
true
false
true
true
False
Developer-Tester
Core Java JyothiShankar Mahakul 167
NOTE:
1.If you want to store unique elements then we should choose Set type of Element.
2.If you want to store unique and not expecting any insertion order we should use HashSet .
3.If you want to store unique elements b maintaining insertion order, use LinkedHashset.
4.If you want to store unique elements with auto sorting then choose TreeSet class
5.To store the elements in List, set, Queue we should use add method.
add() will perform 2 Operation:
1- It will store the given element.
2- It will return Boolean value true if it has stored the given element otherwise false.
6. add() return type is Boolean, based on the add() return value we can be notifies about whether the
given element is stored or not.
Example:
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class Test5
{
public static void main(String[] args)
{
HashSet set = new LinkedHashSet();
set.add(10);
set.add(20.5);
set.add('A');
set.add("Hi");
set.add(90);
System.out.println(set);
Iterator itr = set.iterator();
while(itr.hasNext());
{
System.out.println(itr.next());
itr.remove();
}
System.out.println(set);
}
}
Output:
[10, 20.5, A, Hi, 90]
Example:
import java.util.HashSet;
public class Test6
{
public static void main(String[] args)
{
HashSet set = new HashSet();
set.add(10);
set.add(10);
set.add(10);
}
Output:
true
false
true
true
false
Developer-Tester
Core Java JyothiShankar Mahakul 168
true
true
true
6
[null, A, Hi, 20.5, 20.3, 10]
Example:
import java.util.HashSet;
import java.util.Iterator;
public class Test6
{
public static void main(String[] args)
{
HashSet set = new HashSet();
set.add(10);
set.add(10.5);
set.add(true);
set.add(null);
set.add('A');
set.add("hi");
System.out.println(set);
Iterator itr = set.iterator();
while(itr.hasNext());
{
System.out.println(itr.next());
}
System.out.println(set);
Iterator itr2 = set.iterator();
while(itr2.hasNext());
{
System.out.println(itr2.next());
}
System.out.println(set);
}
}
Output:
[null, A, hi, 10.5, 10, true]
NOTE:
1. to fetch the element Set type of collection we should use iterator method.
2. Iterator is a interface, which is having 3 abstract method implemented in some class
a.HashNext();
b.Next();
c.Remove();
a. HashNext():
- It is implemented like a pointer. Initially it will be pointing to first element of set. HashNext()
will return a Boolean Value true if it us pointing to any element, if it is not pointing to any
element i.e., if its pointing to null then it will return a Boolean value null.
- HashNext() return type is Boolean.
b. Next():
Used to fetch the elements.
Next will perform 2 operations
- It will return element which is pointed by HashNext.
- It will increment the HashNext pointer element to Next method.
-Next return type is Object.
Developer-Tester
Core Java JyothiShankar Mahakul 169
c. Remove():
- Used to remove the elements from set while iterating.
- Removes the element which is returned by Next().
- Removes return type is void.
Example:
import java.util.LinkedHashSet;
public class Test7
{
public static void main(String[] args)
{
String rv = "aaabbbccc";
LinkedHashSet set = new LinkedHashSet();
for(int i=0;i<rv.length();i++)
{
set.add(rv.charAt(i));
}
System.out.println(set);
}
}
Output:
[a, b, c]
Example:
import java.util.Iterator;
import java.util.LinkedHashSet;
public class Test8
{
public static void main(String[] args)
{
LinkedHashSet set = new LinkedHashSet();
set.add("Abhay");
set.add("Disha");
set.add("Nisha");
set.add("Jisha");
Iterator itr = set.iterator();
while(itr.hasNext())
{
String s = (String)itr.next();
System.out.println(s.toUpperCase());
}
}
}
Output:
ABHAY
DISHA
NISHA
JISHA
Example:
import java.util.Iterator;
import java.util.TreeSet;
public class Test9
{
public static void main(String[] args)
{
TreeSet set = new TreeSet();
Developer-Tester
Core Java JyothiShankar Mahakul 170
set.add("einsein");
set.add("Dravid");
set.add("Chetak");
set.add("Tata");
System.out.println(set);
Iterator itr = set.iterator();
String s1=(String)itr.next();
System.out.println(s1.toUpperCase());
String s2=(String)itr.next();
System.out.println(s1.length());
String s3=(String)itr.next();
System.out.println(s1.charAt(3));
String s4=(String)itr.next();
System.out.println(s4.indexOf(1));
}
}
Output:
[Chetak, Dravid, Tata, einsein]
CHETAK
6
t
-1
Developer-Tester
Core Java JyothiShankar Mahakul 171
Each of the primitives has a corresponding class that provides several useful abilities that are
otherwise unavailable to a primitive.
Just think wrapper classes as each being a package of useful abilities wrapped around a primitive
of the corresponding type.
Primitive Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Object
Boxing:
Wrapping up the primitive data into an object by using wrapper classes is called as Boxing
Operation.
or
Converting the primitive data into Object by using wrapper class is called as Boxing Operation.
1.The primitive data types are not objects they do not belong to any class, they are defined in
language itself.
2.Sometimes, it is required to convert data types into objects in Java Program.
3.By using operation we can design Generic functions which can receive any input
4.Through Boxing we can convert everything into objects.
5.To achieve boxing operation, there are some Wrapper class provided.
6.All the wrapper classes are concrete, final and immutable.
7.All the wrapper classes are available in java.lang.package.
8.All the 6 number related wrapper class inherits from a class called NUMBER.
9.Number is an abstract class of java.lang.package and Number is a sub class to object class.
10.All the wrapper class provides some functions which performs operation on the related data.
Ex: in character wrapper class there is a static method which will convert the given character value to
upper case.
11. In Integer wrapper class there is a method called parseInt which will convert the Integer value
which in the String form into its Primitive int form.
Ex: int a = Integer.parseInt(100);
Note:
1. All the wrapper class are sub-class to object class.
2. Whenever we print reference variable of Wrapper classes we will get the Boxed data in the String
form.
Developer-Tester
Core Java JyothiShankar Mahakul 172
Example:
public class A
{
public static void main(String[] args)
{
Integer i1=new Integer(10);//Boxing Operation
Double d1=new Double(10);//Boxing Operation
System.out.println(i1);
System.out.println(d1);
}
}
Output:
10
10.0
Example:
public class B
{
public static void main(String[] args)
{
Integer i1=new Integer(10); //Boxing Operation
int a=i1.intValue();//Un-Boxing Operation
System.out.println("value of a is " +a);
Example:
public class C
{
public static void main(String[] args)
{
Integer i1=90; //Auto-Boxing
int i=i1;
System.out.println(i);
Boolean b1=true;//Auto-Boxing
boolean b=b1;//Auto-UnBoxing
System.out.println(b);
}
}
Output:
90
A
true
Developer-Tester
Core Java JyothiShankar Mahakul 173
Example:
class X
{
}
public class D
{
static void fun(Object obj)
{
System.out.println("done");
}
public static void main(String[] args)
{
fun(new A());
fun(new String("Hello"));
fun("hi");
fun(new Integer(10));
fun(90.5);
fun('A');
fun(true);
}
}
Output:
done
done
done
done
done
done
done
Example:
public class E
{
public static void main(String[] args)
{
System.out.println((Integer.toBinaryString(10)));
System.out.println((Character.toUpperCase('a')));
System.out.println((Character.isUpperCase('A')));
System.out.println((Character.isDigit(9)));
System.out.println((Character.isAlphabetic('A')));
}
}
Output:
1010
A
true
false
true
Example:
public class F
{
public static void main(String[] args)
{
int a=Integer.parseInt("100");
System.out.println(a);
System.out.println(a);
String s1="100";
Developer-Tester
Core Java JyothiShankar Mahakul 174
String s2="200";
System.out.println(s1+s2);
int b=Integer.parseInt(s1);
int c=Integer.parseInt(s2);
System.out.println(b+c);
}
}
Output:
100
100
100200
300
UnBoxing:
Getting the boxed data in its primitive form with the help of some value methods of wrapper
classes is called as UnBoxing.
or
Converting the Primitive data which is boxed as an object into its Primitive form by using value
methods of wrapper classes is called as UnBoxing.
To perform the primitive operations on the boxed data we will go for UnBoxing operation.
Note:Both Boxing and UnBoxing is Automatic, which is also called as Auto-Boxing and Auto-UnBoxing.
Ex: Integer rv1=10
Int a=rv1;
Note: Small-talk is 100% OOP language. Java, C++, .net are not 100% OOP language.
Developer-Tester
Core Java JyothiShankar Mahakul 175
Exception are run-time errors some statements will be syntactically correct but behave
abnormally at run time, then we get run-time errors which is called as Exception.
Whenever we get run-time errors, program will stop its execution. In order to continue the
program executions we should handle run-time errors by using try-catch Blocks.
Definition: (Exception)
Whenever any java statement produces an abnormal condition at tun-time, JVM will create any
one of the appropriate Throw-able class type object and it will throe it to the method in which an
abnormal statement is developed, this is called as Exception and handling those exception using
try-catch block is called as Exception Handling.
An exception can occur for many different reasons, including the following:
1. A user has entered invalid data.
2. A file that needs to be opened cannot be found.
3. A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Handling run-time errors using try-catch block is called as Exception Handling.
Risky statement should be developed inside try block and a catch block should be written to
address the exception.
Example:
public class A
{
public static void main(String[] args)
{
try
{
int a=Integer.parseInt("hey");
}
catch (NumberFormatException e)
{
System.out.println("caught");
}
}
}
Output:
caught
Developer-Tester
Core Java JyothiShankar Mahakul 176
Example:
public class B
{
public static void main(String[] args)
{
try
{
int a=10/0;
}
catch(ArithmeticException e)
{
System.out.println("caught");
}
}
}
Output:
caught
Object
Throwable
Error Exception
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric
format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationExcepiton An unsupported operation was encountered.
Developer-Tester
Core Java JyothiShankar Mahakul 177
Exception Description
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Example:
public class C
{
public static void main(String[] args)
{
int[] arr={10,20};
try
{
System.out.println(arr[900]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
900
Exceptions Methods: Following is the list of important methods available in the Throwable class.
Note:
Throw-able class is the super-most class for the Exception related class.
Throw-able class is the concrete class of java.lang.package
Throw-able class is a sub class to object class.
Developer-Tester
Core Java JyothiShankar Mahakul 178
Example:
public class D
{
public static void main(String[] args)
{
int a=10;
int b=0;
try
{
int result=a/b;
System.out.println("the result is " +result);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
/ by zero
Example:
class Z
{
}
public class E
{
public static void main(String[] args)
{
// Z z1= null;
Z z1=new Z();
try
{
System.out.println(z1.hashCode());
}
catch(ArithmeticException e)
{
System.out.println("caught!");
}
finally
{
System.out.println("Runnig Finally block \n");
}
}
}
Output:
366712642
Runnig Finally block
Developer-Tester
Core Java JyothiShankar Mahakul 179
Example:
class Z
{
}
public class E
{
public static void main(String[] args)
{
Z z1= null;
// Z z1=new Z();
try
{
System.out.println(z1.hashCode());
}
catch(ArithmeticException e)
{
System.out.println("caught!");
}
finally
{
System.out.println("Runnig Finally block \n");
}
}
}
Output:
Runnig Finally block
Exception in thread "main"
java.lang.NullPointerException
Example:
public class F
{
public static void main(String[] args)
{
try
{
int a=10/0;
}
catch(NumberFormatException e)
{
System.out.println("Runnig 1st catch");
}
catch(ArithmeticException e)
{
System.out.println("Running 2nd catch");
}
}
}
Output:
Running 2nd catch
Note:
1 try block can be followed by multiple catch block but only appropriate catch block will be executed.
Developer-Tester
Core Java JyothiShankar Mahakul 180
Example:
public class G
{
public static void main(String[] args)
{
int[] arr1={10,20,30,40,50,60,70,80};
int[] arr2={10,0,30,0,50};
for(int i=0;i<arr1.length;i++)
{
try
{
System.out.println(arr1[i]/arr2[i]);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("No such index");
}
}
}
}
Output:
1
/ by zero
1
/ by zero
1
No such index
No such index
No such index
Example:
public class H
{
public static void main(String[] args)
{
try
{
int[] arr=new int[-10];
}
catch(Throwable e)
{
System.out.println(e.getMessage());
System.out.println("Caught");
}
}
}
Output:
null
Caught
Note: Though throw-able catch block can handle any type of exception we should not use throw-able
catch block alone i.e., while handling exceptions we should follow an order while writing catch block.
We should write the catch block from most specific exception class to most Generic Exception class.
Developer-Tester
Core Java JyothiShankar Mahakul 181
Example:
public class I
{
public static void main(String[] args)
{
try
{
int a =10/0;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
System.out.println("1st caught");
}
catch(RuntimeException e)
{
System.out.println(e.getMessage());
System.out.println("2nd caught");
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.out.println("2nd caught");
}
catch(Throwable e)
{
System.out.println(e.getMessage());
System.out.println("2nd caught");
}
}
}
Output:
/ by zero
1st caught
2. Checked Exceptions:
Checked Exceptions will be detected by compiler. All the sub-classes which are sub class to all
the exceptions class will fall under Checked Exceptions category.
Ex: IOException, fFleNotFoundException, InterupptedException.
Here compiler can identify that certain statements might generate a abnormal condition at
run-time.
If Compiler identifies any checked Exceptions, then programmer should handle it,
There are 2 ways to handle checked Exceptions,
A. try-catch block
B. Using throws keyword.
Developer-Tester
Core Java JyothiShankar Mahakul 182
Example:
class M
{
public static void test() throws Exception
{
int i=10/0;
}
}
public class L
{
public static void main(String[] args)
{
M m1=new M();
try
{
m1.test();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Note: When a method of 1 class is used in another class without inheritance then we need to
surround the method with try catch block.
Throws helps us to take up the memory address of the object and gives it to catch.
Developer-Tester
Core Java JyothiShankar Mahakul 183
Example:
import java.io.File;
public class A
{
public static void main(String[] args)
{
File f1=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
if(f1.mkdir())
{
System.out.println("File is created");
}
else
{
System.out.println("file not created");
}
if(f1.exists())
{
System.out.println("File exists");
}
else
{
System.out.println("file not exists");
}
if(f1.delete())
{
System.out.println("file deleted");
}
else
{
System.out.println(("file not deleted"));
}
}
}
Output:
file not created
File exists
file deleted
Example:
import java.io.*;
public class B
{
public static void main(String[] args)
{
File f1=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
try
{
if(f1.createNewFile())
{
System.out.println("file is created");
}
else
{
System.out.println("File is not created");
Developer-Tester
Core Java JyothiShankar Mahakul 184
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
File is not created
Example:
public class C
{
public static void main(String[] args)
{
File f1=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
try
{
if(f1.createNewFile())
{
System.out.println("File created");
}
else
{
System.out.println("File not created, bcz it exists");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
File not created, bcz it exists
Example:
import java.io.FileWriter;
import java.io.IOException;
public class D
{
public static void main(String[] args)
{
try
{
FileWriter fw=new FileWriter("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
fw.write("Hello World, Hope you are fine");
fw.flush();
fw.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 185
Output:
Hello World, Hope you are fine
Example:
import java.io.*;
public class E
{
public static void main(String[] args)
{
File f1=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
try
{
FileReader fr=new FileReader(f1);
char t[] = new char[(int)f1.length()];
fr.read(t);
String rv=new String(t);
System.out.println(rv);
System.out.println(rv.toUpperCase());
fr.close();
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
Hello World, Hope you are fine
HELLO WORLD, HOPE YOU ARE FINE
Example:
import java.io.*;
public class F
{
public static void main(String[] args)
{
File f=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
try
{
FileWriter fw=new FileWriter(f);
fw.write("ABCD");
fw.close();
System.out.println("Writing Done!");
Developer-Tester
Core Java JyothiShankar Mahakul 186
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Output:
Writing Done!0
ABCD
Example:
public class G
{
public static void main(String[] args)
{
try
{
FileWriter fw=new FileWriter("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
fw.write("XYZ");
fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Output:
Example:
import java.io.FileWriter;
import java.io.IOException;
public class H
{
public static void main(String[] args)
{
try
{
FileWriter fw = new FileWriter("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
fw.write( );
fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Output:
The method write(int) in the type OutputStreamWriter is not applicable for the arguments ()
Example:
public class I
{
public static void main(String[] args)
{
Developer-Tester
Core Java JyothiShankar Mahakul 187
try
{
FileWriter fw=new FileWriter("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
fw.write("hello");
fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Output:
hello
Throws
Throws is a keyword which is used to re-throw the already existing generated exception to the other
methods.
or
Throws is a keyword which is used to delegate the exception to other methods.
1. Throw keyword should be used at the method invocation
2. Using throw keyword we can throw multiple exception.
3. To notify the uses of function or method about the run-time error the method generation for
invalid value we can use throws keyword.
Example:
public class J
{
public static void main(String[] args)
{
try
{
int a[] = new int[999999999];
}
catch(OutOfMemoryError e)
{
System.out.println("caught");
}
}
}
Output:
caught
What is the differences between exception class and error class of throw-able hierarchy?
Whenever there is a problem with external resources we get run-time error which are sub-class
to error class.
Whenever there is a problem in the Java statement (some logical problems) there we get
run-time error which are sub-class to exception class or run-time exception.
Developer-Tester
Core Java JyothiShankar Mahakul 188
Example:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class K
{
public static void main(String[] args) throws Exception
{
File f1=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
FileWriter fw = new FileWriter(f1);
BufferedWriter bw=new BufferedWriter(fw);
String[] ref={"Dog","cat","sheep","cow"};
for(int i=0;i<ref.length;i++)
{
bw.write(ref[i]);
bw.newLine();
}
bw.close();
}
System.out.println("Writing done");
}
Output:
Writing done
Example:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class L
{
public static void main(String[] args) throws Exception
{
File f=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String s=br.readLine();
{
while(s!=null)
{
System.out.println(s);
s=br.readLine();
}
br.close();
}
}
}
Output:
Dog
cat
sheep
Cow
Developer-Tester
Core Java JyothiShankar Mahakul 189
Example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class M
{
public static void main(String[] args) throws IOException
{
File f=new File("C:\\Users\\JYOTHISHANKAR\\Desktop\\Testing.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
//ArrayList<String>list =new ArrayList<String>
ArrayList<String> list = new ArrayList<String>();
String s=br.readLine();
while(s!=null)
{
list.add(s);
s=br.readLine();
}
Collections.sort(list);
FileWriter fw=new FileWriter(f);
BufferedWriter bw=new BufferedWriter(fw);
for(int i=0;i<list.size();i++)
{
bw.write(list.get(i));
bw.newLine();
}
br.close();
br.close();
System.out.println("file Updated");
}
}
Output:
file Updated
Developer-Tester
Core Java JyothiShankar Mahakul 190
fout.close();.
System.out.println("writing done");
}
}
Output:
writing done
Example:
import java.io.IOException;
import java.util.Scanner;
public class O
{
public static void main(String[] args) throws IOException
{
String pwd="Qspiders";
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter one number");
int a = scan.nextInt();
System.out.println("Please Enter another number");
int b=scan.nextInt();
System.out.println("Please enter password for result");
String s=scan.nextLine();
if(pwd.equals(s))
{
int sum=a+b;
System.out.println("result is" +sum);
}
else
{
System.out.println("sorry incorrect password");
}
scan.close();
}
}
Output:
Example:
import java.io.IOException;
import java.util.Scanner;
public class P
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter one string");
String s1=scan.nextLine();
System.out.println("please enter one word");
String s2=scan.next();
System.out.println("enter you replacement word");
String s3=scan.next();
s1=s1.replaceAll(s1, s3);
System.out.println(s1);
scan.close();
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 191
Output:
Please enter one string
hi, hope you doing Good
please enter one word
Good
enter you replacement word
bad
bad
Example:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class R
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter the size of Array");
int size=scan.nextInt();
double[] darr = new double[7];
System.out.println("please Enter " +size+ "elements");
for(int i=0;i<size;i++)
{
darr[i]=scan.nextDouble();
}
System.out.println("The" +size+ "elements are");
for(int i=0;i<size;i++)
{
System.out.println(darr[i]);
}
System.out.println("Sort?? Yes or No");
String opt=scan.next();
if(opt.equalsIgnoreCase("yes"))
{
Arrays.sort(darr);
for(int i=0;i<size;i++)
{
System.out.println(darr[i]);
}
}
else
{
System.out.println("Thank you");
}
scan.close();
}
}
Output:
Please Enter the size of Array
4
please Enter 4elements
1
3
5
7
Developer-Tester
Core Java JyothiShankar Mahakul 192
The4elements are
1.0
3.0
5.0
7.0
Sort?? Yes or No
yes
0.0
0.0
0.0
1.0
Example:
public class Bank
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
Bank rv=new Bank();
int opt;
do
{
System.out.println("1: balance\t 2: Deposit");
System.out.println("3:WithDraw\t 4: Exit");
System.out.println("What's your option?");
opt=scan.nextInt();
switch(opt)
{
case 1 : rv.balance();
System.out.println();
rv.balance();
break;
case 2: System.out.println("Please Enter deposit amount");
int damount=scan.nextInt();
rv.deposit(damount);
break;
case 3: System.out.println("please enter the withdraw amount");
int wamount =scan.nextInt();
rv.withdraw(wamount);
break;
case 4: System.out.println("Thank You");
break;
default:System.out.println("invalid option");
}
}
while(opt!=4);
{
scan.close();
}
}
private void withdraw(int wamount)
{
}
private void deposit(int damount)
{
Developer-Tester
Core Java JyothiShankar Mahakul 193
}
private void balance()
{
}
}
Output:
1: balance 2: Deposit
3:WithDraw 4: Exit
What's your option?
Example:
public class S
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("Please Enter one number");
int a= scan.nextInt();
System.out.println("please enter another number");
int b=scan.nextInt();
if(a>=b)
{
System.out.println("The result is " +(a-b));
}
else
{
throw new ArithmeticException("first No. should be greater than second no.");
}
}
}
Output:
Please Enter one number
5
please enter another number
5
The result is 0
Developer-Tester
Core Java JyothiShankar Mahakul 194
Garbage collection is a process of removing the abandoned objects from the heap memory.
Abandoned object means the object without any references.
The abandoned object will be removed from the heap memory by using finalize() of that abandoned
object by garbage collection.
Garbage Collector is a thread which will be always running in the background.
Garbage Collector is a daemon thread, which will execute whenever the system is free.
Daemon thread means lowest priority thread.
We can predict when exactly an object is eligible for garbage collection.
We cannot predict when exactly garbage collections happens.
While developing the program if you wanted to perform garbage collection then we can use
System.gc();
Example:
class Z
{
@override
protected void finalize() throws Throwable
{
System.out.println("running finding method");
super.finalize();
}
}
public class T
{
public static void main(String[] args)
{
Z z1=new Z();
z1=new Z();
System.gc();
}
}
Output:
running finding method
Example:
class D
{ int i; }
class C
{
void test1()
{
System.out.println("non-static method");
}
}
public class B
{
public static void main(String[] args)
{
System.out.println(new D().i);
new C().test1();
System.out.println(new String("qspiders").toUpperCase());
System.out.println("Jspiders".length());
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 195
Output:
0
non-static method
QSPIDERS
8
Example:
class Sample
{
static String test()
{
return "java Programming";
}
}
class Demo
{
public String test2()
{
return "selenium";
}
}
public class Z
{
public static void main(String[] args)
{
System.out.println(Sample.test().length());
System.out.println(new Demo().test2().length());
}
}
Output:
16
8
Developer-Tester
Core Java JyothiShankar Mahakul 196
Final:
1. Is a keyword.
2. If you want to declare constant variables where in the value cannot change, then those variable
should be declared with the keyword final.
3. Final variable value cannot be changed or overridden.
4. Both local and global variable can be final.
5. Global final variable should be initialized at the time of initialization itself.
6. Local final variable can be declared once and initialized later.
7. In terms of inheritance, final keyword us used to avoid overriding.
8. Final class cannot be inherited.
9. Final class methods cannot be overridden because for method overriding inheritance is
mandatory.
Example:
public class A
{
public static void main(String[] args)
{
final int i=10;
i=20;
System.out.println(i);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final local variable i cannot be assigned. It must be blank and not using a compound
assignment
Note: If you make a variable has final then we can never re-initialize that variable.
Example:
public class B
{
public static void main(String[] args)
{
final int i=10;
i=10;//error
System.out.println(i);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final local variable i cannot be assigned. It must be blank and not using a compound
assignment
Note:
Static and non-static variable if made Final then ts initialization is mandatory or else we will get blank
field error.
Developer-Tester
Core Java JyothiShankar Mahakul 197
Example:
{
final int i;//error because not initialized
public static void main(String[] args)
{
final int j;//local variables should be initialized before usage
System.out.println(j);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable j may not have been initialized
Note:
In case of local variable make it final there is no error, but using it without initialization will throw
error.
Example:
public class D
{
final static int i;
public static void main(String[] args)
{
final int j;
System.out.println(j);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable j may not have been initialized
Note: In final, copying value of variable is possible. Final keyword make the size fixed i.e., cannot be
altered.
Example:
public class E
{
public void test(final int i)
{
i=30;//The final local variable i cannot be assigned. It must be blank and not using a
compound assignment
System.out.println(i);
}
public static void main(String[] args)
{
E e1=new E();
e1.test(10);
}
}
Output:
The final local variable i cannot be assigned. It must be blank and not using a compound assignment
Developer-Tester
Core Java JyothiShankar Mahakul 198
Note: If you make an array as final then its size cannot be altered.
Example:
public class F
{
public static void main(String[] args)
{
final int[] a=new int[5];
a[0]=10;
a[0]=20;
System.out.println(a[0]); //20
}
}
Output:
20
Example:
public class G
{
public static void main(String[] args)
{
final int[] a=new int[5];
a=new int[2];
}
}
Output:
The final local variable a cannot be assigned. It must be blank and not using a compound assignment
Note:
1. When array is final, its size cannot be changed.
2. When array is not final, then size can be altered.
3. When (String[] args) is final, then its size cannot be altered.
4. args[] is a take string no number allowed
Example:
public class H
{
public static void main(String[] args)
{
args=new String[3];
args[0]="10";
System.out.println(args[0]);
}
}
Output:
10
Note:
1. Inheritance of final class is not possible.
2. Final Variable value cannot be altered.
3. Final Array size cannot be altered, but value can be altered.
4. Final Class, inheritance is not possible and value cannot be inherited.
Developer-Tester
Core Java JyothiShankar Mahakul 199
Example:
final class J
{
int i=10;
}
final class I extends J// the type I cannot sub class to final
{
public static void main(String[] args)
{
J j1=new J();
System.out.println(j1.i);
}
}
Output:
Unresolved compilation problem
the type I cannot sub class to final
Developer-Tester
Core Java JyothiShankar Mahakul 200
Note:
1. For overriding access specifier can be different, but return type should be same.
2. When you make a method final and not use void then you get Error.
Example:
public class W extends X
{
public int test()//not a void method when declared test(), so error.
{
System.out.println("");
return 30;
}
public static void main(String[] args)
{
W w1=new W();
w1.test();
}
}
Output:
Cannot override the final method from X
Finally:
Finally is a block which will be used in Exception Handling.
Finally block will be executed irrespective of Exception.
To execute certain mandatory statement without fail we will use Finally block.
Closing the connection established between database and file system of the computer will be
done in finally block, so in any scenario connection will be closed.
Finalize():
Finalize is a non-static method in object class which will be used for garbage collection by
garbage collections thread.
Whenever we use System.exit() statement, then finally block will not execute.
Developer-Tester
Core Java JyothiShankar Mahakul 201
1. Multi-Processing:
Executing multiple processes simultaneously is called as Multi-processing.
Executing multiple application simultaneously is called Multi-processing.
Here 3-4 milli second of processor time will be shared between multiple
application.
2. Multi-Threading:
Dividing an application into multiple parts and allocating the separate processor time and
memory for each part of the same application is called as Multi-Threading.
THREAD
Thread is a execution instance which will have its own processor time and memory.
Whenever a core java program is executed 3 threads will be created automatically, they are:
1. Main Thread.
2. Thread Scheduler.
3. Garbage Collection.
1. Main Thread:
Main thread responsibility is to execute main method of program.
Main method is different and main thread is different.
Main method is foreground process.
2. Thread Scheduler:
Thread Scheduler responsibility is to perform Thread registration.
Thread registration means allocating the separate processor time and memory for the
thread.
3. Garbage Collector:
GC responsibility is to perform Garbage collection and it is a lowest priority background
thread.
In java, there is a built-in class called Thread, it is a sub class to Object class.
Example:
package Multithreading;
public class Tester1
{
public static void main(String[] args)
{
System.out.println("Main Starts");
try
{
Thread.sleep(20000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Main Ends");
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 202
Output:
Main Starts
Main Ends
---------------------------------------------------------------------------
Example:
\public class Tester2
{
public static void main(String[] args) throws InterruptedException
{
System.out.println("Main Starts");
for(int i=1;i<=5;i++)
{
System.out.println(i);
Thread.sleep(1000);
}
System.out.println("Main Ends");
}
}
Output:
Main Starts
1
2
3
4
5
Main Ends
---------------------------------------------------------------------------
Example:
public class Tester3
{
public static void main(String[] args)
{
Thread t1=Thread.currentThread();
System.out.println("Name:" +t1.getName());
System.out.println("Id:" +t1.getId());
System.out.println("Priority:" +t1.getPriority());
t1.setName("initiator");
t1.setPriority(10);
System.out.println("Name" +t1.getName());
System.out.println("Id:" +t1.getId());
System.out.println("Priority:" +t1.getPriority());
}
}
Output:
Name:main
Id:1
Priority:5
Nameinitiator
Id:1
Priority:10
---------------------------------------------------------------------------
Developer-Tester
Core Java JyothiShankar Mahakul 203
Example:
public class Tester4
{
public static void main(String[] args)
{
Thread t1=Thread.currentThread();
t1.setName("Initiator");
for(int i=1;i<4;i++)
{
System.out.println(t1.getName()+"::" +i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Output:
Initiator::1
Initiator::2
Initiator::3
---------------------------------------------------------------------------
Note:
1. Thread is a concrete class of java.lang package.
2. Thread class have a lot of static and non-static method through which we can work with Thread.
3. Thread class is a sub class to object class.
4. Thread class have 2 important static method,
a) Sleep():
b) currentThread():
a)sleep():
sleep is a static method of thread class which will receive millisec as input in long form.
Whenever sleep() is called on any thread, that particular thread will stop its execution for
supplied millisec.
Usage: Thread.sleep(1000); Here, 1000 millisec means 1 sec.
sleep() will throw a checked exception, so whenever we are using thread.sleep() we should
handle it at compile time itself either through try-catch or throws keyword.
b)currentThread():
It is a static method of thread class.
Whenever currentThread class is used on any thread it will give the object of thread on which
it is called.
Using the object returned by currentThread we can explore the property o any Thread.
Usage: Thread t1=Thread.currentThread();
1. Name
2. Id
3. Priority
Developer-Tester
Core Java JyothiShankar Mahakul 204
1. Name:
Any thread will have name.
Main threads name is Main itself.
For user threads, the name will be thread(0), thread(1), thread(2) etc.,
Any threads name can be changed.
2. Id:
Id is a unique long number which cannot be duplicated.
Id will be used to identify a thread uniquely among the group of threads.
3. Priority:
Any thread will have priority between 1 to 10.
The default priority of all thread will be 5.
The priority of thread can be changed.
---------------------------------------------------------------------------
Example:
package Multithreading;
class A extends Thread
{
@Override
public void run()
{
Thread t1=Thread.currentThread();
for(int i=1;i<=5;i++)
{
System.out.println(t1.getName()+ "::" +i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class B extends Thread
{
@Override
public void run()
{
Thread t1=Thread.currentThread();
for(int i=1;i<=5;i++)
{
System.out.println(t1.getName()+ "::" +i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 205
Example:
public class Tester6
{
public static void main(String[] args)
{
EvenNumber a1=new EvenNumber();
a1.setName("even no");
a1.start();
OddNumber b1=new OddNumber();
b1.setName("Odd number");
b1.start();
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 206
Developer-Tester
Core Java JyothiShankar Mahakul 207
Note:
1. Thread class is having 2 important non-static methods. They are:
start();
run();
2. Whenever any class extends Thread class then that class will inherit both start and run method.
3. We should override the inherited run method.
4. The task which has to be executed by the thread should be developed in the run method while
overriding.
5. We should always call the start method to initiate the thread.
6. Start() will perform 2 operations.
a)Operation 1: It will perform Thread registration through Thread Scheduler.
b)Operation 2: It will call the overridden run method.
Thread Synchronization
Whenever multiple threads will execute the same method or resources then data corruption
happen, so we should perform Thread Synchronization.
To perform thread synchronization, the method should be declared with the keyword
Synchronize.
Synchronize method cannot be executed by multiple threads simultaneously.
Synchronized methods are also called as Thread Safe methods.
Example: If 2 threads are using the same transfer function and function is not synchronized then data
corruption might happen on balance data.
Example: Vector class of collection is called Thread safe because all the method of vector class is
Synchronized. i.e., if any thread is using add() on vector object another thread cannot remove the
data simultaneously.
Note: All the synchronized method in eclipse will have a lock method.
Note:
1.Every object in java will have one object lock and only one lock per object.
2.Object lock is related to threads.
3.If nay threads need to execute synchronized methods then it should have object lock.
4.After completely executing synchronized method, the thread will release the object lock. So
synchronized method cannot be executed by multiple threads together.
Example:
A.class
package ThreadSync;
public class A
{
synchronized void test1()
{
Thread t1=new Thread().currentThread();
System.out.println(t1.getName() +"Started test1");
for(int i=1;i<=5;i++)
{
System.out.println(t1.getName() +"::" +i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
Developer-Tester
Core Java JyothiShankar Mahakul 208
Developer-Tester
Core Java JyothiShankar Mahakul 209
B Thread::4
B Threadcompleted test1
B Thread::5
B Threadcompleted test1
C ThreadStarted test1
C Thread::1
C Threadcompleted test1
C Thread::2
C Threadcompleted test1
C Thread::3
C Threadcompleted test1
C Thread::4
C Threadcompleted test1
C Thread::5
C Threadcompleted test1
Developer-Tester
Core Java JyothiShankar Mahakul 210
34. GENERICS
Output:
10
Note:
Generic changes according to the situation.
X can take any alphabet.
Instead of X, any alphabet can be used.
Definition:
A Generic class helps us to create a variable such that any kind of value can be stored in the
variable, because the data type of variable is decided based on the kind of value is stored in the
variable.
Example:
public class C<Z>
{
Z i;
@SuppressWarnings("rawtypes")
public static void main(String[] args)
{
C c1=new C();
c1.i=10.3f;
c1.i=20;
c1.i=30;
System.out.println(c1.i);
}
}
Developer-Tester
Core Java JyothiShankar Mahakul 211
Output:
30
Output:
10
20.3
30.3
Example:
public class F<X>
{
X i;
X j;
X k;
public static void main(String[] args)
{
F f1=new F();
f1.i=30;
f1.j=40.4;
f1.k=50.5f;
System.out.println(f1.i);
System.out.println(f1.j);
System.out.println(f1.k);
}
}
Output:
30
40.4
50.5
Note:
If a method is made a Generic then it will get potential to retuern any kind of value.
When a normal data type is replaced by generic data type, then it can retuen value.
Developer-Tester
Core Java JyothiShankar Mahakul 212
Example:
public class E<X>
{
X i;//generic cannot be applied on local variable
E e1;
public X test()
{
e1=new E();
e1.i=60.6f;
return i;
}
public static void main(String[] args)
{
E e2=new E();
e2.test();
System.out.println("" +e2.i);
System.out.println("" +e2.test());
}
}
Output:
null
null
Note:
1) Generic cannot be applied on local variable.
2) Generic cannot be applied on static variables but can be applied to non-static variable
Example:
public class G<X>
{
X i;
X j;
X k;
public static X test() //Cannot be static
{
g1=new G();
g1.i=90.9f;
return i;//cannot make reference to the non-static field i
}
public static void main(String[] args)
{
G g2=new G();
g2.test();
System.out.println(g1.i);
}
}
Output:
Developer-Tester
Core Java JyothiShankar Mahakul 213
Example:
public class A
{
class B
{
int i=0;
}
public static void main(String[] args)
{
B b1=new B();
System.out.println(b1.i);
}
}
Output:
No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of
type A (e.g. x.new A() where x is an instance of A).
Example:
public class B
{
class C
{
int i=10;
}
public static void main(String[] args)
{
B b1=new B();
C c1=b1.new C();
System.out.println(c1.i);
}
}
Output:
10
Developer-Tester
Core Java JyothiShankar Mahakul 214
Example:
public class C
{
class D
{
public void test()
{
System.out.println("from test");
}
}
public static void main(String[] args)
{
C c1=new C();
D d1=c1.new D();
d1.test();
}
}
Output:
from test
Note:
1.We cannot create static local member in an Inner class.
2. Inner class should only have non-static method.
Example:
public class D
{
class E
{
static int i=10;// The field i cannot be declared static in a non-static inner type, unleass
initialized with a constant expression
public static void test()
{
System.out.println("From test()");
}
}
public static void main(String[] args)
{
D d1=new D();
E e1=d1.new E();
System.out.println(e1.i);//The static field D.E.i should be accessed in a Static way
}
}
Output:
The field i cannot be declared static in a non-static inner type, unless initialized with a constant
expression
The method test cannot be declared static; static methods can only be declared in a static or top
level type
Developer-Tester
Core Java JyothiShankar Mahakul 215
Example:
public class E
{
int j=20;
class F
{
int i=10;
}
public static void main(String[] args)
{
E e1=new E();
F f1=e1.new F();
System.out.println(f1.i);
System.out.println(f1.j);// By creating an object of local inner class we cannot access the
members of outer class
}
}
Output:
j cannot be resolved or is not a field
Note:
By creating an object of local inner class we cannot access the members of outer class
Example:
public class F
{
class G
{
G()
{
System.out.println("from G");
}
}
public static void main(String[] args)
{
F f1=new F();
f1.new G(); // or G g1=f1.new G();
}
}
Output:
from G
Note:
We can create a constructor inside a local inner class.
Example:
public class G
{
static int i=10;
class H extends G
{
static int j=20;
static int i=20;
}
public static void main(String[] args)
{
G g1=new G();
H h1=g1.new H();
Developer-Tester
Core Java JyothiShankar Mahakul 216
System.out.println(h1.i);
}
}
Output:
The field j cannot be declared static in a non-static inner type, unless initialized with a constant
expression
The field i cannot be declared static in a non-static inner type, unless initialized with a constant
expression
Note:
Static members of outer class can be inherited into local inner class but then static members cannot
be created in local inner class.
Example:
public class H
{
class I
{
int i=10;
}
class J
{
int j=20;
}
public static void main(String[] args)
{
H h1=new H();
I i1=h1.new I();
System.out.println(i1.i);
J j1=h1.new J();
System.out.println(j1.j);
}
}
Output:
10
20
Note:
We can create more than 1 local inner class inside a same class.
When we compile the inner class program we will get class as follows,
A$B.class
A$C.class
A.class
But the above program will be saved as a single java file.
Developer-Tester
Core Java JyothiShankar Mahakul 217
Rule 1:
Inheritance between two inner class is possible
Example:
public class I
{
class J
{
int i=20;
}
class K extends J
{
int j=40;
}
public static void main(String[] args)
{
I i1=ne K();
System.outw I();
K k1=i1.new.println(k1.i);
System.out.println(k1.j);
}
}
Output:
20
40
Example:
public class J
{
class K
{
{
System.out.println("from IIB"); //Called first
}
K()
{
System.out.println("constructor");
}
}
public static void main(String[] args)
{
J j1=new J();
j1.new K();//K k1=j1.new K();
}
}
Output:
from IIB
constructor
Note:
When IIB and constructor are both together then upon object creation IIB will be called first and then
constructor.
Note:
When a instance variable is created make sure declaration is outside if you create a variable inside IIB
then it becomes local variable.
Anything created within braces are local, but outside braces and within class is instance variables.
Developer-Tester
Core Java JyothiShankar Mahakul 218
Example:
public class K
{
class L
{
int i;
{
int j=20;
System.out.println("from IIB");
}
L()
{
System.out.println("from constructor");
}
}
public static void main(String[] args)
{
K k1=new K();
L l1=k1.new L();
System.out.println(l1.i);
}
}
Output:
from IIB
from constructor
0
Note:
IIB can be created inside local inner class
Rule 2:
Incomplete methods in interface should be completed in class by inheriting and overriding.
Example:
public interface AA
{
public void test();
}
public class L
{
class M implements AA
{
public void test()
{
System.out.println("from test()");
}
}
public static void main(String[] args)
{
L l1=new L();
M m1=l1.new M();
m1.test();
}
}
Output:
from test()
Class M can extend member of class L.
Class M can implement member of interface AA.
Developer-Tester
Core Java JyothiShankar Mahakul 219
Note:
1. Only IIB can be created in Inner class.
Note:
1. In comparison to Local Inner class, in static Inner class both static and non-static can be created.
2. To access the members(because they are static) you can directly create the object of the static
class.
Ex: System.out.println(B.i);
System.out.println(b1.j);
3. In this class we can have both static and non-static members.
Example:
public class A
{
static class B
{
static int i;
int j=20;
}
public static void main(String[] args)
{
B b1=new B();
System.out.println(B.i);//SIB
System.out.println(b1.j);//IIB
}
}
Output:
0
20
Note:
Inside static class we can create SIB, IIB, constructor.
Example:
public class C
{
static class D
{
static
{
System.out.println("SIB");
}
D()
{
System.out.println("constructor");
}
{
Developer-Tester
Core Java JyothiShankar Mahakul 220
System.out.println("IIB");
}
public static void main(String[] args)
{
D d1=new D();
}
}
}
Output:
SIB
IIB
Constructor
Note:
Inheriting member of outer class to static Inner class.
Example:
public class E
{
int i=10;
static class F extends E
{
}
public static void main(String[] args)
{
F f1=new F();
System.out.println(f1.i);
}
}
Output:
10
Note: We cannot create object of static Inner class and access the members of outer class without
inheritance.
Example:
public class G
{
int i=100;
static class H //extends G
{
}
public static void main(String[] args)
{
H h1=new H();
System.out.println(h1.i);
}
}
Output:
i cannot be resolved or is not a field
Developer-Tester
Core Java JyothiShankar Mahakul 221
Developer-Tester
Core Java JyothiShankar Mahakul 222
Note: Creating the object of Static Inner class cannot access the members of Outer class.
Example:
public class O
{
int i=10;
static class P
{
int j=20;
}
public static void main(String[] args)
{
P p1=new P();
System.out.println(p1.i);//Object of inner class cannot access the member of Outer class
}
}
Output:
i cannot be resolved or is not a field
Note: Inheriting local Inner class members into static Inner class is not possible.
Example:
public class S
{
class T
{
int i=100;
}
static class U extends T
{
}
public static void main(String[] args)
{
U u1=new U();
System.out.println(u1.i);
}
}
Output:
No enclosing instance of type S is available due to some intermediate constructor invocation.
Developer-Tester
Core Java JyothiShankar Mahakul 223
Note: Inheriting static Inner class members into Local Inner class is possible.
Example:
public class V
{
static class W
{
static int j=60;
int i=70;
}
class X extends W
{
}
public static void main(String[] args) {
V v1=new V();
X x1=v1.new X();
System.out.println(x1.i);
System.out.println(X.j);//X will be converted to W, because conversion takes place
}
}
Output:
70
60
Differences:
Static Inner Class Local Inner Class
1. Can consist all the members 1. Can consists of only non-static members
2. Directly create the Object then access the 2. Create Object of Outer class, take its reference
members. then access Inner class.
Example:
public class Y
{
static class Z
{
int j=10;
public static void main(String[] args)
{
int i=100;
System.out.println(i);
}
}
public static void main(String[] args)
{
Z z1=new Z();
System.out.println(z1.j);//calling statement
Z.main(null);
}
}
Output:
100
Developer-Tester
Core Java JyothiShankar Mahakul 224
Note:
1. When the class has name use implement.
2. When the class dies not have name, the syntax of implements will be new B(){ };
(this class implements interface)
Example:
public class A
{
public static void main(String[] args)
{
AA b1=new AA(){
public void test()
{
System.out.println("from B");
}
};
b1.test();
}
}
Output:
from B
Example:
public class B
{
public void test1()
{
System.out.println("from B");
}
}
public class C
{
public static void main(String[] args)
{
B b1=new B(){//Anonymous class extends B
public void test()
{
System.out.println("from B");
}
};
b1.test1();
}
}
Output:
from B
Developer-Tester
Core Java JyothiShankar Mahakul 225
Note:
1. In class, inherit complete method and overriding complete method.
2. In interface, inherit incomplete method and override with complete method
Note:
1. Anonymous class automatically inherits the members of the object before it.
2. new()(member of the object will be created and inherited).
3. Anonymous class actually works on the principle of Inheritance.
Example:
class D
{
public void test()
{
System.out.println("from test()");
}
}
public class E
{
public static void main(String[] args)
{
D d1=new D(){
};
d1.test();
}
}
Output:
from test()
Note: Anonymous class is capable of inheriting members and then only make it accessible.
Example:
public class F
{
class G
{
int i=10;
}
public static void main(String[] args)
{
F f1=new F();//creating object of F class
G g1=f1.new G(){
};
System.out.println(g1.i);
}
}
Output:
10
Developer-Tester
Core Java JyothiShankar Mahakul 226
Note:
1. Anonymous class can inherit members of any other class.
2. Anonymous class can inherit interfaces.
3. Anonymous class can inherit local inner class.
4. Anonymous class can inherit static Inner class.
5. But cannot inherit members of Outer class.
Example:
public class H
{
static class I
{
public void test()
{
System.out.println("test-B");
}
}
public static void main(String[] args)
{
I i1=new I(){
public void test()
{
System.out.println("test-anonymous");
}
};
i1.test();
}
}
Output:
test-anonymous
Developer-Tester
Core Java JyothiShankar Mahakul 227
Developer-Tester
Core Java JyothiShankar Mahakul 228
Output:
Output:
the number is 121 is palindrome
Developer-Tester
Core Java JyothiShankar Mahakul 229
Example:
class Adam
{
static int reverse(int num)
{
int res=0;
while(num!=0)
{
int temp=num%10;
res=temp+(res*10);
num=num/10;
}
return res;
}
static int square(int num)
{
int res;
res=num*num;
return res;
}
public static void checkAdam(int num,int res)
{
if(num==res)
{
System.out.println("the number is Adam");
}
else
{
System.out.println("The number is not Adam");
}
}
public static void main(String[] args)
{
int num=12;
System.out.println("the no is " +num);
int num1=Adam.square(num);
int res1=Adam.reverse(num);
int num2=Adam.square((res1));
int res2=Adam.reverse(num2);
Adam.checkAdam(num1, num2);
}
}
Output:
the no is 12
The number is not Adam
the no is 121
the number is Adam
Developer-Tester