Comprehensive Java Course Notes
Comprehensive Java Course Notes
udaypawar037@[Link] 1
Java Course Content (50-55 Sessions)
1. Variables
2. Datatypes
3. Operators
4. Structure
5. Conditional Statements
6. Looping Statements
---------------------------------------------------------------------
1. Object, Class, Keywords and Identifiers
2. Methods, Constructor and Blocks
3. Inheritance
4. Overloading and Overriding
5. Access Modifiers and Encapsulation
6. Casting, Abstract keyword, Interface and Arrays
7. Polymorphism
8. Abstraction
----------------------------------------------------------------------
1. Java Libraries -> String -> Lambda Functions
2. Exception Handling
3. File Handling
4. Multi-Threading
5. Collection Framework
What is Java?
- Java is a high level, platform independent,
object-oriented programming language.
udaypawar037@[Link] 2
- High Level Language is a language which is in
normal English i.e. Human Understandable Form.
- Programming Language is a medium to interact or
communicate with the system.
udaypawar037@[Link] 3
Note: Refer Screenshot for diagram
History:
1. Java was introduced by a company called as Sun
Micro Systems.
2. Java is owned by a company called as Oracle
presently.
3. James Gosling was the Person who developed
JAVA.
4. Previous Names of Java are Green Talk and Oak.
Variables
1. Variable is Container in order to store some data or
information.
Example:
Datatypes
1. Datatype is an indication of the type of data stored
into a variable.
2. In order to store Non-Decimal Numeric Values, we make
use byte, short, int, long.
3. In order to store Decimal Numeric Values, we make use
float, double.
4. In order to store true/false, we make use boolean.
5. In order to store Single Character in single quotes,
we make use char.
udaypawar037@[Link] 4
Note: All the above 8 Datatypes are referred Primitive
Datatypes
6. In order to store a sequence of characters we make
use of String.
udaypawar037@[Link] 5
Programs
1.
class FirstProgram
{
public static void main(String[] args)
{
[Link]("Hello World!!");
}
}
o/p:
Hello World!!
2.
class Greet
{
public static void main(String[] args)
{
[Link]("Welcome to Java Online
Session");
}
}
o/p:
udaypawar037@[Link] 6
Welcome to Java Online Session
1. Arithmetic Operators
a. +
b. –
c. *
d. /
e. %
2. Assignment Operators
a. =
b.+=
c. -=
d.*=
e. /=
f. %=
udaypawar037@[Link] 7
e. ==
f. !=
Note: Return type is Boolean value (true or false)
4. Logical Operators
a. && -> AND
b. || -> OR
c. ! -> Not
Note: Return type is Boolean value
Truth Tables: True-T False-F
AND (&&)
A B O/P
T T T
T F F
F T F
F F F
OR (||)
A B O/P
T T T
T F T
F T T
F F F
NOT
T F
F T
5. Unary Operators
++ Increment by 1
udaypawar037@[Link] 8
-- Decrement by 1
int x = 5;
int y = x++;
Post-Increment -> First Assign, Then Increment
---------------------------
int a = 10;
int b = ++a;
Pre-Increment -> First Increment, Then Assign
int x = 5;
int y = x--;
Post-Decrement -> First Assign, Then Decrement
---------------------------
int a = 10;
int b = --a;
Pre-Decrement -> First Decrement, Then Assign
Comments
1. Additional Information which will not affect the
execution of a program.
// Single Line Comment
/* Multi
Line
Comment */
udaypawar037@[Link] 9
1.
class Student
{
public static void main(String[] args)
{
// Variable Declaration
int age;
// Variable Initialization
age = 20;
[Link](age);
[Link](name);
[Link]("--------------");
[Link]("--------------");
[Link](age+name);
[Link]("--------------");
[Link](age+" "+name);
}
}
udaypawar037@[Link]
10
/* this
is
a
java program */
o/p:
20
Jerry
--------------
Student Age = 20
Student Name is Jerry
--------------
20Jerry
--------------
20 Jerry
2.
class Operators
{
public static void main(String[] args)
{
/* Arithmetic Operators */
int a = 5;
int b = 10;
int sum = a+b;
[Link]("Sum: "+sum);
[Link](a-2);
[Link](4*b);
[Link](10/5);
[Link](10%2);
udaypawar037@[Link]
11
[Link]("-------------");
/* Assignment Operators */
int x = 10;
[Link]("value of x = "+x);
x+=20; // x = x+20;
[Link]("value of x = "+x);
int i = 45;
[Link]("value of i = "+i);
i -= 13;
[Link]("value of i = "+i);
[Link]("-------------");
}
}
o/p:
Sum: 15
3
40
2
0
-------------
value of x = 10
value of x = 30
value of i = 45
value of i = 32
-------------
udaypawar037@[Link]
12
3.
class Demo
{
public static void main(String[] args)
{
/* Comparison Operators */
int x = 10;
int y = 20;
[Link](x<y); // true
[Link](x<=5); // false
[Link]("------------");
[Link](y>50); // false
[Link](y>=20); // true
[Link]("------------");
[Link](x==y); // false
[Link](x!=y); // true
[Link](x==10); // true
[Link](x!=10); // false
[Link]("=====================");
/* Logical Operators */
int a = 1;
udaypawar037@[Link]
13
int b = 2;
boolean result = a<b && a==1;
[Link](result); // true
[Link](a<=4 && a==b); // false
[Link]("------------");
[Link]("------------");
[Link](!true); // false
[Link](!false);// true
[Link](!(1<2)); // false
[Link](!(20<5)); // true
}
}
o/p:
true
false
------------
false
true
------------
false
true
true
false
=====================
true
udaypawar037@[Link]
14
false
------------
true
false
------------
false
true
false
true
4.
class Unary
{
public static void main(String[] args)
{
int x = 5;
[Link]("x: "+x); // 5
x++;
[Link]("x: "+x); // 6
x++;
[Link]("x: "+x); // 7
x--;
[Link]("x: "+x); // 6
x--;
[Link]("x: "+x); // 5
[Link]("===================");
udaypawar037@[Link]
15
int i = 40;
int j = i++; // Post Increment -> First Assign, Then
Increment
[Link](i+" "+j); // 41 40
[Link]("-------------");
int a = 5;
int b = --a; // pre decrement -> first decrement,
then assign
[Link](a+" "+b); // 4 4
[Link]("===================");
/* Ternary Operators */
int p = 10;
int q = 50;
}
}
o/p
x: 5
udaypawar037@[Link]
16
x: 6
x: 7
x: 6
x: 5
===================
41 40
-------------
44
===================
Maximum of 10 & 50 is 50
Simple If:
- It is a Decision-Making statement wherein we execute
a set of the instructions if the condition is true.
If Else:
- It is a Decision-Making statement wherein we execute
a set of the instructions if the condition is true
and another set of instructions if the condition is
false.
If Else If
udaypawar037@[Link]
17
- - If Else If Condition is used when we need to check
or compare multiple conditions.
1.
class SimpleIfDemo
{
public static void main(String[] args)
{
[Link]("start");
int n = 5;
[Link]("end");
}
}
o/p:
start
5 is lesser than or equal to 10
end
2.
class IfElseDemo
{
public static void main(String[] args)
{
int a = 50;
int b = 20;
if(a<=b)
{
[Link](a+" is lesser than or equal
to "+b);
}
else
{
udaypawar037@[Link]
18
[Link](a+" is greater than "+b);
}
[Link]("--------------------------");
if(true)
{
[Link]("Hai Dinga");
}
else
{
[Link]("Bye Dinga");
}
[Link]("--------------------------");
if(false)
{
[Link]("Hai Dinga");
}
else
{
[Link]("Bye Dinga");
}
o/p:
50 is greater than 20
--------------------------
Hai Dinga
--------------------------
Bye Dinga
3.
class IfElseIfDemo
{
public static void main(String[] args)
{
int a = 10;
udaypawar037@[Link]
19
int b = 10;
o/p:
10 is equal to 10
4.
class MarksValidation
{
public static void main(String[] args)
{
int marks = -7;
o/p:
Invalid Marks
4. Nested If
- Nested If is a decision-making statement wherein one if
condition is present inside another if condition.
1.
class NestedIf
{
public static void main(String[] args)
{
int a = 70;
if(a==5) // inner if
{
[Link]("a is equal to 5");
}
else // inner else
{
[Link]("a is not equal to
5");
udaypawar037@[Link]
21
}
}
else // outer else
{
[Link]("a greater than 10");
}
}
}
o/p:
a greater than 10
2.
class LoginValidation
{
public static void main(String[] args)
{
String id = "adminxyz";
int password = 123;
if(id == "admin")
{
[Link]("User Id is Valid");
if(password == 123)
{
udaypawar037@[Link]
22
[Link]("Password is
Valid");
[Link]("Login Successful
:)");
}
else
{
[Link]("Password is
Invalid");
[Link]("Login Unsuccessful
:(");
}
}
else
{
[Link]("User Id is Invalid");
[Link]("Login Unsuccessful :(");
}
}
}
o/p:
User Id is Invalid
Login Unsuccessful :(
3.
class AssignmentPrograms
udaypawar037@[Link]
23
{
public static void main(String[] args)
{
int num = -10;
if(num>0)
{
[Link](num+" is a Positive
Number");
}
else
{
[Link](num+" is a Negative
Number");
}
[Link]("-------------");
int n = 215;
int a = 20;
int b = 20;
[Link]("a:"+a+" b:"+b);
if(a>b)
{
[Link]("a is Largest");
}
else if(a<b) // b>a
{
[Link]("b is Largest");
}
else
{
[Link]("a and b are both
equal");
}
}
}
o/p:
-10 is a Negative Number
-------------
udaypawar037@[Link]
25
215 is a Odd Number
-------------
a:20 b:20
a and b are both equal
Switch Statement:
Switch Statement is generally used for Character Comparison.
1.
class SwitchDemo
{
public static void main(String[] args)
{
int choice = 3;
switch(choice)
{
case 1: [Link]("In Case-1");
break;
default : [Link]("Invalid");
udaypawar037@[Link]
26
}
}
}
o/p:
In Case-3
2.
class GradeValidation
{
public static void main(String[] args)
{
char grade = 'C';
switch(grade)
{
case 'A': [Link]("Excellent ->
Distinction");
break;
udaypawar037@[Link]
27
default: [Link]("Invalid
Grade");
}
}
}
o/p:
Bad -> Fail :(
3.
class LargestOfThreeNumbers
{
public static void main(String[] args)
{
int a = 20;
int b = 150;
int c = 10;
if(a>b)
{
if(a>c) {
[Link]("a is Largest");
}
else {
[Link]("c is Largest");
udaypawar037@[Link]
28
}
}
else if(b>c)
{
[Link]("b is Largest");
}
else
{
[Link]("c is Largest");
}
[Link]("-------------------");
udaypawar037@[Link]
29
o/p:
a:20 b:150 c:10
b is Largest
-------------------
b is Largest
4.
class Demo
{
public static void main(String[] args)
{
[Link]("hai");
[Link]("hai");
[Link](" bye"+10);
[Link]("java");
[Link]("hai"+" hello");
[Link]("hai");
[Link]("bye");
[Link]("hai");
[Link]("Good Morning");
[Link]("Bye");
[Link]("==============");
[Link]("hai");
[Link]("Morning");
udaypawar037@[Link]
30
[Link]("bye");
}
}
o/p:
hai
hai bye10java
hai hellohaibye
hai
Good Morning
Bye
==============
haiMorningbye
5.
class MatrimonyPortal
{
public static void main(String[] args)
{
char gender = 'M';
int age = 19;
if(gender == 'M')
{
[Link]("Gender is Male");
udaypawar037@[Link]
31
if(age>=21)
{
[Link]("Yes, You can get
Married");
}
else
{
[Link]("Have Patience :)");
}
}
else if(gender == 'F')
{
[Link]("Gender is Female");
if(age>=18)
{
[Link]("Yes, You can get
Married");
}
else
{
[Link]("Have Patience :)");
}
}
else
{
[Link]("Invalid");
udaypawar037@[Link]
32
}
}
}
o/p
Gender is Male
Have Patience :)
Looping Statements:
Looping Statements are generally used to perform repetitive task.
Loops are used to repeat the execution of a set of instructions and
traverse a group of elements.
Different Looping Statements are as follows:
o For Loop
o While Loop
o Do-While Loop
o Nested For Loop
For Loop:
For loop is used to execute a set of instructions for a fixed no of times.
It has a logical start point and end point.
Assignment
1.
class ForLoopDemo
{
udaypawar037@[Link]
33
public static void main(String[] args)
{
// Print Hello 5 times
[Link]("Hello");
[Link]("Hello");
[Link]("Hello");
[Link]("Hello");
[Link]("Hello");
[Link]("-------------");
[Link]("-------------");
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link]("-------------");
udaypawar037@[Link]
34
for(int i=1; i<=5; i++)
{
[Link](i);
}
}
}
o/p:
Hello
Hello
Hello
Hello
Hello
-------------
Hello
Hello
Hello
Hello
Hello
-------------
1
2
3
4
5
-------------
1
udaypawar037@[Link]
35
2
3
4
5
2.
class ForLoopExample
{
public static void main(String[] args)
{
int n = 5;
int sum = 0;
[Link]("Sum: "+sum);
[Link]("---------");
udaypawar037@[Link]
36
[Link]("---------");
// 5 4 3 2 1
for(int i=5; i>=1; i--)
{
[Link](i);
}
[Link]("---------");
// 2 4 6 8 10
for(int i=2; i<=10; i=i+2)
{
[Link](i);
}
[Link]("---------");
// 1 3 5 7 9
for(int i=1; i<=9; i+=2)
{
[Link](i);
}
[Link]("---------");
udaypawar037@[Link]
37
for(int i=2; i<=10; i+=2)
{
[Link](i+" ");
}
}
}
o/p:
Sum: 15
---------
146
147
148
149
150
---------
5
4
3
2
1
---------
2
4
6
8
udaypawar037@[Link]
38
10
---------
1
3
5
7
9
---------
2 4 6 8 10
While Loop:
- While loop is a looping statement which keeps on
executing until the condition is false.
Do-While Loop:
- Do-While loop is similar to while loop but do while
loop executes a set of instructions and then checks
the condition.
**********************************************************
Difference between while loop and do-while loop
While Loop Do While Loop
1. Checks Condition first and 1. Executes a set of
then executes a set of instructions first and then
instructions. checks the condition.
2. Does not execute even once 2. executes at least once even
if the initial condition if the initial condition is
is false. false.
udaypawar037@[Link]
39
1.
class WhileLoopDemo
{
public static void main(String[] args)
{
int n = 1;
while(n<=5)
{
[Link](n);
n++;
}
[Link]("--------------");
int x = 1;
do
{
[Link](x);
x++;
}
while(x<=5);
[Link]("--------------");
int i = 5;;
while(i>=1)
{
udaypawar037@[Link]
40
[Link](i);
i--;
}
[Link]("--------------");
int j = 5;
do
{
[Link](j);
j--;
}
while(j>=1);
}
}
o/p:
1
2
3
4
5
--------------
1
2
3
udaypawar037@[Link]
41
4
5
--------------
5
4
3
2
1
--------------
5
4
3
2
1
2.
class NestedForLoopDemo
{
public static void main(String[] args)
{
for(int i=1; i<=3; i++)
{
for(int j=5; j<=6; j++)
{
[Link]("i:"+i + " j:"+j);
}
[Link]("--------");
udaypawar037@[Link]
42
}
o/p:
i:1 j:5
i:1 j:6
--------
i:2 j:5
i:2 j:6
--------
i:3 j:5
i:3 j:6
--------
* * * * *
* * * * *
* * * * *
* * * * *
udaypawar037@[Link]
43
* * * * *
udaypawar037@[Link]
44
Java Notes
udaypawar037@[Link] 1
Object Oriented Programming
Object
- Anything which is present in the real world and
physically existing can be termed as an Object.
- The Properties of every object is categorized into 2
types:
o States
o Behaviours
- States are the properties used to store some data.
- Behaviour are the properties to perform some task.
Class
- class is a blue print of an object.
- It’s a platform to store states and behaviours of an
object.
- class has to be declared using class keyword.
- class can also act as datatype.
udaypawar037@[Link] 2
1.
/*
Accessing Non-Static Variables inside same class
*/
class Student
{
// NON-STATIC VARIABLES
int age = 20;
String name = "Dinga";
[Link]([Link]);
[Link]([Link]);
[Link]("------------------------
-");
[Link]("Age: "+[Link]);
[Link]("Name: "+[Link]);
[Link]("------------------------
-");
[Link]([Link]+" is "+[Link]+"
years old");
[Link]("*****");
[Link]("end");
}
}
o/p
udaypawar037@[Link] 3
start
*****
20
Dinga
-------------------------
Age: 20
Name: Dinga
-------------------------
Dinga is 20 years old
*****
end
2a.
class Employee
{
int id = 101;
String name = "Tom";
double salary = 123.45;
}
2b.
/*
Accessing Non-Static Variables in another class
*/
class Test
{
public static void main(String[] args)
{
Employee emp = new Employee();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
o/p:
101
udaypawar037@[Link] 4
Tom
123.45
udaypawar037@[Link] 5
Java Notes
udaypawar037@[Link] 1
Default Value
- If a variable is declared and not initialized to any
value, then the compiler will automatically initialize to
its default value.
- Default values are applicable only for Member Variables
(Static and Non-Static Variables).
Assignment:
1. Create a class called as Employee.
2. Declare 3 attributes as id, name and salary.
3. Create another class called as Solution.
4. Under main(), create 3 objects of Employee, then re-
initialize to their respective values and display the contents.
1.
package com;
class DefaultValuesDemo {
int a;
double b;
char c;
boolean d;
udaypawar037@[Link] 2
String e;
[Link](dvd.a);
[Link](dvd.b);
[Link](dvd.c);
[Link](dvd.d);
[Link](dvd.e);
}
}
o/p:
0
0.0
2.
package com;
class Car {
[Link]([Link]+"
"+[Link]);
udaypawar037@[Link] 3
[Link] = 15;
[Link] = 23;
[Link]([Link]+"
"+[Link]);
}
}
o/p:
10 10
15 23
3.
package com;
class Student {
String name;
int marks;
[Link]([Link]+"
"+[Link]);
[Link]([Link]+"
"+[Link]);
[Link]("-------------------
");
udaypawar037@[Link] 4
[Link] = "Tom";
[Link] = 36;
[Link] = "Jerry";
[Link] = 40;
[Link]([Link]+"
"+[Link]);
[Link]([Link]+"
"+[Link]);
[Link]("-------------------
");
}
}
o/p:
null 0
null 0
-------------------
Tom 36
Jerry 40
-------------------
Tom has scored 36 marks in Java
Jerry has scored 40 marks in Java
udaypawar037@[Link] 5
Java Notes
udaypawar037@[Link] 1
Methods or Functions
1. A Method is a set of instructions or a block of code in order to
perform a specific task.
void: void is an indication to the caller, that the method does not
return anything.
udaypawar037@[Link] 2
1.
package com;
class Demo {
[Link]("start");
[Link]("end");
}
}
o/p:
start
Hello World!
end
2.
package com;
class Addition
{
/* Method with Arguments and without return statement */
void add(int a, int b)
{
[Link]("Sum of "+a+" & "+b+" is "+ (a+b) );
/* int sum = a+b;
[Link]("Sum of "+a+" & "+b+" is "+sum);
[Link](a+b); */
}
udaypawar037@[Link] 3
[Link](10, 20);
[Link](6, 3);
[Link](123, 456);
}
}
o/p:
Sum of 10 & 20 is 30
Sum of 6 & 3 is 9
Sum of 123 & 456 is 579
3.
package com;
class Test
{
/* Method without Arguments and with return statement */
int display()
{
return 10;
}
[Link]("start");
[Link]([Link]());
[Link]("end");
}
}
o/p:
start
10
10
end
udaypawar037@[Link] 4
4.
package com;
class Example
{
/* Method with Arguments and with return statement */
int findSquare(int n)
{
return n*n;
}
[Link]([Link](4));
}
}
o/p:
25
16
5a.
package com;
class Solution {
5b.
package com;
s.m1();
[Link]("------------");
s.m2("john", 25);
[Link]("------------");
[Link](s.m3());
[Link]("------------");
[Link](s.m4(12, 78));
}
}
o/p:
Learning Methods
------------
Name: john Age:25
------------
Jspiders
Jspiders
------------
9
90
udaypawar037@[Link] 6
6.
package com;
int m1()
{
return 10+10;
}
double m2()
{
return 10+10.7;
}
String m3()
{
return "hai"+10;
}
String a = "java";
}
udaypawar037@[Link] 7
Java Notes
udaypawar037@[Link] 1
Method Overloading
1. In a class having multiple methods with the same name,
but difference in arguments is called as Method
Overloading.
Note:
1. Both Static and Non-Static methods can be Overloaded.
2. Yes, we can overload Main() as well, But the execution
starts from the main() which accepts String[] as the
argument.
3. returntype might be same or different.
4. Method Overloading is also referred as Compile time
Polymorphism.
Scanner
1. Scanner is a pre-defined class in [Link] package.
2. Scanner class is used to accept dynamic input from the
User.
udaypawar037@[Link] 2
2. Pass [Link] to the Constructor call.
syntax: Scanner scan = new Scanner([Link]);
1. byte - nextByte()
2. short - nextShort()
3. int - nextInt()
4. long - nextLong()
5. float - nextFloat()
6. double - nextDouble()
7. boolean - nextBoolean()
1a.
package com;
udaypawar037@[Link] 3
public class MethodOverloading {
void display() {
[Link]("Hello DabbaFellow");
}
void display(int x) {
[Link](x);
}
void display(double x) {
[Link](x);
}
1b.
package com;
udaypawar037@[Link] 4
public static void main(String[] args) {
[Link](45);
[Link](12, "java");
[Link](45.65);
[Link]();
[Link]("eclipse", 789);
}
}
o/p:
45
12 java
45.65
Hello DabbaFellow
eclipse 789
2.
package com;
o/p:
Hello
a:10
b:12.45
Bye
3.
package com;
udaypawar037@[Link] 6
import [Link];
[Link](a+b);
[Link]();
o/p:
Enter the value of a:
5
Enter the value of b:
20
25
udaypawar037@[Link] 7
4.
package com;
import [Link];
[Link]("Enter Age:");
int age = [Link]();
[Link]("Enter Name:");
String name = [Link]();
[Link]("Enter Salary:");
double salary = [Link]();
[Link]("-----------------");
[Link]("Age:"+age+"\nName:"+name+"\nSalar
y:"+salary);
udaypawar037@[Link] 8
}
o/p:
Enter Age:
25
Enter Name:
John
Enter Salary:
1200.35
-----------------
Age:25
Name:John
Salary:1200.35
5.
package com;
import [Link];
udaypawar037@[Link] 9
public static void main(String[] args) {
[Link](a, b);
[Link]("----------------");
}
}
}
o/p:
Enter First Number:
2
Enter Second Number:
3
Sum of 2 and 3 is 5
udaypawar037@[Link]
10
----------------
Enter First Number:
45
Enter Second Number:
65
Sum of 45 and 65 is 110
----------------
Enter First Number:
526
Enter Second Number:
9562
Sum of 526 and 9562 is 10088
----------------
udaypawar037@[Link]
11
Java Notes
udaypawar037@[Link] 1
static
1. static is a keyword which can be used with class,
variable, method and blocks.
2. The Class Loader loads all the static properties inside
a memory location called as Class Area or Static Pool.
3. All the static properties has to accessed with help of
ClassName.
4. static properties can be accessed directly or with the
help of ClassName in the same class.
5. static properties can be accessed only with the help of
ClassName in the different/another class.
Note:
1. STATIC PROPERTIES ARE LOADED ONLY ONCE, THEREFORE THEY
WILL HAVE A SINGLE COPY.
2. All Objects will implicitly be pointing to the static
pool, therefore we can access static properties with
object reference but not a good practice.
1a.
package com;
udaypawar037@[Link] 2
static void study()
{
[Link]("Student is Studying");
}
[Link]("------------");
[Link](age); //
[Link] -> [Link] -> [Link]
study(); // [Link]() ->
[Link]() -> [Link]()
}
}
o/p:
20
Student is Studying
------------
20
Student is Studying
udaypawar037@[Link] 3
2a.
package com;
class Employee {
2b.
package com;
[Link]([Link]);
[Link]();
// [Link](id); [Link]
// work(); [Link]();
}
udaypawar037@[Link] 4
}
o/p:
101
Employee is Working
3.
package com;
[Link](cost); // [Link]
[Link](cost); // [Link]
[Link]("------------------");
udaypawar037@[Link] 5
[Link]([Link]); // not a good
practice
}
}
o/p:
10
20
------------------
20
4a.
package com;
void checkEvenOrOdd(int n) {
if(n%2 == 0)
{
[Link](n+" is a Even Number");
}
else
{
[Link](n+" is a Odd Number");
}
udaypawar037@[Link] 6
}
4b.
package com;
import [Link];
[Link](num);
[Link]("--------");
}
[Link]();
}
udaypawar037@[Link] 7
}
o/p:
Enter Number:
1
1 is a Odd Number
--------
Enter Number:
2
2 is a Even Number
--------
Enter Number:
3
3 is a Odd Number
--------
Enter Number:
4
4 is a Even Number
--------
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Blocks
1. Blocks are a set of Instructions/Block of code used for
initialization.
2. Blocks are generally categorized into
a. static block
b. non-static block
static block
1. Static blocks are a set of instructions used to
initializing static variables.
syntax: static
{
1.
package jspiders;
udaypawar037@[Link] 2
[Link]("In Static Block-1");
}
static
{
[Link]("In Static Block-2");
}
static
{
[Link]("In Static Block-3");
}
}
o/p:
In Static Block-1
In Static Block-2
In Static Block-3
Hello
2.
package jspiders;
udaypawar037@[Link] 3
public class Student
{
static int age;
static
{
age = 10; // [Link] = 10;
}
static
{
[Link] = 20; // age = 20;
}
}
o/p:
Age: 20
udaypawar037@[Link] 4
syntax:
{
3.
package jspiders;
{
[Link]("In Non-Static Block-2");
}
udaypawar037@[Link] 5
[Link]("End");
}
{
[Link]("In Non-Static Block-3");
}
o/p:
Start
In Non-Static Block-1
In Non-Static Block-2
In Non-Static Block-3
End
4.
package jspiders;
{
id = 10;
}
udaypawar037@[Link] 6
public static void main(String[] args)
{
Employee e = new Employee();
[Link]("ID: "+[Link]);
}
{
id = 20;
}
// id = 0 -> 10 -> 20
o/p:
ID: 20
5.
package jspiders;
udaypawar037@[Link] 7
public static void main(String[] args)
{
Car c = new Car();
[Link](3);
}
{
[Link](2);
}
}
o/p:
1
2
3
6.
package jspiders;
static
{
x = 20;
}
udaypawar037@[Link] 8
public static void main(String[] args)
{
Pen p = new Pen();
[Link](x);
}
{
x = 30;
}
}
o/p:
30
JDK
- Java Development Kit
- JDK is a software which contains all the resources in
order to develop and execute java programs.
JRE
- Java Runtime Environment
- JRE is a software which provides a platform for
executing java programs.
JIT Compiler
- Just In Time Compiler
- JIT Compiler complies/coverts java program(High Level)
into machine understandable language.
udaypawar037@[Link] 9
Class Loader
- Loads the Class from secondary storage to executable
area.
Interpreter
- Interprets the code line by line.
JVM
- Java Virtual Machine
- JVM is the Manager of the JRE.
JVM Architecture
1. Heap Area - Objects get created here.
2. Class Area - or Static Pool - All the static members
gets stored here.
3. Stack - Execution happens inside stack.
4. Method Area - Implementation of methods is stored here.
5. Native Area
7.
package jspiders;
o/p:
start
Hai
Bye 20
end
udaypawar037@[Link]
11
Java Notes
udaypawar037@[Link] 1
Constructor
1. Constructor is a set of instructions used for
initialization(Assigning) and Instantiation (Object
Creation).
2. Constructor Name and Class Name should always be same.
3. Constructors will not have return type.
4. Constructors will get executed at the time of object
creation.
5. Constructors are categorized into 2 types:
a. Default Constructor
b. Custom/User-Defined Constructor
Default Constructor
1. If a constructor is not explicitly present in a class,
then the compiler will automatically generate a
constructor and those constructors are called as Default
Constructor.
2. Default constructor neither accepts any arguments nor
has any implementation.
Custom/User-Defined Constructor
1. If a constructor is explicitly defined inside a class
by the user or the programmer, then we refer it as
custom/user-defined constructor.
udaypawar037@[Link] 2
2. They are further categorized into 2 types:
i. Non-Parameterized Custom Constructor
ii. Parameterized Custom Constructor
udaypawar037@[Link] 3
*******************PROGRAMS*******************
1a.
package com;
class Car
{
// Non-Parameterized Custom Constructor
Car()
{
[Link]("Hello");
}
[Link]("end");
}
}
o/p:
start
Hello
end
udaypawar037@[Link] 4
2.
package com;
class Bike
{
// Parameterized Custom Constructor
Bike(int cost) // cost=1000
{
[Link]("Cost: "+cost);
}
o/p:
Cost: 1000
3.
package com;
udaypawar037@[Link] 5
{
}
*/
public static void main(String[] args)
{
Pen p = new Pen();
}
}
4.
package com;
class Student
{
int age;
Student(int a)
{
age = a;
}
udaypawar037@[Link] 6
[Link]("Age: "+[Link]);
[Link]("Age: "+[Link]);
}
}
o/p:
Age: 21
Age: 22
5.
package com;
class Kangaroo
{
double height = 5.5; // Member/Global
Variable (Non-Static)
void display()
{
double height = 4.4; // Local
Variable
[Link](height);
[Link]([Link]);
}
udaypawar037@[Link] 7
Kangaroo k = new Kangaroo();
[Link]();
}
}
o/p:
4.4
5.5
6.
package com;
class Person {
int age;
String name;
udaypawar037@[Link] 8
[Link]("Name: "+[Link]+" Age:
"+[Link]);
[Link]("Name: "+[Link]+" Age:
"+[Link]);
o/p:
Name: Tom Age: 20
Name: Tim Age: 22
7.
package com;
class Vehicle
{
int x = 10;
}
class Test
{
public static void main(String[] args)
{
Vehicle v = new Vehicle();
[Link](v.x);
udaypawar037@[Link] 9
}
}
o/p:
10
udaypawar037@[Link]
10
Java Notes
udaypawar037@[Link] 1
INHERITANCE
1. Inheritance is a process of one class acquiring the
properties of another class.
2. A class which gives or shares the properties are called
as Super Class, Base Class or Parent Class.
3. A class which acquires or accepts the properties are
called as Sub Class, Derived Class or Child Class.
4. In java, we achieve inheritance with the help of
'extends' keyword.
5. Inheritance is also referred as "IS-A" Relationship.
6. In java, Only Variables and methods are inherited
whereas blocks and constructors are not INHERITED.
Types of Inheritance
1. Single Level Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1a.
package singlelevel;
1b.
udaypawar037@[Link] 2
package singlelevel;
1c.
package singlelevel;
[Link]([Link]);
[Link]([Link]);
o/p:
40
Tom
udaypawar037@[Link] 3
2a.
package multilevel;
void conductExams() {
[Link]("VTU is conducting Exams");
}
2b.
package multilevel;
void providePlacements() {
[Link]("Jspiders Provides
Placement");
}
udaypawar037@[Link] 4
2c.
package multilevel;
void fest() {
[Link]("CS Department had a Fest
called as Equinox");
}
2d.
package multilevel;
[Link]("University Name:
"+[Link]);
[Link]("College Name:
"+[Link]);
udaypawar037@[Link] 5
[Link]("Department Name:
"+[Link]);
[Link]("-----------------");
[Link]();
[Link]();
[Link]();
o/p:
University Name: VTU
College Name: Jspiders
Department Name: Computer Science
-----------------
VTU is conducting Exams
CS Department had a Fest called as Equinox
Jspiders Provides Placement
3a.
package hierarchical;
udaypawar037@[Link] 6
}
3b.
package hierarchical;
void start() {
[Link]("Car Started");
}
3c.
package hierarchical;
void stop() {
[Link]("Bike Stopped");
}
udaypawar037@[Link] 7
}
3d.
package hierarchical;
[Link]("--------");
}
}
o/p:
BMW 45000
Car Started
--------
BMW Petrol
Bike Stopped
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Constructor Overloading
1. The Process of having multiple constructors in the same
class but difference in arguments.
In order to achieve Constructor Overloading we have to
either follow 1 of the following rules.
a. There should be a change in the (length)No of
Arguments.
b. There should be a change in the Datatype of the
Arguments.
c. There should be a change in the Sequence/Order of
Datatype.
Programs
1.
package org;
class Employee {
int id;
String name;
double salary;
udaypawar037@[Link] 2
public static void main(String[] args) {
[Link]("Employee Details");
[Link]("==========================");
[Link]("-------------------");
}
}
2.
package com;
udaypawar037@[Link] 3
int id;
String name;
double salary;
void display() {
[Link]("Employee Id: "+[Link]);
[Link]("Employee Name: "+[Link]);
[Link]("Employee Salary: "+salary);
// [Link]
}
[Link]("Employee Details");
[Link]("==========================");
[Link]();
udaypawar037@[Link] 4
[Link]("-------------------");
[Link]();
}
}
3.
package com;
udaypawar037@[Link] 5
Vehicle(String brand) {
[Link]("Brand: "+brand);
}
Vehicle() {
[Link]("No Argument Constructor");
}
new Vehicle();
Vehicle obj = new Vehicle();
udaypawar037@[Link] 6
}
}
o/p:
Brand: BMW
Brand: Audi Cost:45000
Cost: 8999 Brand: Suzuki
Brand: Honda Fuel: Petrol
No Argument Constructor
No Argument Constructor
super keyword
1. super is a keyword which is used to access the super
class properties.
syntax: [Link] or [Link]()
Note:
1. this -> points to current object
2. super -> points to super class object
4a.
package org;
4b.
package org;
void display()
{
int age = 10;
[Link](age); // 10
[Link]([Link]); // 30
[Link]([Link]); // 50
}
}
4c.
package org;
udaypawar037@[Link] 8
[Link]();
o/p:
10
30
50
udaypawar037@[Link] 9
Java Notes
udaypawar037@[Link] 1
CONSTRUCTOR CHAINING
1. The Process of one constructor calling another
constructor is called as constructor chaining.
2. Constructor Chaining can be achieved only in case of
constructor overloading.
Note:
1. this() or super() should always be the first executable
line within the constructor.
2. Recursive Chaining is not possible, Therefore if there
are 'n' constructors we can have a maximum of 'n-1' caling
statements.
1.
package chaining;
udaypawar037@[Link] 2
Demo()
{
[Link](2);
}
[Link]("END");
}
}
o/p:
START
2
1
END
2.
package chaining;
udaypawar037@[Link] 3
Student(int age) // age = 22
{
this("Tom");
[Link]("Age: "+age);
}
o/p:
Name: Tom
Age: 22
Height: 5.8
udaypawar037@[Link] 4
3.
// Recursive Chaining
package chaining;
Car(String brand)
{
// this(500);
}
Car(int cost)
{
// this("bmw");
}
4.
package chaining;
udaypawar037@[Link] 5
public class Employee {
o/p:
101
Dinga
udaypawar037@[Link] 6
a. IS-A (Inheritance) --> extends
b. super() ie. super calling statement.
i. implicitly
When we create an object of a class, and if that class has
a super class, and if that super class has a non-
parameterized constructor, then the sub class constructor
will invoke the super class constructor implicitly.
1a.
package com;
class Father
{
Father()
{
[Link](1);
}
}
1b.
package com;
udaypawar037@[Link] 7
[Link](2);
}
}
1c.
package com;
}
}
o/p:
1
2
ii. explicitly
When we create an object of a class, and if that class has
a super class, and if that super class has a parameterized
constructor, then the sub class constructor should invoke
the super class constructor explicitly, otherwise we get
compile time error.
1a.
package com;
udaypawar037@[Link] 8
class Father
{
Father(int a)
{
[Link](1);
}
}
1b.
package com;
1c.
package com;
udaypawar037@[Link] 9
}
o/p:
1
2
2a.
package com;
class Vehicle
{
Vehicle(String brand)
{
[Link]("brand: "+brand);
}
}
2b.
package com;
udaypawar037@[Link]
10
2c.
package com;
}
}
o/p:
brand: BMW
cost: 200
udaypawar037@[Link]
11
Java Notes
udaypawar037@[Link] 1
Method Overriding
1. The process of Inheriting the method and changing the
implementation/Definition of the inherited method is
called as method overriding.
Note:
1. Access Specifier should be same or of Higher
Visibility.
2. While Overriding a method we can optionally use
annotation ie. @Override
3. annotation was introduced from JDK 1.5
1a.
package com;
class Father
{
void bike()
{
[Link]("Old Fashioned Father's
Bike!");
udaypawar037@[Link] 2
}
}
1b.
package com;
o/p:
New Modified Son's Bike
udaypawar037@[Link] 3
2a.
package com;
void start() {
[Link]("Vehicle Started");
}
2b.
package com;
@Override
void start()
{
[Link]();
[Link]("Car Started");
[Link]();
}
udaypawar037@[Link] 4
2c.
package com;
[Link]();
o/p:
Vehicle Started
Car Started
Vehicle Started
3a.
package com;
udaypawar037@[Link] 5
public class WhatsApp1 {
void display() {
[Link]("Single Ticks
Supported");
}
3b.
package com;
@Override
void display() {
[Link]();
[Link]("Double Ticks
Supported");
}
void call() {
[Link]("Voice Call Supported");
}
}
udaypawar037@[Link] 6
3c.
package com;
@Override
void display() {
[Link]();
[Link]("Blue Ticks Supported");
}
@Override
void call() {
[Link]();
[Link]("Video Call Supported");
}
void story() {
[Link]("Can Upload Images as
Story");
}
udaypawar037@[Link] 7
3d.
package com;
[Link]();
[Link]("-----------------");
[Link]();
[Link]("-----------------");
[Link]();
o/p:
udaypawar037@[Link] 8
Single Ticks Supported
Double Ticks Supported
Blue Ticks Supported
-----------------
Voice Call Supported
Video Call Supported
-----------------
Can Upload Images as Story
final keyword
- final keyword can be used with a variable,
method, and class.
- final variable acts as a constant, whose value
cannot be re-initialized.
- final methods can be inherited but cannot be
Overridden.
- final class cannot be Inherited.
4.
package com;
int a = 10;
a = 20;
a = 30;
}
}
5a.
package com;
class Father
{
final void bike()
{
[Link]("Old Fashioned Father's
Bike!");
}
}
5b.
udaypawar037@[Link]
10
package com;
6a.
package com;
udaypawar037@[Link]
11
}
6b.
package com;
// Error
udaypawar037@[Link]
12
Java Notes
udaypawar037@[Link] 1
Array
1. Array is a container to store a group of Data/Elements.
2. Array is of Fixed Size.
3. Array can store only Homogeneous Data.
4. Array is of Indexed Based and index position starts
from 0.
1.
package com;
/* Array Declaration */
int[] a;
/* Array Creation */
a = new int[3];
[Link]("-------");
/* Array Initialization */
a[0] = 10;
a[1] = 20;
a[2] = 40;
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link]("==============");
udaypawar037@[Link] 2
// Array Declaration and Creation
double[] x = new double[4];
[Link](x[0]);
[Link](x[1]);
[Link](x[2]);
[Link](x[3]);
[Link]("-------");
x[0] = 1.2;
x[1] = 3.4;
x[2] = 5.6;
x[3] = 7.8;
[Link](x[0]);
[Link](x[1]);
[Link](x[2]);
[Link](x[3]);
[Link]("Length: "+[Link]);
}
o/p:
0
0
0
-------
10
20
40
==============
0.0
0.0
0.0
0.0
-------
udaypawar037@[Link] 3
1.2
3.4
5.6
7.8
Length: 4
2.
package com;
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link]("------");
[Link]("------");
[Link]("======================");
int sum = 0;
udaypawar037@[Link] 4
for(int i=0; i<[Link]; i++)
{
sum = sum + data[i]; // sum += data[i];
}
[Link]("Sum: "+sum);
}
}
o/p:
10
20
30
------
10
20
30
------
30
20
10
======================
Sum: 150
Average: 30
udaypawar037@[Link] 5
Java Notes
udaypawar037@[Link] 1
Packages
1. Packages are nothing but Folder or Directory.
2. Packages are used to store classes and interfaces.
3. Searching becomes easy.
4. Better Maintenance of the Programs.
example:
package [Link];
class Inbox {
udaypawar037@[Link] 2
udaypawar037@[Link] 3
udaypawar037@[Link] 4
1.
package com;
public Person() {
[Link]("In Person Class Constructor");
}
}
}
o/p:
In Person Class Constructor
20
Person is Eating
udaypawar037@[Link] 5
2a.
package com;
public Person() {
[Link]("In Person Class Constructor");
}
2b.
package com;
udaypawar037@[Link] 6
[Link]([Link]);
[Link]();
o/p:
In Person Class Constructor
20
Person is Eating
3a.
package com;
public Person() {
[Link]("In Person Class Constructor");
}
udaypawar037@[Link] 7
}
3b.
package org;
import [Link];
o/p:
In Person Class Constructor
20
Person is Eating
4.
package com;
udaypawar037@[Link] 8
/* Accessing Private Members In Same Class Same Package */
o/p:
2000
Chatting
5a.
package com;
udaypawar037@[Link] 9
public class Mobile {
5b. ERROR
package com;
}
}
--------------------------------------------------------
6.
package com;
udaypawar037@[Link]
10
/* Accessing default Members In Same Class */
class Television {
Television() {
[Link]("In Constructor");
}
void watchMovie() {
[Link]("Watching Movie");
}
o/p:
In Constructor
Sony
Watching Movie
udaypawar037@[Link]
11
7a.
package com;
class Television {
Television() {
[Link]("In Constructor");
}
void watchMovie() {
[Link]("Watching Movie");
}
7b.
package com;
class User {
udaypawar037@[Link]
12
}
o/p:
In Constructor
Sony
Watching Movie
8a.
package com;
class Television {
Television() {
[Link]("In Constructor");
}
void watchMovie() {
[Link]("Watching Movie");
}
udaypawar037@[Link]
13
8b. ERROR
package org;
// import [Link];
------------------------------------------
9.
package com;
protected Television() {
[Link]("In Television Constructor");
}
udaypawar037@[Link]
14
[Link]("Watching Movie");
}
}
}
o/p:
In Television Constructor
LG
Watching Movie
9a.
package com;
protected Television() {
[Link]("In Television Constructor");
}
udaypawar037@[Link]
15
protected void watchMovie() {
[Link]("Watching Movie");
}
}
9b.
package com;
class User {
o/p:
In Television Constructor
LG
Watching Movie
10a.
package com;
udaypawar037@[Link]
16
/* Accessing Protected Members in Different class Different Package
*/
10b.
package org;
import [Link];
o/p:
50
udaypawar037@[Link]
17
Java Notes
udaypawar037@[Link] 1
Encapsulation
1. Encapsulation is a Process of Wrapping/Binding/Grouping
Data Members with its related Member Functions in a Single
Entity called as Class.
2. The process of grouping and protecting data members and
member functions in a single entity called as class.
3. The Best Example for Encapsulation is JAVA BEAN CLASS.
Advantages of Encapsulation
1. Validation can be done. (Protecting -> data security)
2. Flexible ie. Data can be made either write only or read
only.
Programs
1a.
package [Link];
[Link](25);
[Link]([Link]());
/*[Link]([Link]);
[Link] = 20;*/
o/p:
Age: 25
25
2a.
package [Link];
udaypawar037@[Link] 3
public class Employee {
2b.
package [Link];
[Link]([Link]()+"
"+[Link]());
[Link]("-----------------");
udaypawar037@[Link] 4
[Link](101);
[Link]("Name: "+[Link]());
[Link]("Id: "+[Link]());
o/p:
null 0
-----------------
Name: Tom
Id: 101
3a.
package [Link];
if(age>0) {
[Link]("Age Initialized");
[Link] = age;
}
else {
[Link]("Age Cannot be
Initialized");
}
udaypawar037@[Link] 5
}
3b.
package [Link];
import [Link];
[Link]("Enter Age:");
int age = [Link]();
[Link](age);
[Link]([Link]());
}
}
o/p:
Enter Age:
25
Age Initialized
25
4a.
package [Link];
udaypawar037@[Link] 6
if(cost>0) {
[Link] = cost;
}
}
4b.
package [Link];
[Link]("Cost: "+[Link]());
[Link](200);
[Link]("Cost: "+[Link]());
[Link](300);
[Link]("Cost: "+[Link]());
}
}
o/p:
Cost: 100
Cost: 200
Cost: 300
udaypawar037@[Link] 7
Java Notes
udaypawar037@[Link] 1
TYPE CASTING
1. Type Casting is a process of converting/storing one
type of value/data into another type of value/data.
2. They are classified into 2 types:
i. Primitive Type Casting
ii. Non-Primitive Type Casting (Derived Casting)
i. Widening:
- Converting Smaller type of data into Bigger type of
data.
- Widening happens Implicitly/Automatically.
ii. Narrowing:
- Converting Bigger type of data into Smaller type of
data.
- Narrowing happens Explicitly.
1.
package primitivecasting;
[Link]("---Widening---");
udaypawar037@[Link] 2
int a = 10;
double b = a;
[Link](a+" "+b);
char c = 'a';
int d = c;
[Link](c+" "+d);
[Link]("---Narrowing---");
double x = 3.45;
int y = (int) x;
[Link](x+" "+y);
int p = 66;
char q = (char)p;
[Link](p+" "+q);
[Link]("==============");
[Link]("A"+"B");
[Link]("A"+20);
[Link]('A'+'B');
udaypawar037@[Link] 3
[Link]('a'+20);
[Link]('a'+"a");
}
}
o/p:
---Widening---
10 10.0
a 97
---Narrowing---
3.45 3
66 B
==============
AB
A20
131
117
aa
2.
udaypawar037@[Link] 4
package primitivecasting;
[Link](10); // int
[Link](10.5); // double
double x = 4.7;
float y = (float) x; // float y = (float) 4.7;
float b = 3.5f;
float c = 3.5F;
float i = (float)1.2;
[Link]("--------------------");
udaypawar037@[Link] 5
}
o/p:
10
10.5
--------------------
3.
package primitivecasting;
import [Link];
[Link]("Enter No of Elements to be
Inserted:");
int size = [Link]();
int count = 0;
[Link]("No of Occurences of
"+element+" is "+count);
}
}
udaypawar037@[Link] 7
// 100 200 300
// 0 1 2
o/p:
Enter No of Elements to be Inserted:
3
Enter 3 Elements:
10
201
10
Array Elements are:
10
201
10
Enter the Element to be find the No of Occurences:
10
No of Occurences of 10 is 2
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Non-Primitive Casting or Derived Casting
1. Non-Primitive Casting or Derived Casting or Class Type
Casting can be divided into 2 types:
i. Up-Casting
ii. Down-Casting
Upcasting
1. Creating an object of sub class, and storing it's
address into a reference of type Superclass.
2. With Upcasted Reference we can access only superclass
Members/Properties.
3. In order to achieve upcasting, IS-A Relationship
mandatory.
4. Upcasting will have implicitly/Automatically.
5. Superclass reference, subclass object.
Down-Casting
1. The process of converting the upcasted reference back
to Subclass type reference is called as Down-casting.
2. With the Subclass/Down-casted reference we can access
both superclass and subclass members properties.
3. In order to achieve down-casting, upcasting is
mandatory.
4. Down-casting has to be done explicitly.
syntax: (SubClassName) SuperClassReference;
1a.
package nonprimitive;
1b.
package nonprimitive;
1c.
package nonprimitive;
/* UPCASTING */
Father f = new Son();
[Link]([Link]); //[Link] will give
error
/* DOWNCASTING */
Son s = (Son) f;
[Link]([Link]+" "+[Link]);
o/p:
45
udaypawar037@[Link] 3
45 Dinga
2a.
package nonprimitive;
void start() {
[Link]("Vehicle Started");
}
}
2b.
package nonprimitive;
void stop() {
[Link]("Car Stopped");
}
2c.
package nonprimitive;
udaypawar037@[Link] 4
[Link]("-------------");
Car c = (Car) v;
[Link]([Link]+" "+[Link]);
[Link]();
[Link]();
o/p:
BMW
Vehicle Started
-------------
BMW Petrol
Vehicle Started
Car Stopped
udaypawar037@[Link] 5
Java Notes
udaypawar037@[Link] 1
ClassCastException
1. If an object has been upcasted we have to downcast to
same type else we get ClassCastException.
2. In other words, if one type of reference is upcasted
and downcasted to some other type of reference we get
ClassCastException.
3. If we Downcast, without upcasting even then we get
ClassCastException.
4. In order to avoid ClassCastException we make use of
instanceof operator.
instanceof
1. instanceof is an operator in order to check if an
object is an instance of a specific class type or not.
2. In other words, instanceof is an operator in order to
check if an object is having the properties of a specific
class type or not.
3. instanceof will return boolean value.
syntax: object instanceof ClassName
1a.
package org;
1b.
package org;
udaypawar037@[Link] 2
public class Son extends Father
{
int y = 20;
}
1c.
package org;
1d.
package org;
Father obj;
obj = new Son();
udaypawar037@[Link] 3
{
[Link]("Downcasting to Son");
Son s = (Son) obj;
[Link](s.x+" "+s.y);
}
else if(obj instanceof Daughter)
{
[Link]("Downcasting to
Daughter");
Daughter d = (Daughter) obj;
[Link](d.x+" "+d.z);
}
}
}
/*
Father f = new Son();
Daughter s = (Daughter) f;
o/p:
Downcasting to Son
30 20
udaypawar037@[Link] 4
1e.
package org;
[Link]("--------");
[Link]("--------");
udaypawar037@[Link] 5
[Link]("--------");
}
}
o/p:
true
true
--------
true
true
--------
true
false
false
--------
true
true
2a
udaypawar037@[Link] 6
package org;
2b.
package org;
2c.
package org;
2d.
package org;
udaypawar037@[Link] 7
public static void main(String[] args) {
}
}
o/p:
Brand: Suzuki Fuel: Diesel
3a.
package org;
udaypawar037@[Link] 8
public class Food {
3b.
package org;
3c.
package org;
3d.
package org;
3e.
package org;
udaypawar037@[Link] 9
public class KFC {
3f.
package org;
udaypawar037@[Link]
10
public class Customer {
}
}
o/p:
Eating Sandwich
udaypawar037@[Link]
11
4a.
package org;
4b.
package org;
4c.
package org;
4d.
package org;
udaypawar037@[Link]
12
Beverage vendingMachine(int choice)
{
if(choice == 1)
{
return new Coffee();
}
else if(choice == 2)
{
return new Tea();
}
else
{
return null;
}
}
}
/*
Beverage vendingMachine(int choice)
{
if(choice == 1)
{
Coffee c = new Coffee();
return c;
}
else if(choice == 2)
udaypawar037@[Link]
13
{
Tea t = new Tea();
return t;
}
else
{
return null;
}
}
*/
4e.
package org;
import [Link];
[Link]("Enter Choice:");
[Link]("1:Coffee\n2:Tea");
int choice = [Link]();
udaypawar037@[Link]
14
Beverage obj = [Link](choice);
o/p:
Enter Choice:
1:Coffee
2:Tea
1
Drinking Coffee
udaypawar037@[Link]
15
Java Notes
udaypawar037@[Link] 1
Method Binding
Associating or Mapping the Method Caller to its Method
Implementation or Definition is called Method Binding.
Polymorphism
1. Polymorphism means many forms.
2. The ability of a method to behave differently, when
different objects are acting upon it.
3. The ability of a method to exhibit different forms,
when different objects are acting upon it.
4. Different types of polymorphism are as follows:
i. Compile time polymorphism.
ii. Run time polymorphism.
**************************************************************
1a.
package compiletime;
udaypawar037@[Link] 2
public class Myntra {
udaypawar037@[Link] 3
[Link]("Cost: "+cost+" Product:
"+product);
}
1b.
package compiletime;
[Link]("GooglePay");
[Link](2500);
[Link]("Shoe", 3000);
[Link](15000, "Mobile");
[Link]("Adidas", "T-Shirt");
}
}
o/p:
Payment Gateway: GooglePay
Cost: Rs.2500
udaypawar037@[Link] 4
Product: Shoe Cost: 3000
Cost: 15000 Product: Mobile
Brand: Adidas Product T-Shirt
Note:
If we call an overridden method on the superclass
reference, always the overridden method implementation
only gets executed.
1a.
package runtime;
void work() {
udaypawar037@[Link] 5
[Link]("Working");
}
1b.
package runtime;
@Override
void work() {
[Link]("Developer is "
+ "developing an application");
}
1c.
package runtime;
@Override
void work() {
[Link]("Tester is "
+ "testing an application");
udaypawar037@[Link] 6
}
1d.
package runtime;
}
}
o/p:
Developer is developing an application
Tester is testing an application
2a.
package compiletime;
udaypawar037@[Link] 7
public class Vehicle
{
void start()
{
[Link]("Vehicle Started");
}
}
2b.
package compiletime;
2c.
package compiletime;
@Override
void start() { // 2
udaypawar037@[Link] 8
[Link]("Bike Started");
}
2d.
package compiletime;
o/p:
Car Started
Bike Started
2e.
package compiletime;
udaypawar037@[Link] 9
void invokeStart(Vehicle v) // Vehicle obj = new
Car(); -> Vehicle obj = new Bike();
{
[Link]();
}
[Link](new Car());
[Link](new Bike());
}
o/p:
Car Started
Bike Started
eg:
package runtime;
[Link]("-------------");
udaypawar037@[Link]
11
Java Notes
udaypawar037@[Link] 1
abstract
1. abstract is a keyword which can be used with class and
method.
2. A class which is not declared using abstract keyword is
called as Concrete class.
3. Concrete class can allow only concrete methods.
4. A class which is declared using abstract keyword is
called as Abstract class.
5. Abstract class can allow both abstract and concrete
methods.
6. Concrete method has both declaration and
implementation/definition.
7. Abstract method has only declaration but no
implementation.
8. All Abstract methods should be declared using abstract
keyword.
--------------------------------------------------
udaypawar037@[Link] 2
Yes. But we cannot invoke indirectly, it has to be invoked
by the sub class constructor either implicitly or
explicitly using super().
----------------------------------------------------
NOTE:
1. Can a class inherit an abstract class? -> YES
2. We cannot create an object of abstract class.
3. Abstract methods cannot be private.
4. Abstract methods cannot be static.
5. Abstract methods cannot be final.
1a.
package com;
1b.
package com;
@Override
void work() {
[Link]("Working");
}
udaypawar037@[Link] 3
[Link]();
}
o/p:
Working
2a.
package com;
void shiftGears() {
[Link]("Shifting Gears!");
}
2b.
package com;
@Override
udaypawar037@[Link] 4
void stop() {
[Link]("Car Stopped");
}
@Override
void start() {
[Link]("Car Started");
}
o/p:
Car Started
Shifting Gears!
Car Stopped
udaypawar037@[Link] 5
{
[Link](1);
}
}
1b.
package org;
1c.
package org;
udaypawar037@[Link] 6
}
o/p:
1
2
2a.
package org;
2b.
package org;
udaypawar037@[Link] 7
}
}
2c.
package org;
o/p:
1
2
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Interface
1. Interface is a Java Type Definition which has to be
declared using interface keyword.
2. Interface is a media between 2 systems, wherein 1
system is the client/user and another system is object
with resources/services.
syntax: interface InterfaceName
{
udaypawar037@[Link] 2
Programs
1a.
package org;
1b.
package org;
@Override
public void eat() {
[Link]("Eating");
}
[Link]([Link]);
udaypawar037@[Link] 3
[Link]();
o/p:
101
Eating
2a.
package org;
2b.
package org;
2c.
udaypawar037@[Link] 4
package org;
@Override
public void deposit() {
[Link]("Depositing Amount");
}
@Override
public void withdraw() {
[Link]("Withdrawing Amount");
}
}
}
o/p:
Depositing Amount
Withdrawing Amount
3a.
udaypawar037@[Link] 5
package org;
void devlop();
3b.
package org;
void test();
3c.
package org;
void work() {
[Link]("Working");
}
}
udaypawar037@[Link] 6
3d.
package org;
@Override
public void devlop() {
[Link]("Developing");
}
@Override
public void test() {
[Link]("Testing");
}
3e.
package org;
[Link]();
udaypawar037@[Link] 7
[Link]();
[Link]();
}
}
o/p:
Developing
Testing
Working
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Abstraction
1. The process of Hiding the Implementation details
(unnecessary details) and showing only the functionalities
(Behaviour) to the user with the help of an abstract class
or interface is called as Abstraction.
2. The process of Hiding the Implementation and showing
only the functionality is called as Abstraction.
3. Abstraction can be achieved by following the below
rules:
i. Abstract class or Interface.
ii. Is-A (Inheritance).
iii. Method Overriding.
iv. Upcasting.
1a.
package com;
void work();
}*/
udaypawar037@[Link] 2
1b.
package com;
@Override
public void work() {
[Link]("Employee is Working");
}
1c.
package com;
udaypawar037@[Link] 3
}
o/p:
Employee is Working
2a.
package [Link];
2b.
package [Link];
@Override
public void deposit(int amount) {
[Link]("Depositing Rs."+amount);
udaypawar037@[Link] 4
balance = balance + amount;
[Link]("Amount Deposited
Successfully");
}
@Override
public void withdraw(int amount) {
[Link]("Withdrawing Rs."+amount);
balance -= amount; // balance = balance - amount;
[Link]("Amount Withdrawn
Successfully");
}
@Override
public void checkBalance() {
[Link]("Available Balance:
Rs."+balance);
}
2c.
package [Link];
udaypawar037@[Link] 5
Bank obj = new ATM();
[Link]();
[Link]("------------------");
[Link](5000);
[Link]();
[Link]("------------------");
[Link](4500);
[Link]();
o/p:
Available Balance: Rs.10000
------------------
Depositing Rs.5000
Amount Deposited Successfully
Available Balance: Rs.15000
------------------
Withdrawing Rs.4500
Amount Withdrawn Successfully
udaypawar037@[Link] 6
Available Balance: Rs.10500
2d.
package [Link];
import [Link];
while(true)
{
[Link]("Enter Choice");
[Link]("1:Deposit\n2:Withdraw\n3:CheckBal
ance\n4:Exit");
int choice = [Link]();
switch(choice)
{
case 1:
[Link]("Enter Amount to be
Deposited:");
udaypawar037@[Link] 7
int amount = [Link]();
[Link](amount);
break;
case 2:
[Link]("Enter Amount to be
Withdrawn:");
int amt = [Link]();
[Link](amt);
// [Link]([Link]());
break;
case 3:
[Link]();
break;
case 4:
[Link]("Thank You!!");
[Link](0);
default:
[Link]("Invalid Choice");
}
[Link]("---------------------");
}
udaypawar037@[Link] 8
}
o/p:
Enter Choice
1:Deposit
2:Withdraw
3:CheckBalance
4:Exit
1
Enter Amount to be Deposited:
2000
Depositing Rs.2000
Amount Deposited Successfully
---------------------
Enter Choice
1:Deposit
2:Withdraw
3:CheckBalance
4:Exit
3
Available Balance: Rs.12000
---------------------
Enter Choice
1:Deposit
2:Withdraw
3:CheckBalance
udaypawar037@[Link] 9
4:Exit
2
Enter Amount to be Withdrawn:
5000
Withdrawing Rs.5000
Amount Withdrawn Successfully
---------------------
Enter Choice
1:Deposit
2:Withdraw
3:CheckBalance
4:Exit
3
Available Balance: Rs.7000
---------------------
Enter Choice
1:Deposit
2:Withdraw
3:CheckBalance
4:Exit
4
Thank You!!
2.
package [Link];
import [Link];
udaypawar037@[Link]
10
public class Demo {
while(true)
{
[Link]("Enter Choice:");
int choice = [Link]();
switch(choice)
{
case 1:
[Link]("Hai");
break;
case 2:
[Link]("Bye");
break;
case 3:
[Link](0);
default:
[Link]("Invalid Choice");
udaypawar037@[Link]
11
}
[Link]("----------");
o/p:
Enter Choice:
1
Hai
----------
Enter Choice:
2
Bye
----------
Enter Choice:
5
Invalid Choice
----------
Enter Choice:
3
udaypawar037@[Link]
12
Java Notes
udaypawar037@[Link] 1
Java Libraries
1. It is a collection of pre-defined packages.
2. Each package/folder is collection of pre-defined
classes and pre-defined interfaces.
3. Each class or interface is a collection of variables
and methods.
4. All the pre-defined classes and interfaces are present
inside a jar file called as [Link] (rt->runtime) or zip
file -> [Link]
2. Object Class
- Object is a pre-defined class present in [Link]
package.
- Object class is referred as super-most class in java.
- Object class is implicitly inherited by all java
classes.
udaypawar037@[Link] 2
methods present in Object Class
1. protected Object clone()
2. public boolean equals(Object o)
3. public int hashCode()
4. public String toString()
5. public void wait()
6. public void wait(long a)
7. public void wait(long a, int b)
8. public void notify()
9. public void notifyAll()
10. public Class getClass()
11. protected void finalize()
----------------------------------------
1. toString()
syntax : public String toString()
Programs:
1.
package com;
import [Link];
udaypawar037@[Link] 3
import [Link];
2.
package com;
// Up-casting
Object obj = new Car();
}
}
udaypawar037@[Link] 4
public class Person
{
public static void main(String[] args)
{
Person p = new Person();
o/p:
[Link]@15db9742
[Link]@15db9742
[Link]([Link]()); // explicitly
calls toString()
}
udaypawar037@[Link] 5
}
o/p:
Hi Guldu!
Hi Guldu!
5.
package org;
Student(String name) {
[Link] = name;
}
@Override
public String toString() {
return "Name: "+name;
}
[Link](s1);
[Link](s2);
[Link]([Link]());
[Link]([Link]());
}
}
o/p:
udaypawar037@[Link] 6
Name: Tom
Name: Jerry
Name: Tom
Name: Jerry
6.
package org;
int id;
String name;
@Override
public String toString() {
return "Employee Id of "+name+" is "+id;
}
[Link](e1);
[Link](e2);
[Link](e3);
}
}
o/p:
Employee Id of Ambani is 101
Employee Id of Tata is 102
Employee Id of Cook is 103
udaypawar037@[Link] 7
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Storing Objects inside Array
1.
package storingobjects;
Car(String brand)
{
[Link] = brand;
}
udaypawar037@[Link] 2
[Link]("-----------");
[Link]("-----------");
a[0] = 10;
a[1] = 20;
*/
o/p:
[Link]@15db9742
[Link]@6d06d69c
udaypawar037@[Link] 3
-----------
BMW
Audi
-----------
[Link]@15db9742
Brand: BMW
[Link]@6d06d69c
Brand: Audi
2.
package storingobjects;
int age;
String name;
s[0] = s1;
s[1] = s2;
s[2] = s3;
udaypawar037@[Link] 4
for(int i=0; i<[Link]; i++) {
[Link](s[i]);
[Link](s[i].age+" "+s[i].name);
}
}
}
o/p:
[Link]@15db9742
21 Dinga
[Link]@6d06d69c
22 Guldu
[Link]@7852e922
23 Dingi
3.
package storingobjects;
int age;
String name;
@Override
public String toString() {
return "Age: "+age+" Name: "+name;
}
udaypawar037@[Link] 5
Person p3 = new Person(23, "Dingi");
p[0] = p1;
p[1] = p2;
p[2] = p3;
}
}
// p1 p2 p2
// 0 1 2
o/p:
Age: 21 Name: Dinga
Age: 22 Name: Guldu
Age: 23 Name: Dingi
4a.
package storingobjects;
class Laptop {
String brand;
int cost;
String ramSize;
@Override
udaypawar037@[Link] 6
public String toString() {
return "Brand:"+brand+
" Cost:"+cost+
" RAM Size:"+ramSize;
}
4b.
package storingobjects;
class Customer {
/*
int[] a = new int[2];
a[0] = 10;
a[1] = 20;
udaypawar037@[Link] 7
l[2] = l3;
l[3] = l4;
*/
o/p:
Brand:HP Cost:2000 RAM Size:4GB
Brand:Dell Cost:3000 RAM Size:8GB
Brand:Lenovo Cost:7000 RAM Size:16GB
Brand:Acer Cost:2500 RAM Size:2GB
2. hashCode()
***************
syntax : public int hashCode()
5.
package com;
[Link]([Link]());
udaypawar037@[Link] 8
o/p:
366712642
6.
package com;
@Override
public int hashCode() {
return 124;
}
[Link]([Link]());
o/p:
124
udaypawar037@[Link] 9
Java Notes
udaypawar037@[Link] 1
equals()
- equals() is used to compare the content/members of two
objects.
- equals() is used for content comparison.
syntax: public boolean equals(Object obj)
1.
package comparingobjects;
int age;
Student(int age) {
[Link] = age;
}
[Link]([Link](s2)); // false
udaypawar037@[Link] 2
}
2.
package comparingobjects;
int age;
Student(int age) {
[Link] = age;
}
@Override
public boolean equals(Object obj)
{
Student s = (Student) obj;
return [Link] == [Link];
}
udaypawar037@[Link] 3
Student s1 = new Student(20);
Student s2 = new Student(20);
[Link]([Link](s2)); // true
// s1 -> this
// s2 -> obj -> s
o/p:
false
true
3.
package comparingobjects;
udaypawar037@[Link] 4
int id;
double height;
@Override
public boolean equals(Object obj)
{
Employee emp = (Employee) obj;
return [Link] == [Link] && [Link] == [Link];
}
[Link]([Link](e2));
[Link]("---------------------");
udaypawar037@[Link] 5
[Link](new Employee(1, 5.7).equals(new
Employee(1, 5.4)));
[Link]("----------------------");
if([Link](e2)) {
[Link]("Contents are Same");
}
else {
[Link]("Contents are Different");
}
o/p:
false
---------------------
false
----------------------
Contents are Different
udaypawar037@[Link] 6
4a.
package comparingobjects;
public interface A
{
void m1(String a);
}
4b.
package comparingobjects;
public interface B
{
void m1(int a);
}
4c.
package comparingobjects;
@Override
public void m1(int a) {
udaypawar037@[Link] 7
}
@Override
public void m1(String a) {
udaypawar037@[Link] 8
Java Notes
udaypawar037@[Link] 1
Singleton Design Pattern or Singleton Class
- It is a Design Patten wherein we can create only a
single instance or a single object for a class.
_______________________________________________________
1a.
package com;
private Account() {
[Link]("Object Created");
}
udaypawar037@[Link] 2
{
a = new Account();
}
else
{
[Link]("Cannot Create");
}
}
}
1b.
package com;
[Link]();
[Link]();
[Link]();
o/p:
udaypawar037@[Link] 3
Object Created
Cannot Create
Cannot Create
2a.
package singleton;
private AadhaarCard() {
[Link]("AadhaarCard Object Created");
}
2b.
package singleton;
udaypawar037@[Link] 4
public class Person {
[Link]();
[Link]();
[Link]();
[Link]();
o/p:
AadhaarCard Object Created
3a.
package singleton;
udaypawar037@[Link] 5
private static PrimeMinister pm; // pm = null
private PrimeMinister() {
[Link]("PM got Elected");
}
3b.
package singleton;
PrimeMinister pm =
[Link]();
udaypawar037@[Link] 6
[Link]("Name: "+[Link]);
o/p:
PM got Elected
Name: Modi
4a.
package singleton;
private Marriage() {
[Link]("Got Married");
}
udaypawar037@[Link] 7
public static Marriage getInstance() {
if(m == null) {
m = new Marriage();
}
return m;
}
}
4b.
package singleton;
o/p:
udaypawar037@[Link] 8
Got Married
at the age of 29
udaypawar037@[Link] 9
Java Notes
udaypawar037@[Link] 1
String
-> String is pre-defined final class present in [Link]
package.
-> String Objects Immutable in Nature.
-> String is a Collection/Set of Characters.
-> String is also a Non-Primitive Datatype.
-> String implements Serializable, Comparable,
CharSequence
udaypawar037@[Link] 2
1. toString()
2. hashCode()
3. equals()
udaypawar037@[Link] 3
// Converting an Array of Characters to String
String s3 = new String(ch);
[Link](s3);
}
o/p:
dinga
java
--------------------------------------
1.
udaypawar037@[Link] 4
package jspiders;
[Link]("-----------------");
[Link]("-----------------");
[Link]([Link](s2));
}
}
o/p:
udaypawar037@[Link] 5
[Link]@15db9742
[Link]@15db9742
-----------------
1829164700
-----------------
false
2.
package jspiders;
// String s = "java";
[Link]("-----------------");
udaypawar037@[Link] 6
[Link]("-----------------");
[Link]([Link](b));
}
}
o/p:
java
java
-----------------
97
-----------------
true
[Link]([Link]()); // 18
udaypawar037@[Link] 7
[Link]("------------------");
[Link]([Link]());
[Link]("------------------");
[Link]([Link]());
[Link]("------------------");
[Link]([Link]("soft"));
[Link]([Link]("Soft"));
[Link]("------------------");
[Link]([Link]("er"));
[Link]([Link]("Eloper"));
[Link]("------------------");
[Link]([Link]("dev"));
[Link]([Link]("Dev"));
[Link]("------------------");
[Link]([Link](" in TY"));
[Link]("------------------");
// Software Developer
[Link]([Link](2));
[Link]([Link](14));
[Link]("------------------");
[Link]([Link]('t'));
[Link]([Link]('D'));
[Link]([Link]('e'));
[Link]("------------------");
udaypawar037@[Link] 8
String a = "java";
String b = "JavA";
String c = "java";
[Link]([Link](b)); // false
[Link]([Link](c)); // true
[Link]([Link](b));
[Link]("------------------");
[Link]([Link](3)); // lo dinga
[Link]([Link](7)); // inga
[Link]("------------------");
}
}
o/p:
18
------------------
SOFTWARE DEVELOPER
------------------
software developer
------------------
false
true
------------------
true
false
------------------
false
udaypawar037@[Link] 9
true
------------------
Software Developer in TY
------------------
f
o
------------------
3
9
7
------------------
false
true
true
------------------
lo dinga
inga
llo d
o ding
------------------
udaypawar037@[Link]
10
Java Notes
udaypawar037@[Link] 1
Exception Handling
1. Exception is an event or an interruption which
stops the execution of a program ie. abrupt
termination wherein below lines of code will not
get executed.
2. In other words, Exception is a Runtime
Interruption which can be HANDLED.
3. ERROR: Error is also a Runtime
Interruption/Mistake which cannot be HANDLED (We
have to Debug)
- Errors can occur during
i. Compile time -> Compilation error ->
Syntax Mistakes
ii. Runtime -> Runtime Error -> Executing a
class without main()
Exception Hierarchy
udaypawar037@[Link] 2
1. The Process of handling an Exception is called
as Exception Handling.
2. Typically an Exception is Handled using Try
Block and Catch Block.
udaypawar037@[Link] 3
5. There should not be any executable lines of code
between try and catch block.
6. It is always a good practice to handle the
superclass exception as the last catch block.
Programs
1.
package com;
import [Link];
[Link]("start");
udaypawar037@[Link] 4
int b = [Link](); // 0
try
{
[Link](a/b); // 10/0 ->
ArithmeticException
}
catch(ArithmeticException e) // Specific
Exception Handler
{
[Link]("Dabbafellow, do not
divide by 0");
}
[Link]();
[Link]("end");
}
o/p:
start
Enter the value of a:
10
Enter the value of b:
udaypawar037@[Link] 5
0
Dabbafellow, do not divide by 0
end
2.
package com;
[Link]("start");
try {
[Link](a[99]);
}
catch(ArrayIndexOutOfBoundsException e) {
// Specific Exception Handler
[Link]("Invalid Index");
}
[Link]("end");
udaypawar037@[Link] 6
}
o/p:
start
Invalid Index
end
3.
package com;
try {
[Link](10/0); // Object
of ArithmeticException is thrown
}
catch(ArithmeticException e) {
[Link]("Invalid
Denominator");
}
udaypawar037@[Link] 7
}
}
o/p:
Invalid Denominator
/* internally
* 1. An object of ArithmeticException is created
* 2. the object is thrown
* 3. it is caught by the catch block
*/
4.
package com;
try {
[Link](10/0);
}
catch(ArrayIndexOutOfBoundsException e) {
udaypawar037@[Link] 8
[Link]("Invalid Index
Position");
}
catch(NullPointerException e) {
[Link]("Invalid");
}
catch(ArithmeticException e) {
[Link]("Invalid
Denominator");
}
catch(Exception e) {
[Link]("SuperClass
Exception Handler");
}
}
}
o/p:
Invalid Denominator
udaypawar037@[Link] 9
Java Notes
udaypawar037@[Link] 1
Important methods present in Throwable Class:
1. printStackTrace(): This method is used to get
the complete information about the Exception.
finally block
1. The Set of Instructions which has to be executed
all the time has to written within the finally
block.
2. Finally Block is a block of code which gets
executed all the time. ie. irrespective of
exception occurs or not.
syntax:
finally
{
Note:
1. In java we can have nested try and catch block.
2. We can have try and catch block within finally
block as well.
udaypawar037@[Link] 2
1.
package org;
[Link]("start");
try
{
[Link](10/0);
}
catch(Exception e)
{
[Link]();
}
[Link]("end");
}
}
/*
Exception in thread "main"
[Link]: / by zero
udaypawar037@[Link] 3
at [Link]([Link])
*/
o/p:
start
[Link]: / by zero
at [Link]([Link])
end
2.
package org;
[Link]("start");
try
{
[Link](10/0);
}
catch(Exception e)
{
[Link]([Link]());
udaypawar037@[Link] 4
String message = [Link]();
[Link](message);
}
[Link]("end");
}
}
/*
Exception in thread "main"
[Link]: / by zero
at [Link]([Link])
*/
o/p:
start
/ by zero
/ by zero
end
3.
package org;
udaypawar037@[Link] 5
public class FinallyBlockExample {
[Link]("start");
try
{
[Link](10/0);
}
catch(ArithmeticException e)
{
[Link]("Invalid");
}
finally
{
[Link]("Inside Finally
Block");
}
[Link]("end");
}
}
udaypawar037@[Link] 6
o/p:
start
Invalid
Inside Finally Block
end
4.
package org;
try
{
try
{
}
catch (Exception e)
{
}
}
catch (Exception e)
udaypawar037@[Link] 7
{
finally
{
try
{
}
catch (Exception e)
{
}
}
}
}
5.
package org;
udaypawar037@[Link] 8
String s = "java";
char[] c = [Link]();
[Link]();
o/p:
java
avaj
udaypawar037@[Link] 9
Java Notes
throws
udaypawar037@[Link] 1
1. throws is an indication to the caller about the possibility of an
Exception.
2. throws is used to propagate an Exception.
3. throws is generally used with Checked Exceptions.
4. Typically we use throws with methods, and we can use throws
w.r.t Constructors as well.
1.
package jspiders;
public class A {
[Link](10/0);
}
// ArithmeticException -> Unchecked Exception
2.
package jspiders;
public class B {
udaypawar037@[Link] 2
public static void main(String[] args) {
[Link](a[1000]);
}
}
// ArrayIndexOutOfBoundsException -> Unchecked Exception
3.
package jspiders;
public class C {
try
{
udaypawar037@[Link] 3
[Link](2000);
}
catch (InterruptedException e)
{
[Link]();
}
}
}
// InterruptedException -> Checked Exception
4.
package jspiders;
import [Link];
import [Link];
public class D {
try
udaypawar037@[Link] 4
{
FileReader f = new FileReader("[Link]");
}
catch (FileNotFoundException e)
{
[Link]("File Not Found");
}
5.
package jspiders;
udaypawar037@[Link] 5
[Link]("start");
try
{
div();
}
catch (Exception e)
{
[Link]("Handled");
}
[Link]("end");
6.
package jspiders;
udaypawar037@[Link] 6
{
for (int i=1; i<=5; i++)
{
[Link](i);
[Link](3000);
}
}
try {
display();
}
catch (Exception e) {
[Link]();
}
7.
package jspiders;
udaypawar037@[Link] 7
import [Link];
import [Link];
try {
[Link]();
} catch (FileNotFoundException e1) {
[Link]("File not present");
}
}
udaypawar037@[Link] 8
8a.
package example;
8b.
package example;
@Override
public int add(int a, int b) {
return a+b;
}
udaypawar037@[Link] 9
@Override
public int sub(int a, int b) {
return a-b;
}
@Override
public int mul(int a, int b) {
return a*b;
}
@Override
public int div(int a, int b) {
return a/b;
}
8c.
package example;
import [Link];
udaypawar037@[Link]
10
public static void main(String[] args) {
[Link]("===================================
");
while(true) {
[Link]("1:Addition\n2:Subtraction\n3:Multiplicat
ion");
[Link]("4:Division\n5:Exit");
[Link]("Enter Choice:");
int choice = [Link]();
int a = 0;
int b = 0;
switch(choice) {
case 1:
int sum = [Link](a, b);
[Link]("Sum: "+sum);
break;
case 2:
int diff= [Link](a, b);
[Link]("Difference: "+diff);
break;
case 3:
[Link]("Product: "+[Link](a, b));
break;
case 4:
[Link]("Quotient: "+[Link](a, b));
udaypawar037@[Link]
12
break;
case 5:
[Link]("Thank You!!");
[Link](0);
default:
[Link]("Invalid Choice");
}
[Link]("--------------------------------------");
}
}
}
o/p:
---Welcome to Calculator Project---
===================================
1:Addition
2:Subtraction
3:Multiplication
4:Division
5:Exit
udaypawar037@[Link]
13
Enter Choice:
1
enter first number:
20
enter second number:
30
Sum: 50
--------------------------------------
1:Addition
2:Subtraction
3:Multiplication
4:Division
5:Exit
Enter Choice:
2
enter first number:
5
enter second number:
3
Difference: 2
--------------------------------------
1:Addition
2:Subtraction
3:Multiplication
udaypawar037@[Link]
14
4:Division
5:Exit
Enter Choice:
3
enter first number:
4
enter second number:
6
Product: 24
--------------------------------------
1:Addition
2:Subtraction
3:Multiplication
4:Division
5:Exit
Enter Choice:
5
Thank You!!
udaypawar037@[Link]
15
Java Notes
udaypawar037@[Link] 1
Custom Exception or User-Defined Exception
1. Based on the project, it is sometimes necessary to create our
own Exception and those exceptions which the user/Programmer
creates are called as Custom Exception or User-Defined Exception.
throw
1. throw is a keyword in order to invoke an object of Exception.
2. throw is generally used with custom exception.
syntax: throw objectOfExceptionType ;
// throw new ExceptionName();
1a.
package customexception;
udaypawar037@[Link] 2
}
1b.
package customexception;
import [Link];
if([Link]("admin")) {
if(password == 123) {
[Link]("Login Successful");
}
udaypawar037@[Link] 3
else {
try {
// throw new
InvalidPasswordException();
InvalidPasswordException obj = new
InvalidPasswordException();
throw obj;
}
catch(InvalidPasswordException e) {
[Link]("Invalid Password
Entered!!");
}
[Link]();
o/p:
udaypawar037@[Link] 4
Enter User Id:
admin
Enter Password:
126
Invalid Password Entered!!
2a.
package customexception;
2b.
package customexception;
import [Link];
udaypawar037@[Link] 5
int balance = 10000;
if(amount<=balance) {
[Link]("Withdrawal Successful");
}
else
{
try
{
throw new InsufficientBalanceException();
}
catch (InsufficientBalanceException e)
{
[Link]("Not Enough Balance to
Withdraw! :(");
}
}
}
udaypawar037@[Link] 6
o/p:
Enter Amount to be Withdrawn:
15263
Not Enough Balance to Withdraw! :(
3a.
package customexception;
Employee(String name) {
[Link] = name;
}
3b.
udaypawar037@[Link] 7
package customexception;
o/p:
Tom
4a.
package customexception;
AgeInvalidException(String message) {
udaypawar037@[Link] 8
[Link] = message;
}
@Override
public String getMessage() {
return message;
}
4b.
package customexception;
import [Link];
[Link]("Enter Age:");
int age = [Link]();
udaypawar037@[Link] 9
if(age>=21) {
[Link]("Get Married Soon!!!");
}
else
{
try
{
throw new AgeInvalidException("Have
Patience, You are not yet 21!!");
}
catch (Exception e)
{
[Link]([Link]());
}
}
}
}
o/p:
Enter Age:
udaypawar037@[Link]
10
12
Have Patience, You are not yet 21!!
udaypawar037@[Link]
11
1.
package day1;
import [Link];
[Link](l);
[Link]("-------------");
[Link]("-------------");
// [Link]([Link](250)); IndexOutOfBoundsException
[Link]("-------------");
[Link]("-------------");
[Link](l);
[Link](l);
[Link]("-------------");
[Link]([Link]());
[Link]("=========================");
[Link](20);
[Link](10);
[Link](30);
[Link](10);
[Link](30);
[Link](10);
[Link](60);
[Link](x);
[Link]("-------------");
[Link]("-------------");
o/p:
[10, 20.34, 10, null, java]
-------------
5
-------------
10
-------------
true
false
-------------
[10, 20.34, 10, null, java]
[10, 20.34, null, java]
-------------
false
true
=========================
[20, 10, 30, 10, 30, 10, 60]
-------------
2
1
-1
-------------
5
ArrayList LinkedList
-------------------------------------------------------------------------
-
1. PDC in [Link] 1. PDC in [Link]
2. JDK 1.2 2. JDK 1.2
1.
package day2;
import [Link];
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](l);
[Link]("--------------------");
[Link]("--------------------");
[Link]("--------------------");
String y = "java";
[Link]([Link]());
[Link]([Link]());
}
}
o/p:
[10, 20, 30, 40]
--------------------
10
20
30
40
--------------------
40
30
20
10
--------------------
3
4
4
2.
package day2;
import [Link];
import [Link];
[Link](10);
[Link](20);
[Link]("Objects inside ArrayList: "+al+" Size:
"+[Link]());
[Link]("--------------");
/**
* addAll() is used to add all the objects of one collection
into another collection.
*/
[Link](al);
[Link](30);
[Link]("Objects inside LinkedList: "+ll+" Size:
"+[Link]());
}
}
o/p:
Objects inside ArrayList: [10, 20] Size: 2
--------------
Objects inside LinkedList: [10, 20, 30] Size: 3
3.
package day2;
import [Link].*;
[Link]("--------------");
[Link](al);
[Link](30);
[Link]("Objects inside LinkedList: "+ll+" Size:
"+[Link]());
[Link]("-----------------------");
/**
* containsAll() is used to check if all the objects of one
collection is present
* inside another collection or not.
*/
[Link]([Link](al)); // true
[Link](1);
o/p:
Objects inside ArrayList: [10, 20] Size: 2
--------------
Objects inside LinkedList: [10, 20, 30] Size: 3
-----------------------
Objects inside LinkedList: [10, 20, 30] Size: 3
true
Objects inside LinkedList: [10, 30] Size: 2
false
4.
package day2;
import [Link].*;
public class Runner {
[Link](10);
[Link](20);
[Link]("Objects inside ArrayList: "+al+" Size:
"+[Link]());
[Link]("--------------");
[Link](al);
[Link](30);
[Link]("Objects inside LinkedList: "+ll+" Size:
"+[Link]());
o/p:
Objects inside ArrayList: [10, 20] Size: 2
--------------
Objects inside LinkedList: [10, 20, 30] Size: 3
Objects inside LinkedList: [30] Size: 1
5.
package day2;
import [Link];
[Link](10);
[Link](20);
[Link](30);
}
}
o/p:
[10, 20, 30]
[10, 50, 20, 30]
[10, 50, 70, 30]
6.
package day2;
import [Link];
import [Link];
[Link](30);
[Link](40);
[Link](10);
[Link](20);
[Link]("Before Sorting:");
for(int i=0 ;i<[Link](); i++) {
[Link]([Link](i));
}
[Link](l);
[Link]("After Sorting:");
for(int i=0 ;i<[Link](); i++) {
[Link]([Link](i));
}
}
}
o/p:
Before Sorting:
30
40
10
20
After Sorting:
10
20
30
40
1.
package day3;
[Link]("---------");
for(int i : a) {
[Link](i);
}
[Link]("---------");
for(double z : percentage) {
[Link](z);
}
[Link]("---------");
}
}
o/p:
10
20
30
---------
10
20
30
---------
1.2
3.4
5.6
7.8
---------
Apple
Mango
ButterFruit
2.
package day3;
public class BoxingDemo {
[Link](a+" "+b);
[Link]("--------");
[Link](x+" "+y);
[Link]("==============================");
int i = 5;
Integer j = new Integer(i);
[Link](i+" "+j);
[Link]("--------");
char p = 'z';
Character q = new Character(p);
[Link](p+" "+q);
[Link]("=============================");
[Link]("--------");
o/p:
10 10
--------
A A
==============================
5 5
--------
z z
=============================
50 50
--------
5.2 5.2
3.
package day3;
import [Link];
import [Link];
[Link]("20");
[Link]("sql");
[Link]("java");
for(String s : l) {
[Link](s);
}
[Link]("-------------");
[Link](10);
[Link](34);
[Link](67);
for(Integer i : x) { //for(int i : x) {
[Link](i);
}
[Link]("-------------");
[Link](8.99);
[Link](102.34);
[Link](3.45);
for(double j : z) { // for(Double j : z) {
[Link](j);
}
o/p:
20
sql
java
-------------
10
34
67
-------------
8.99
102.34
3.45
4.
package day3;
import [Link];
import [Link];
int a = 10;
char b = 'z';
for(Object o : l) {
[Link](o);
}
[Link]("--------------");
o/p:
10
20.45
z
--------------
10
java
1.2
Programs
1a.
package day4;
int age ;
String name;
1b.
package day4;
import [Link];
[Link](s1);
[Link](s2);
[Link](s3);
for(Student obj : l) {
[Link](obj);
[Link]("Name:"+[Link]+" Age:"+[Link]);
[Link]("-------------------");
}
}
}
o/p:
[Link]@15db9742
Name:Tom Age:21
-------------------
[Link]@6d06d69c
Name:Jerry Age:22
-------------------
[Link]@7852e922
Name:Smith Age:23
-------------------
2a.
package day4;
@Override
public String toString() {
return "Id:"+id+" Name:"+name;
}
2b.
package day4;
import [Link];
[Link](e1);
[Link](e2);
[Link](e3);
[Link]("------");
}
}
o/p:
Id:101 Name:Ambani
Id:102 Name:Cook
Id:103 Name:Sundar
------
Id:101 Name:Ambani
Id:102 Name:Cook
Id:103 Name:Sundar
3.
package day4;
import [Link];
public class Solution {
[Link](10);
[Link](20.45);
[Link]("dinga");
for(Object o : v) {
[Link](o);
}
}
}
o/p:
10
20.45
dinga
4.
package day4;
import [Link];
import [Link];
import [Link];
[Link]("----------------------");
o/p:
[10]
[10, 20]
[10, 20, 30]
----------------------
---------------------------------
Wrapper Class
--------------
- The Non-Primitive version of a Primitive Datatype.
- The Class/Object version of a Primitive Datatype.
- All Wrapper Classes are present inside [Link] package.
- toString() is overridden in all Wrapper Classes and String class.
**********************************************************
**********************************************************
**********************************************************
Generics
--------
Generics are used to specify the element type
jdk 1.5
<ElementType>
*******************************************************
Vector:
ArrayList | LinkedList
---------------------------------------------------
1. PDC in [Link] | 1. PDC in [Link]
2. JDK 1.2 | 2. JDK 1.2
6. 3 Constructors | 6. 2 Constructors
ArrayList | Vector
---------------------------------------------------
1. JDK 1.2 | 1. JDK 1.0
2. IC = (CC*3)/2 +1 | 2. IC = CC*2
3. 3 Constructors | 3. 4 Constructors
-----------------------------------------------------
Constructors
=====================
ArrayList()
ArrayList(int initialCapacity)
ArrayList(Collection c)
------------------------------
LinkedList()
LinkedList(Collection c)
----------------------------
Vector()
Vector(int intialCapacity)
Vector(int intialCapacity, int incrementalCapacity)
Vector(Collection c)
1.
package day5;
import [Link];
[Link](20);
[Link](20.67);
[Link](null);
[Link](20);
[Link]("java");
for(Object obj : h) {
[Link](obj);
}
[Link]("----------");
[Link](h);
[Link]("----------");
[Link]("Size: "+[Link]());
}
}
o/p:
null
java
20
20.67
----------
[null, java, 20, 20.67]
----------
Size: 4
2.
package day5;
import [Link];
[Link]("java");
[Link]("python");
[Link]("java");
[Link]("javascript");
o/p:
java
python
javascript
3.
package day5;
import [Link];
[Link](30);
[Link](40);
[Link](20);
[Link](30);
[Link](50);
[Link](10);
for(int i : t) {
[Link](i);
}
}
}
o/p:
10
20
30
40
50
4.
package day5;
import [Link];
Integer i;
[Link]("Banana");
[Link]("Cat");
[Link]("Apple");
[Link](t);
[Link]("----------");
for(String s : t) {
[Link](s);
}
o/p:
[Apple, Banana, Cat]
----------
Apple
Banana
Cat
5.
package day5;
import [Link];
String a = "A";
String b = "B";
[Link]([Link](b)); // -1
[Link]([Link](a)); // +1
[Link]([Link](b)); // 0
[Link]("--------");
Integer x = 10;
Integer y = 20;
[Link]([Link](y)); // -1
[Link]([Link](x)); // 1
[Link]([Link](x)); // 0
[Link]("-----------");
Double i = 2.4;
Double j = 3.5;
[Link]([Link](j));
[Link]([Link](i));
[Link]([Link](i));
[Link]("--------------");
[Link](10);
[Link]("dinga");
[Link](10.4);
[Link](t);
}
}
o/p:
-1
1
0
--------
-1
1
0
-----------
-1
0
1
--------------
[]
How can we compare User-Defined Object?
--------------------------------------
<<Comparable>>
1a.
package defaultsorting;
int cost;
Car(int cost) {
[Link] = cost;
}
@Override
public String toString() {
return "cost: "+cost;
}
@Override
public int compareTo(Car c) {
return [Link] - [Link];
}
/*
public static void main(String[] args) {
Car c = new Car(100);
[Link](c);
import [Link];
class SortCar {
[Link](c1);
[Link](c2);
[Link](c3);
for(Car c : t) {
[Link](c);
}
}
}
o/p:
cost: 100
cost: 200
cost: 300
2a.
package defaultsorting;
int id;
String name;
@Override
public String toString() {
return id+" "+name;
}
@Override
public int compareTo(Student s) {
return [Link]([Link]);
}
/*@Override
public int compareTo(Student s) {
return [Link] - [Link];
}*/
}
2b.
package defaultsorting;
import [Link];
[Link](s1);
[Link](s2);
[Link](s3);
for(Student obj : t) {
[Link](obj);
}
}
}
o/p:
102 Alex
103 Brian
101 Craig
3a.
package defaultsorting;
int id;
String name;
double salary;
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" +
salary + "]";
}
/*@Override
public int compareTo(Employee e) {
return (int) ([Link] - [Link]); //2.4 - 1.1 ->
1.3 -> Explore -> Tomorrow
}*/
@Override
public int compareTo(Employee e) {
return [Link]([Link]);
}
// @Override
// public int compareTo(Employee e) {
// return [Link] - [Link]; //return [Link] - [Link];
// }
3b.
package defaultsorting;
import [Link];
[Link](e1);
[Link](e2);
[Link](new Employee(4, "Tom", 12.67));
[Link](new Employee(3, "Jerry", 99.41));
for(Employee emp : t) {
[Link](emp);
}
}
}
o/p:
Employee [id=4, name=Tom, salary=12.67]
Employee [id=2, name=John, salary=45.67]
Employee [id=3, name=Jerry, salary=99.41]
Employee [id=1, name=Aaron, salary=62.67]
Comparator
------------
1. Comparator is a pre-defined interface present in [Link] package.
4. Pass The Object of the Class which has the sorting logic to the
constructor of the TreeSet.
1a.
package customsorting;
int age;
String name;
@Override
public String toString() {
return age+" "+name;
}
1b.
package customsorting;
import [Link];
@Override
public int compare(Student x, Student y) {
return [Link] - [Link];
}
1c.
package customsorting;
import [Link];
@Override
public int compare(Student x, Student y) {
return [Link]([Link]);
}
1d.
package customsorting;
import [Link];
[Link](s1);
[Link](s2);
[Link](s3);
for(Student std : t) {
[Link](std);
}
}
}
o/p:
21 A
24 B
20 C
2a.
package customsorting;
Integer id;
String name;
Double salary;
@Override
public String toString() {
return id+" "+name+" "+salary;
}
2b.
package customsorting;
import [Link];
@Override // descending
public int compare(Employee x, Employee y) {
return [Link]([Link]);
}
2c.
package customsorting;
import [Link];
@Override
public int compare(Employee x, Employee y) {
return [Link]([Link]);
}
/*@Override
public int compare(Employee x, Employee y) {
return [Link]([Link]);
}*/
2d.
package customsorting;
import [Link];
@Override
public int compare(Employee x, Employee y) {
return [Link]([Link]);
}
}
2e.
package customsorting;
import [Link];
[Link](e1);
[Link](e2);
[Link](new Employee(20, "Tata", 18.98));
[Link](new Employee(15, "Kotak", 18.34));
for(Employee emp : t) {
[Link](emp);
}
}
}
Map
========
2. Map is used organize the data in terms of key and value pair.
i. Keys cannot be Duplicated
ii. Values can be Duplicated
1. put()
2. get()
3. clear()
4. isEmpty()
5. remove()
6. containsKey()
7. containsValue()
8. keySet()
----------------------------------------------------------------
HashMap
-------
1. Pre-defined class in [Link] package.
2. Jdk 1.2
3. Insertion Order is not Maintained.
4. Underlined Data Structure is HashTable.
----------------------------------------------------------------
LinkedHashMap
-------------
1. Pre-defined class in [Link] package.
2. Jdk 1.4
3. Insertion Order is Maintained.
4. Underlined Data Structure is LinkedList and HashTable.
----------------------------------------------------------------
TreeMap
-------------
1. Pre-defined class in [Link] package.
2. Jdk 1.2
3. Maintains Sorted Order ie.(Sorting based on key in ascending order)
4. Underlined Data Structure is Binary Tree.
----------------------------------------------
HashMap -> JDK 1.2 -> Not Thread Safe(Not Synchronized)
HashTable -> JDK 1.0 -> Thread Safe(Synchronized)
********************************************************
1.
package mapprograms;
import [Link];
[Link](h);
[Link]("-----------");
[Link]("-----------");
[Link]("-----------");
[Link]("-----------");
[Link](h);
[Link](h);
[Link]("-----------");
[Link]([Link]());
[Link]("-----------");
}
}
o/p:
{1.2=100, 10=dinga, guldu=10.45}
-----------
dinga
null
-----------
false
true
-----------
true
false
-----------
{1.2=100, 10=dinga, guldu=10.45}
{1.2=100, guldu=10.45}
-----------
false
true
-----------
2.
package mapprograms;
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("tom", 22);
[Link]("jerry", 21);
[Link]("bheem", 23);
Set<String> s1 = [Link]();
[Link]("-------------------");
[Link](10, "Java");
[Link](20, "Sql");
[Link](30, "Web");
Set<Integer> s = [Link]();
for(int key : s) {
[Link](key+" --> "+[Link](key));
}
[Link]("-------------------");
[Link](20, 1.5);
[Link](30, 2.5);
[Link](10, 4.5);
Set<Integer> s2 = [Link]();
o/p:
bheem is 23 years old
tom is 22 years old
jerry is 21 years old
-------------------
10 --> Java
20 --> Sql
30 --> Web
-------------------
10 : 4.5
20 : 1.5
30 : 2.5
3.
package mapprograms;
import [Link];
import [Link];
[Link]("Mango", 23);
[Link]("Apple", 20);
[Link]("Banana", 15);
Set<String> s = [Link]();
for(String key: s) {
[Link]("Cost of 1Kg "+key+" is
"+[Link](key));
}
}
}
o/p:
Cost of 1Kg Apple is 20
Cost of 1Kg Banana is 15
Cost of 1Kg Mango is 23
4.
package mapprograms;
import [Link];
[Link](1, "Sony");
[Link](h);
[Link](1, "Nokia");
[Link](h);
}
}
o/p:
{1=Sony}
{1=Nokia}
Java allows for the creation of custom exceptions by extending the Exception class or its subclasses like RuntimeException. A custom exception class typically includes a constructor to set up the exception message and overrides the getMessage() method to return the custom message. For example, the 'AgeInvalidException' extends RuntimeException, with a constructor to accept a message indicating invalid age, and the getMessage() method is overridden to return this message. In a main class such as 'MatrimonyPortal', an instance of this exception is thrown if a certain condition (age < 21) is met, catching it and displaying the custom message .
Inheritance in Java is a mechanism where a new class (subclass or child class) acquires the properties and behaviors of an existing class (superclass or parent class). This allows for code reusability and hierarchical classification. Inheritance in Java is achieved using the 'extends' keyword, creating an 'is-a' relationship. Only variables and methods are inherited; constructors and blocks are not inherited .
Java supports generics in collections to allow type safety by specifying the type of elements collections can contain. This is done by using angled brackets with the desired Type when instantiating the collection, such as ArrayList<String> or LinkedList<Integer>. Generics enforce compile-time type checking, preventing potential runtime errors and eliding the need for explicit type casting when retrieving elements. This ensures code reliability and maintainability, as one can ascertain the type of data stored in collections without ambiguity .
In Java, 'this' and 'super' are keywords serving different purposes. The 'this' keyword refers to the current object instance and is used to access instance variables and methods or to call another constructor in the same class. It resolves ambiguity with local variables of the same name and facilitates constructor chaining via 'this()'. Meanwhile, 'super' refers to the parent class instance, allowing access to its variables, methods via 'super.method()' or 'super.variable', and the constructor of the superclass through 'super()' within subclass constructors. 'Super' is essential when overriding variables or methods in case of inheritance, allowing the derived class to invoke the inherited features .
Primitive data types in Java (e.g., int, char) directly hold values, whereas non-primitive types such as wrapper classes (Integer, Character) are objects that store these values. Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes, while unboxing is the reverse process. For example, a primitive integer 'a = 10' and a non-primitive 'Integer b = new Integer(10)' demonstrate autoboxing "int to Integer". Access to object-specific methods (like toString()) is possible only through these wrapper classes. Java provides these mechanisms to facilitate generic programming and collections usage .
ArrayList and LinkedList differ in terms of memory allocation and capacity. ArrayList uses sequential memory allocation and has an initial capacity that grows as needed (initial capacity is 10 with incremental capacity calculated as (current capacity*3/2) + 1). This makes it suitable for random access but less efficient for insertions and deletions. Conversely, LinkedList does not have initial or incremental capacity and uses non-sequential memory allocation via a doubly linked list structure, which makes it efficient for insertions and deletions but slower for random access due to traversal from the head .
Attempting to remove an element from a Java Collection using an invalid index will cause an IndexOutOfBoundsException to be thrown. This occurs because the specified index does not exist within the bounds of the collection. To handle this, one can wrap the removal operation in a try-catch block where the 'catch' part intercepts the IndexOutOfBoundsException. This allows the program to continue execution or take corrective measures such as providing user feedback or adjusting the operation logic .
ArrayLists have better performance than LinkedLists for retrieval operations due to their underlying data structure, which is a resizable array. This allows random access to elements with a time complexity of O(1) as elements can be accessed directly via indices. In contrast, LinkedLists use a doubly-linked list structure, requiring sequential access from the head or tail with a time complexity of O(n) for retrieval, as each node must be traversed sequentially to reach a specified element. This fundamental difference makes ArrayLists more efficient in scenarios where frequent data retrieval is necessary .
Constructor chaining in Java refers to the process of calling one constructor from another constructor within the same class or from a constructor in a base class. This can be achieved in two ways: 1. In the same class, constructor chaining is done using the 'this()' call. 2. In another class (typically a super class), it is done using the 'super()' call. 'Constructor chaining allows for a streamlined and efficient way to initialize an object with multiple constructors, ensuring all necessary initializations and setups are performed. This() or super() must be the first line in the constructor, and recursive chaining is not possible, meaning you can only have 'n-1' calls for 'n' constructors in a class .
The 'this' keyword in Java is used to refer to the current object instance. It becomes particularly useful when there is ambiguity between member variables (also known as global variables) and local variables with the same name. When a local variable has the same name as a member variable, the local variable will dominate within the scope. Therefore, 'this' is used to clarify that you are referring to the member variable of the current object rather than the local variable .









