Java Notes by Uday
Java Notes by Uday
Java Notes by Uday
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 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.
[email protected] 5
Programs
1.
class FirstProgram
{
public static void main(String[] args)
{
System.out.println("Hello World!!");
}
}
o/p:
Hello World!!
2.
class Greet
{
public static void main(String[] args)
{
System.out.println("Welcome to Java Online
Session");
}
}
o/p:
[email protected] 6
Welcome to Java Online Session
1. Arithmetic Operators
a. +
b. –
c. *
d. /
e. %
2. Assignment Operators
a. =
b.+=
c. -=
d.*=
e. /=
f. %=
[email protected] 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
[email protected] 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 */
[email protected] 9
1.
class Student
{
public static void main(String[] args)
{
// Variable Declaration
int age;
// Variable Initialization
age = 20;
System.out.println(age);
System.out.println(name);
System.out.println("--------------");
System.out.println("--------------");
System.out.println(age+name);
System.out.println("--------------");
System.out.println(age+" "+name);
}
}
[email protected]
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;
System.out.println("Sum: "+sum);
System.out.println(a-2);
System.out.println(4*b);
System.out.println(10/5);
System.out.println(10%2);
[email protected]
11
System.out.println("-------------");
/* Assignment Operators */
int x = 10;
System.out.println("value of x = "+x);
x+=20; // x = x+20;
System.out.println("value of x = "+x);
int i = 45;
System.out.println("value of i = "+i);
i -= 13;
System.out.println("value of i = "+i);
System.out.println("-------------");
}
}
o/p:
Sum: 15
3
40
2
0
-------------
value of x = 10
value of x = 30
value of i = 45
value of i = 32
-------------
[email protected]
12
3.
class Demo
{
public static void main(String[] args)
{
/* Comparison Operators */
int x = 10;
int y = 20;
System.out.println(x<y); // true
System.out.println(x<=5); // false
System.out.println("------------");
System.out.println(y>50); // false
System.out.println(y>=20); // true
System.out.println("------------");
System.out.println(x==y); // false
System.out.println(x!=y); // true
System.out.println(x==10); // true
System.out.println(x!=10); // false
System.out.println("=====================");
/* Logical Operators */
int a = 1;
[email protected]
13
int b = 2;
boolean result = a<b && a==1;
System.out.println(result); // true
System.out.println(a<=4 && a==b); // false
System.out.println("------------");
System.out.println("------------");
System.out.println(!true); // false
System.out.println(!false);// true
System.out.println(!(1<2)); // false
System.out.println(!(20<5)); // true
}
}
o/p:
true
false
------------
false
true
------------
false
true
true
false
=====================
true
[email protected]
14
false
------------
true
false
------------
false
true
false
true
4.
class Unary
{
public static void main(String[] args)
{
int x = 5;
System.out.println("x: "+x); // 5
x++;
System.out.println("x: "+x); // 6
x++;
System.out.println("x: "+x); // 7
x--;
System.out.println("x: "+x); // 6
x--;
System.out.println("x: "+x); // 5
System.out.println("===================");
[email protected]
15
int i = 40;
int j = i++; // Post Increment -> First Assign, Then
Increment
System.out.println(i+" "+j); // 41 40
System.out.println("-------------");
int a = 5;
int b = --a; // pre decrement -> first decrement,
then assign
System.out.println(a+" "+b); // 4 4
System.out.println("===================");
/* Ternary Operators */
int p = 10;
int q = 50;
}
}
o/p
x: 5
[email protected]
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
[email protected]
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)
{
System.out.println("start");
int n = 5;
System.out.println("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)
{
System.out.println(a+" is lesser than or equal
to "+b);
}
else
{
[email protected]
18
System.out.println(a+" is greater than "+b);
}
System.out.println("--------------------------");
if(true)
{
System.out.println("Hai Dinga");
}
else
{
System.out.println("Bye Dinga");
}
System.out.println("--------------------------");
if(false)
{
System.out.println("Hai Dinga");
}
else
{
System.out.println("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;
[email protected]
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
{
System.out.println("a is equal to 5");
}
else // inner else
{
System.out.println("a is not equal to
5");
[email protected]
21
}
}
else // outer else
{
System.out.println("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")
{
System.out.println("User Id is Valid");
if(password == 123)
{
[email protected]
22
System.out.println("Password is
Valid");
System.out.println("Login Successful
:)");
}
else
{
System.out.println("Password is
Invalid");
System.out.println("Login Unsuccessful
:(");
}
}
else
{
System.out.println("User Id is Invalid");
System.out.println("Login Unsuccessful :(");
}
}
}
o/p:
User Id is Invalid
Login Unsuccessful :(
3.
class AssignmentPrograms
[email protected]
23
{
public static void main(String[] args)
{
int num = -10;
if(num>0)
{
System.out.println(num+" is a Positive
Number");
}
else
{
System.out.println(num+" is a Negative
Number");
}
System.out.println("-------------");
int n = 215;
int a = 20;
int b = 20;
System.out.println("a:"+a+" b:"+b);
if(a>b)
{
System.out.println("a is Largest");
}
else if(a<b) // b>a
{
System.out.println("b is Largest");
}
else
{
System.out.println("a and b are both
equal");
}
}
}
o/p:
-10 is a Negative Number
-------------
[email protected]
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: System.out.println("In Case-1");
break;
default : System.out.println("Invalid");
[email protected]
26
}
}
}
o/p:
In Case-3
2.
class GradeValidation
{
public static void main(String[] args)
{
char grade = 'C';
switch(grade)
{
case 'A': System.out.println("Excellent ->
Distinction");
break;
[email protected]
27
default: System.out.println("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) {
System.out.println("a is Largest");
}
else {
System.out.println("c is Largest");
[email protected]
28
}
}
else if(b>c)
{
System.out.println("b is Largest");
}
else
{
System.out.println("c is Largest");
}
System.out.println("-------------------");
[email protected]
29
o/p:
a:20 b:150 c:10
b is Largest
-------------------
b is Largest
4.
class Demo
{
public static void main(String[] args)
{
System.out.println("hai");
System.out.print("hai");
System.out.print(" bye"+10);
System.out.println("java");
System.out.print("hai"+" hello");
System.out.print("hai");
System.out.println("bye");
System.out.println("hai");
System.out.println("Good Morning");
System.out.println("Bye");
System.out.println("==============");
System.out.print("hai");
System.out.print("Morning");
[email protected]
30
System.out.print("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')
{
System.out.println("Gender is Male");
[email protected]
31
if(age>=21)
{
System.out.println("Yes, You can get
Married");
}
else
{
System.out.println("Have Patience :)");
}
}
else if(gender == 'F')
{
System.out.println("Gender is Female");
if(age>=18)
{
System.out.println("Yes, You can get
Married");
}
else
{
System.out.println("Have Patience :)");
}
}
else
{
System.out.println("Invalid");
[email protected]
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
{
[email protected]
33
public static void main(String[] args)
{
// Print Hello 5 times
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("-------------");
System.out.println("-------------");
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
System.out.println("-------------");
[email protected]
34
for(int i=1; i<=5; i++)
{
System.out.println(i);
}
}
}
o/p:
Hello
Hello
Hello
Hello
Hello
-------------
Hello
Hello
Hello
Hello
Hello
-------------
1
2
3
4
5
-------------
1
[email protected]
35
2
3
4
5
2.
class ForLoopExample
{
public static void main(String[] args)
{
int n = 5;
int sum = 0;
System.out.println("Sum: "+sum);
System.out.println("---------");
[email protected]
36
System.out.println("---------");
// 5 4 3 2 1
for(int i=5; i>=1; i--)
{
System.out.println(i);
}
System.out.println("---------");
// 2 4 6 8 10
for(int i=2; i<=10; i=i+2)
{
System.out.println(i);
}
System.out.println("---------");
// 1 3 5 7 9
for(int i=1; i<=9; i+=2)
{
System.out.println(i);
}
System.out.println("---------");
[email protected]
37
for(int i=2; i<=10; i+=2)
{
System.out.print(i+" ");
}
}
}
o/p:
Sum: 15
---------
146
147
148
149
150
---------
5
4
3
2
1
---------
2
4
6
8
[email protected]
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.
[email protected]
39
1.
class WhileLoopDemo
{
public static void main(String[] args)
{
int n = 1;
while(n<=5)
{
System.out.println(n);
n++;
}
System.out.println("--------------");
int x = 1;
do
{
System.out.println(x);
x++;
}
while(x<=5);
System.out.println("--------------");
int i = 5;;
while(i>=1)
{
[email protected]
40
System.out.println(i);
i--;
}
System.out.println("--------------");
int j = 5;
do
{
System.out.println(j);
j--;
}
while(j>=1);
}
}
o/p:
1
2
3
4
5
--------------
1
2
3
[email protected]
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++)
{
System.out.println("i:"+i + " j:"+j);
}
System.out.println("--------");
[email protected]
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
--------
* * * * *
* * * * *
* * * * *
* * * * *
[email protected]
43
* * * * *
[email protected]
44
Java Notes
[email protected] 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.
[email protected] 2
1.
/*
Accessing Non-Static Variables inside same class
*/
class Student
{
// NON-STATIC VARIABLES
int age = 20;
String name = "Dinga";
System.out.println(s.age);
System.out.println(s.name);
System.out.println("------------------------
-");
System.out.println("Age: "+s.age);
System.out.println("Name: "+s.name);
System.out.println("------------------------
-");
System.out.println(s.name+" is "+s.age+"
years old");
System.out.println("*****");
System.out.println("end");
}
}
o/p
[email protected] 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();
System.out.println(emp.id);
System.out.println(emp.name);
System.out.println(emp.salary);
}
}
o/p:
101
[email protected] 4
Tom
123.45
[email protected] 5
Java Notes
[email protected] 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;
[email protected] 2
String e;
System.out.println(dvd.a);
System.out.println(dvd.b);
System.out.println(dvd.c);
System.out.println(dvd.d);
System.out.println(dvd.e);
}
}
o/p:
0
0.0
2.
package com;
class Car {
System.out.println(c1.cost+"
"+c2.cost);
[email protected] 3
c1.cost = 15;
c2.cost = 23;
System.out.println(c1.cost+"
"+c2.cost);
}
}
o/p:
10 10
15 23
3.
package com;
class Student {
String name;
int marks;
System.out.println(s1.name+"
"+s1.marks);
System.out.println(s2.name+"
"+s1.marks);
System.out.println("-------------------
");
[email protected] 4
s1.name = "Tom";
s1.marks = 36;
s2.name = "Jerry";
s2.marks = 40;
System.out.println(s1.name+"
"+s1.marks);
System.out.println(s2.name+"
"+s2.marks);
System.out.println("-------------------
");
}
}
o/p:
null 0
null 0
-------------------
Tom 36
Jerry 40
-------------------
Tom has scored 36 marks in Java
Jerry has scored 40 marks in Java
[email protected] 5
Java Notes
[email protected] 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.
[email protected] 2
1.
package com;
class Demo {
System.out.println("start");
System.out.println("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)
{
System.out.println("Sum of "+a+" & "+b+" is "+ (a+b) );
/* int sum = a+b;
System.out.println("Sum of "+a+" & "+b+" is "+sum);
System.out.println(a+b); */
}
[email protected] 3
obj.add(10, 20);
obj.add(6, 3);
obj.add(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;
}
System.out.println("start");
System.out.println(t.display());
System.out.println("end");
}
}
o/p:
start
10
10
end
[email protected] 4
4.
package com;
class Example
{
/* Method with Arguments and with return statement */
int findSquare(int n)
{
return n*n;
}
System.out.println(e.findSquare(4));
}
}
o/p:
25
16
5a.
package com;
class Solution {
5b.
package com;
s.m1();
System.out.println("------------");
s.m2("john", 25);
System.out.println("------------");
System.out.println(s.m3());
System.out.println("------------");
System.out.println(s.m4(12, 78));
}
}
o/p:
Learning Methods
------------
Name: john Age:25
------------
Jspiders
Jspiders
------------
9
90
[email protected] 6
6.
package com;
int m1()
{
return 10+10;
}
double m2()
{
return 10+10.7;
}
String m3()
{
return "hai"+10;
}
String a = "java";
}
[email protected] 7
Java Notes
[email protected] 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 java.util package.
2. Scanner class is used to accept dynamic input from the
User.
[email protected] 2
2. Pass System.in to the Constructor call.
syntax: Scanner scan = new Scanner(System.in);
1. byte - nextByte()
2. short - nextShort()
3. int - nextInt()
4. long - nextLong()
5. float - nextFloat()
6. double - nextDouble()
7. boolean - nextBoolean()
1a.
package com;
[email protected] 3
public class MethodOverloading {
void display() {
System.out.println("Hello DabbaFellow");
}
void display(int x) {
System.out.println(x);
}
void display(double x) {
System.out.println(x);
}
1b.
package com;
[email protected] 4
public static void main(String[] args) {
mol.display(45);
mol.display(12, "java");
mol.display(45.65);
mol.display();
mol.display("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;
[email protected] 6
import java.util.Scanner;
System.out.println(a+b);
scan.close();
o/p:
Enter the value of a:
5
Enter the value of b:
20
25
[email protected] 7
4.
package com;
import java.util.Scanner;
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Name:");
String name = s.next();
System.out.println("Enter Salary:");
double salary = s.nextDouble();
System.out.println("-----------------");
System.out.println("Age:"+age+"\nName:"+name+"\nSalar
y:"+salary);
o/p:
Enter Age:
25
Enter Name:
John
Enter Salary:
1200.35
-----------------
Age:25
Name:John
Salary:1200.35
5.
package com;
import java.util.Scanner;
[email protected] 9
public static void main(String[] args) {
s.add(a, b);
System.out.println("----------------");
}
}
}
o/p:
Enter First Number:
2
Enter Second Number:
3
Sum of 2 and 3 is 5
[email protected]
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
----------------
[email protected]
11
Java Notes
[email protected] 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;
[email protected] 2
static void study()
{
System.out.println("Student is Studying");
}
System.out.println("------------");
System.out.println(age); //
ClassName.variableName -> ClassName.age -> Student.age
study(); // ClassName.methodName() ->
ClassName.study() -> Student.study()
}
}
o/p:
20
Student is Studying
------------
20
Student is Studying
[email protected] 3
2a.
package com;
class Employee {
2b.
package com;
System.out.println(Employee.id);
Employee.work();
// System.out.println(id); Test.id
// work(); Test.work();
}
[email protected] 4
}
o/p:
101
Employee is Working
3.
package com;
System.out.println(cost); // Car.cost
System.out.println(cost); // Car.cost
System.out.println("------------------");
[email protected] 5
System.out.println(c1.cost); // not a good
practice
}
}
o/p:
10
20
------------------
20
4a.
package com;
void checkEvenOrOdd(int n) {
if(n%2 == 0)
{
System.out.println(n+" is a Even Number");
}
else
{
System.out.println(n+" is a Odd Number");
}
4b.
package com;
import java.util.Scanner;
d.checkEvenOrOdd(num);
System.out.println("--------");
}
scan.close();
}
[email protected] 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
--------
[email protected] 8
Java Notes
[email protected] 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;
[email protected] 2
System.out.println("In Static Block-1");
}
static
{
System.out.println("In Static Block-2");
}
static
{
System.out.println("In Static Block-3");
}
}
o/p:
In Static Block-1
In Static Block-2
In Static Block-3
Hello
2.
package jspiders;
[email protected] 3
public class Student
{
static int age;
static
{
age = 10; // Student.age = 10;
}
static
{
Student.age = 20; // age = 20;
}
}
o/p:
Age: 20
[email protected] 4
syntax:
{
3.
package jspiders;
{
System.out.println("In Non-Static Block-2");
}
[email protected] 5
System.out.println("End");
}
{
System.out.println("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;
}
[email protected] 6
public static void main(String[] args)
{
Employee e = new Employee();
System.out.println("ID: "+e.id);
}
{
id = 20;
}
// id = 0 -> 10 -> 20
o/p:
ID: 20
5.
package jspiders;
[email protected] 7
public static void main(String[] args)
{
Car c = new Car();
System.out.println(3);
}
{
System.out.println(2);
}
}
o/p:
1
2
3
6.
package jspiders;
static
{
x = 20;
}
[email protected] 8
public static void main(String[] args)
{
Pen p = new Pen();
System.out.println(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.
[email protected] 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
[email protected]
11
Java Notes
[email protected] 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.
[email protected] 2
2. They are further categorized into 2 types:
i. Non-Parameterized Custom Constructor
ii. Parameterized Custom Constructor
[email protected] 3
*******************PROGRAMS*******************
1a.
package com;
class Car
{
// Non-Parameterized Custom Constructor
Car()
{
System.out.println("Hello");
}
System.out.println("end");
}
}
o/p:
start
Hello
end
[email protected] 4
2.
package com;
class Bike
{
// Parameterized Custom Constructor
Bike(int cost) // cost=1000
{
System.out.println("Cost: "+cost);
}
o/p:
Cost: 1000
3.
package com;
}
*/
public static void main(String[] args)
{
Pen p = new Pen();
}
}
4.
package com;
class Student
{
int age;
Student(int a)
{
age = a;
}
[email protected] 6
System.out.println("Age: "+s1.age);
System.out.println("Age: "+s2.age);
}
}
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
System.out.println(height);
System.out.println(this.height);
}
[email protected] 7
Kangaroo k = new Kangaroo();
k.display();
}
}
o/p:
4.4
5.5
6.
package com;
class Person {
int age;
String name;
[email protected] 8
System.out.println("Name: "+p1.name+" Age:
"+p1.age);
System.out.println("Name: "+p2.name+" Age:
"+p2.age);
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();
System.out.println(v.x);
[email protected] 9
}
}
o/p:
10
[email protected]
10
Java Notes
[email protected] 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.
[email protected] 2
package singlelevel;
1c.
package singlelevel;
System.out.println(s.age);
System.out.println(s.name);
o/p:
40
Tom
[email protected] 3
2a.
package multilevel;
void conductExams() {
System.out.println("VTU is conducting Exams");
}
2b.
package multilevel;
void providePlacements() {
System.out.println("Jspiders Provides
Placement");
}
[email protected] 4
2c.
package multilevel;
void fest() {
System.out.println("CS Department had a Fest
called as Equinox");
}
2d.
package multilevel;
System.out.println("University Name:
"+d.universityName);
System.out.println("College Name:
"+d.collegeName);
[email protected] 5
System.out.println("Department Name:
"+d.departmentName);
System.out.println("-----------------");
d.conductExams();
d.fest();
d.providePlacements();
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;
3b.
package hierarchical;
void start() {
System.out.println("Car Started");
}
3c.
package hierarchical;
void stop() {
System.out.println("Bike Stopped");
}
3d.
package hierarchical;
System.out.println("--------");
}
}
o/p:
BMW 45000
Car Started
--------
BMW Petrol
Bike Stopped
[email protected] 8
Java Notes
[email protected] 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;
[email protected] 2
public static void main(String[] args) {
System.out.println("Employee Details");
System.out.println("==========================");
System.out.println("-------------------");
}
}
2.
package com;
[email protected] 3
int id;
String name;
double salary;
void display() {
System.out.println("Employee Id: "+this.id);
System.out.println("Employee Name: "+this.name);
System.out.println("Employee Salary: "+salary);
// this.salary
}
System.out.println("Employee Details");
System.out.println("==========================");
e1.display();
[email protected] 4
System.out.println("-------------------");
e2.display();
}
}
3.
package com;
[email protected] 5
Vehicle(String brand) {
System.out.println("Brand: "+brand);
}
Vehicle() {
System.out.println("No Argument Constructor");
}
new Vehicle();
Vehicle obj = new Vehicle();
[email protected] 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: super.variableName or super.methodName()
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;
System.out.println(age); // 10
System.out.println(this.age); // 30
System.out.println(super.age); // 50
}
}
4c.
package org;
[email protected] 8
s.display();
o/p:
10
30
50
[email protected] 9
Java Notes
[email protected] 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;
[email protected] 2
Demo()
{
System.out.println(2);
}
System.out.println("END");
}
}
o/p:
START
2
1
END
2.
package chaining;
[email protected] 3
Student(int age) // age = 22
{
this("Tom");
System.out.println("Age: "+age);
}
o/p:
Name: Tom
Age: 22
Height: 5.8
[email protected] 4
3.
// Recursive Chaining
package chaining;
Car(String brand)
{
// this(500);
}
Car(int cost)
{
// this("bmw");
}
4.
package chaining;
[email protected] 5
public class Employee {
o/p:
101
Dinga
[email protected] 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()
{
System.out.println(1);
}
}
1b.
package com;
[email protected] 7
System.out.println(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;
[email protected] 8
class Father
{
Father(int a)
{
System.out.println(1);
}
}
1b.
package com;
1c.
package com;
o/p:
1
2
2a.
package com;
class Vehicle
{
Vehicle(String brand)
{
System.out.println("brand: "+brand);
}
}
2b.
package com;
[email protected]
10
2c.
package com;
}
}
o/p:
brand: BMW
cost: 200
[email protected]
11
Java Notes
[email protected] 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()
{
System.out.println("Old Fashioned Father's
Bike!");
[email protected] 2
}
}
1b.
package com;
o/p:
New Modified Son's Bike
[email protected] 3
2a.
package com;
void start() {
System.out.println("Vehicle Started");
}
2b.
package com;
@Override
void start()
{
super.start();
System.out.println("Car Started");
super.start();
}
[email protected] 4
2c.
package com;
c.start();
o/p:
Vehicle Started
Car Started
Vehicle Started
3a.
package com;
[email protected] 5
public class WhatsApp1 {
void display() {
System.out.println("Single Ticks
Supported");
}
3b.
package com;
@Override
void display() {
super.display();
System.out.println("Double Ticks
Supported");
}
void call() {
System.out.println("Voice Call Supported");
}
}
[email protected] 6
3c.
package com;
@Override
void display() {
super.display();
System.out.println("Blue Ticks Supported");
}
@Override
void call() {
super.call();
System.out.println("Video Call Supported");
}
void story() {
System.out.println("Can Upload Images as
Story");
}
[email protected] 7
3d.
package com;
w3.display();
System.out.println("-----------------");
w3.call();
System.out.println("-----------------");
w3.story();
o/p:
[email protected] 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()
{
System.out.println("Old Fashioned Father's
Bike!");
}
}
5b.
[email protected]
10
package com;
6a.
package com;
6b.
package com;
// Error
[email protected]
12
Java Notes
[email protected] 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];
System.out.println("-------");
/* Array Initialization */
a[0] = 10;
a[1] = 20;
a[2] = 40;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println("==============");
[email protected] 2
// Array Declaration and Creation
double[] x = new double[4];
System.out.println(x[0]);
System.out.println(x[1]);
System.out.println(x[2]);
System.out.println(x[3]);
System.out.println("-------");
x[0] = 1.2;
x[1] = 3.4;
x[2] = 5.6;
x[3] = 7.8;
System.out.println(x[0]);
System.out.println(x[1]);
System.out.println(x[2]);
System.out.println(x[3]);
System.out.println("Length: "+x.length);
}
o/p:
0
0
0
-------
10
20
40
==============
0.0
0.0
0.0
0.0
-------
[email protected] 3
1.2
3.4
5.6
7.8
Length: 4
2.
package com;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println("------");
System.out.println("------");
System.out.println("======================");
int sum = 0;
[email protected] 4
for(int i=0; i<data.length; i++)
{
sum = sum + data[i]; // sum += data[i];
}
System.out.println("Sum: "+sum);
}
}
o/p:
10
20
30
------
10
20
30
------
30
20
10
======================
Sum: 150
Average: 30
[email protected] 5
Java Notes
[email protected] 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 com.google.gmail;
class Inbox {
[email protected] 2
[email protected] 3
[email protected] 4
1.
package com;
public Person() {
System.out.println("In Person Class Constructor");
}
}
}
o/p:
In Person Class Constructor
20
Person is Eating
[email protected] 5
2a.
package com;
public Person() {
System.out.println("In Person Class Constructor");
}
2b.
package com;
[email protected] 6
System.out.println(p.age);
p.eat();
o/p:
In Person Class Constructor
20
Person is Eating
3a.
package com;
public Person() {
System.out.println("In Person Class Constructor");
}
3b.
package org;
import com.Person;
o/p:
In Person Class Constructor
20
Person is Eating
4.
package com;
[email protected] 8
/* Accessing Private Members In Same Class Same Package */
o/p:
2000
Chatting
5a.
package com;
[email protected] 9
public class Mobile {
5b. ERROR
package com;
}
}
--------------------------------------------------------
6.
package com;
[email protected]
10
/* Accessing default Members In Same Class */
class Television {
Television() {
System.out.println("In Constructor");
}
void watchMovie() {
System.out.println("Watching Movie");
}
o/p:
In Constructor
Sony
Watching Movie
[email protected]
11
7a.
package com;
class Television {
Television() {
System.out.println("In Constructor");
}
void watchMovie() {
System.out.println("Watching Movie");
}
7b.
package com;
class User {
[email protected]
12
}
o/p:
In Constructor
Sony
Watching Movie
8a.
package com;
class Television {
Television() {
System.out.println("In Constructor");
}
void watchMovie() {
System.out.println("Watching Movie");
}
[email protected]
13
8b. ERROR
package org;
// import com.Television;
------------------------------------------
9.
package com;
protected Television() {
System.out.println("In Television Constructor");
}
[email protected]
14
System.out.println("Watching Movie");
}
}
}
o/p:
In Television Constructor
LG
Watching Movie
9a.
package com;
protected Television() {
System.out.println("In Television Constructor");
}
[email protected]
15
protected void watchMovie() {
System.out.println("Watching Movie");
}
}
9b.
package com;
class User {
o/p:
In Television Constructor
LG
Watching Movie
10a.
package com;
[email protected]
16
/* Accessing Protected Members in Different class Different Package
*/
10b.
package org;
import com.Father;
o/p:
50
[email protected]
17
Java Notes
[email protected] 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 com.javabean;
p.setAge(25);
System.out.println(p.getAge());
/*System.out.println(p.age);
p.age = 20;*/
o/p:
Age: 25
25
2a.
package com.javabean;
[email protected] 3
public class Employee {
2b.
package com.javabean;
System.out.println(emp.getName()+"
"+emp.getId());
System.out.println("-----------------");
[email protected] 4
emp.setId(101);
System.out.println("Name: "+emp.getName());
System.out.println("Id: "+emp.getId());
o/p:
null 0
-----------------
Name: Tom
Id: 101
3a.
package com.javabean;
if(age>0) {
System.out.println("Age Initialized");
this.age = age;
}
else {
System.out.println("Age Cannot be
Initialized");
}
3b.
package com.javabean;
import java.util.Scanner;
System.out.println("Enter Age:");
int age = scan.nextInt();
s.setAge(age);
System.out.println(s.getAge());
}
}
o/p:
Enter Age:
25
Age Initialized
25
4a.
package com.javabean;
[email protected] 6
if(cost>0) {
this.cost = cost;
}
}
4b.
package com.javabean;
System.out.println("Cost: "+c.getCost());
c.setCost(200);
System.out.println("Cost: "+c.getCost());
c.setCost(300);
System.out.println("Cost: "+c.getCost());
}
}
o/p:
Cost: 100
Cost: 200
Cost: 300
[email protected] 7
Java Notes
[email protected] 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;
System.out.println("---Widening---");
[email protected] 2
int a = 10;
double b = a;
System.out.println(a+" "+b);
char c = 'a';
int d = c;
System.out.println(c+" "+d);
System.out.println("---Narrowing---");
double x = 3.45;
int y = (int) x;
System.out.println(x+" "+y);
int p = 66;
char q = (char)p;
System.out.println(p+" "+q);
System.out.println("==============");
System.out.println("A"+"B");
System.out.println("A"+20);
System.out.println('A'+'B');
[email protected] 3
System.out.println('a'+20);
System.out.println('a'+"a");
}
}
o/p:
---Widening---
10 10.0
a 97
---Narrowing---
3.45 3
66 B
==============
AB
A20
131
117
aa
2.
[email protected] 4
package primitivecasting;
System.out.println(10); // int
System.out.println(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;
System.out.println("--------------------");
o/p:
10
10.5
--------------------
3.
package primitivecasting;
import java.util.Scanner;
System.out.println("Enter No of Elements to be
Inserted:");
int size = scan.nextInt();
int count = 0;
System.out.println("No of Occurences of
"+element+" is "+count);
}
}
[email protected] 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
[email protected] 8
Java Notes
[email protected] 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();
System.out.println(f.age); //f.name will give
error
/* DOWNCASTING */
Son s = (Son) f;
System.out.println(s.age+" "+s.name);
o/p:
45
[email protected] 3
45 Dinga
2a.
package nonprimitive;
void start() {
System.out.println("Vehicle Started");
}
}
2b.
package nonprimitive;
void stop() {
System.out.println("Car Stopped");
}
2c.
package nonprimitive;
[email protected] 4
System.out.println("-------------");
Car c = (Car) v;
System.out.println(c.brand+" "+c.fuel);
c.start();
c.stop();
o/p:
BMW
Vehicle Started
-------------
BMW Petrol
Vehicle Started
Car Stopped
[email protected] 5
Java Notes
[email protected] 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;
[email protected] 2
public class Son extends Father
{
int y = 20;
}
1c.
package org;
1d.
package org;
Father obj;
obj = new Son();
[email protected] 3
{
System.out.println("Downcasting to Son");
Son s = (Son) obj;
System.out.println(s.x+" "+s.y);
}
else if(obj instanceof Daughter)
{
System.out.println("Downcasting to
Daughter");
Daughter d = (Daughter) obj;
System.out.println(d.x+" "+d.z);
}
}
}
/*
Father f = new Son();
Daughter s = (Daughter) f;
o/p:
Downcasting to Son
30 20
[email protected] 4
1e.
package org;
System.out.println("--------");
System.out.println("--------");
[email protected] 5
System.out.println("--------");
}
}
o/p:
true
true
--------
true
true
--------
true
false
false
--------
true
true
2a
[email protected] 6
package org;
2b.
package org;
2c.
package org;
2d.
package org;
[email protected] 7
public static void main(String[] args) {
}
}
o/p:
Brand: Suzuki Fuel: Diesel
3a.
package org;
[email protected] 8
public class Food {
3b.
package org;
3c.
package org;
3d.
package org;
3e.
package org;
[email protected] 9
public class KFC {
3f.
package org;
[email protected]
10
public class Customer {
}
}
o/p:
Eating Sandwich
[email protected]
11
4a.
package org;
4b.
package org;
4c.
package org;
4d.
package org;
[email protected]
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)
[email protected]
13
{
Tea t = new Tea();
return t;
}
else
{
return null;
}
}
*/
4e.
package org;
import java.util.Scanner;
System.out.println("Enter Choice:");
System.out.println("1:Coffee\n2:Tea");
int choice = scan.nextInt();
[email protected]
14
Beverage obj = c.vendingMachine(choice);
o/p:
Enter Choice:
1:Coffee
2:Tea
1
Drinking Coffee
[email protected]
15
Java Notes
[email protected] 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;
[email protected] 2
public class Myntra {
[email protected] 3
System.out.println("Cost: "+cost+" Product:
"+product);
}
1b.
package compiletime;
m.purchase("GooglePay");
m.purchase(2500);
m.purchase("Shoe", 3000);
m.purchase(15000, "Mobile");
m.purchase("Adidas", "T-Shirt");
}
}
o/p:
Payment Gateway: GooglePay
Cost: Rs.2500
[email protected] 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() {
[email protected] 5
System.out.println("Working");
}
1b.
package runtime;
@Override
void work() {
System.out.println("Developer is "
+ "developing an application");
}
1c.
package runtime;
@Override
void work() {
System.out.println("Tester is "
+ "testing an application");
1d.
package runtime;
}
}
o/p:
Developer is developing an application
Tester is testing an application
2a.
package compiletime;
[email protected] 7
public class Vehicle
{
void start()
{
System.out.println("Vehicle Started");
}
}
2b.
package compiletime;
2c.
package compiletime;
@Override
void start() { // 2
[email protected] 8
System.out.println("Bike Started");
}
2d.
package compiletime;
o/p:
Car Started
Bike Started
2e.
package compiletime;
[email protected] 9
void invokeStart(Vehicle v) // Vehicle obj = new
Car(); -> Vehicle obj = new Bike();
{
v.start();
}
d.invokeStart(new Car());
d.invokeStart(new Bike());
}
o/p:
Car Started
Bike Started
eg:
package runtime;
System.out.println("-------------");
[email protected]
11
Java Notes
[email protected] 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.
--------------------------------------------------
[email protected] 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() {
System.out.println("Working");
}
[email protected] 3
e.work();
}
o/p:
Working
2a.
package com;
void shiftGears() {
System.out.println("Shifting Gears!");
}
2b.
package com;
@Override
[email protected] 4
void stop() {
System.out.println("Car Stopped");
}
@Override
void start() {
System.out.println("Car Started");
}
o/p:
Car Started
Shifting Gears!
Car Stopped
[email protected] 5
{
System.out.println(1);
}
}
1b.
package org;
1c.
package org;
o/p:
1
2
2a.
package org;
2b.
package org;
[email protected] 7
}
}
2c.
package org;
o/p:
1
2
[email protected] 8
Java Notes
[email protected] 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
{
[email protected] 2
Programs
1a.
package org;
1b.
package org;
@Override
public void eat() {
System.out.println("Eating");
}
System.out.println(Person.id);
[email protected] 3
d.eat();
o/p:
101
Eating
2a.
package org;
2b.
package org;
2c.
[email protected] 4
package org;
@Override
public void deposit() {
System.out.println("Depositing Amount");
}
@Override
public void withdraw() {
System.out.println("Withdrawing Amount");
}
}
}
o/p:
Depositing Amount
Withdrawing Amount
3a.
[email protected] 5
package org;
void devlop();
3b.
package org;
void test();
3c.
package org;
void work() {
System.out.println("Working");
}
}
[email protected] 6
3d.
package org;
@Override
public void devlop() {
System.out.println("Developing");
}
@Override
public void test() {
System.out.println("Testing");
}
3e.
package org;
u.devlop();
[email protected] 7
u.test();
u.work();
}
}
o/p:
Developing
Testing
Working
[email protected] 8
Java Notes
[email protected] 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();
}*/
[email protected] 2
1b.
package com;
@Override
public void work() {
System.out.println("Employee is Working");
}
1c.
package com;
o/p:
Employee is Working
2a.
package org.bankapp;
2b.
package org.bankapp;
@Override
public void deposit(int amount) {
System.out.println("Depositing Rs."+amount);
[email protected] 4
balance = balance + amount;
System.out.println("Amount Deposited
Successfully");
}
@Override
public void withdraw(int amount) {
System.out.println("Withdrawing Rs."+amount);
balance -= amount; // balance = balance - amount;
System.out.println("Amount Withdrawn
Successfully");
}
@Override
public void checkBalance() {
System.out.println("Available Balance:
Rs."+balance);
}
2c.
package org.bankapp;
[email protected] 5
Bank obj = new ATM();
obj.checkBalance();
System.out.println("------------------");
obj.deposit(5000);
obj.checkBalance();
System.out.println("------------------");
obj.withdraw(4500);
obj.checkBalance();
o/p:
Available Balance: Rs.10000
------------------
Depositing Rs.5000
Amount Deposited Successfully
Available Balance: Rs.15000
------------------
Withdrawing Rs.4500
Amount Withdrawn Successfully
[email protected] 6
Available Balance: Rs.10500
2d.
package org.bankapp;
import java.util.Scanner;
while(true)
{
System.out.println("Enter Choice");
System.out.println("1:Deposit\n2:Withdraw\n3:CheckBal
ance\n4:Exit");
int choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter Amount to be
Deposited:");
[email protected] 7
int amount = scan.nextInt();
b.deposit(amount);
break;
case 2:
System.out.println("Enter Amount to be
Withdrawn:");
int amt = scan.nextInt();
b.withdraw(amt);
// b.withdraw(scan.nextInt());
break;
case 3:
b.checkBalance();
break;
case 4:
System.out.println("Thank You!!");
System.exit(0);
default:
System.out.println("Invalid Choice");
}
System.out.println("---------------------");
}
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
[email protected] 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 org.bankapp;
import java.util.Scanner;
[email protected]
10
public class Demo {
while(true)
{
System.out.println("Enter Choice:");
int choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Hai");
break;
case 2:
System.out.println("Bye");
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid Choice");
[email protected]
11
}
System.out.println("----------");
o/p:
Enter Choice:
1
Hai
----------
Enter Choice:
2
Bye
----------
Enter Choice:
5
Invalid Choice
----------
Enter Choice:
3
[email protected]
12
Java Notes
[email protected] 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 rt.jar (rt->runtime) or zip
file -> src.zip
2. Object Class
- Object is a pre-defined class present in java.lang
package.
- Object class is referred as super-most class in java.
- Object class is implicitly inherited by all java
classes.
[email protected] 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 java.util.Scanner;
[email protected] 3
import java.util.ArrayList;
2.
package com;
// Up-casting
Object obj = new Car();
}
}
[email protected] 4
public class Person
{
public static void main(String[] args)
{
Person p = new Person();
o/p:
com.Person@15db9742
com.Person@15db9742
System.out.println(p.toString()); // explicitly
calls toString()
}
o/p:
Hi Guldu!
Hi Guldu!
5.
package org;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return "Name: "+name;
}
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
o/p:
[email protected] 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;
}
System.out.println(e1);
System.out.println(e2);
System.out.println(e3);
}
}
o/p:
Employee Id of Ambani is 101
Employee Id of Tata is 102
Employee Id of Cook is 103
[email protected] 7
[email protected] 8
Java Notes
[email protected] 1
Storing Objects inside Array
1.
package storingobjects;
Car(String brand)
{
this.brand = brand;
}
[email protected] 2
System.out.println("-----------");
System.out.println("-----------");
a[0] = 10;
a[1] = 20;
*/
o/p:
storingobjects.Car@15db9742
storingobjects.Car@6d06d69c
[email protected] 3
-----------
BMW
Audi
-----------
storingobjects.Car@15db9742
Brand: BMW
storingobjects.Car@6d06d69c
Brand: Audi
2.
package storingobjects;
int age;
String name;
s[0] = s1;
s[1] = s2;
s[2] = s3;
[email protected] 4
for(int i=0; i<s.length; i++) {
System.out.println(s[i]);
System.out.println(s[i].age+" "+s[i].name);
}
}
}
o/p:
storingobjects.Student@15db9742
21 Dinga
storingobjects.Student@6d06d69c
22 Guldu
storingobjects.Student@7852e922
23 Dingi
3.
package storingobjects;
int age;
String name;
@Override
public String toString() {
return "Age: "+age+" Name: "+name;
}
[email protected] 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
[email protected] 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;
[email protected] 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;
System.out.println(e.hashCode());
[email protected] 8
o/p:
366712642
6.
package com;
@Override
public int hashCode() {
return 124;
}
System.out.println(e.hashCode());
o/p:
124
[email protected] 9
Java Notes
[email protected] 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) {
this.age = age;
}
System.out.println(s1.equals(s2)); // false
2.
package comparingobjects;
int age;
Student(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj)
{
Student s = (Student) obj;
return this.age == s.age;
}
[email protected] 3
Student s1 = new Student(20);
Student s2 = new Student(20);
System.out.println(s1.equals(s2)); // true
// s1 -> this
// s2 -> obj -> s
o/p:
false
true
3.
package comparingobjects;
[email protected] 4
int id;
double height;
@Override
public boolean equals(Object obj)
{
Employee emp = (Employee) obj;
return this.id == emp.id && this.height == emp.height;
}
System.out.println(e1.equals(e2));
System.out.println("---------------------");
[email protected] 5
System.out.println(new Employee(1, 5.7).equals(new
Employee(1, 5.4)));
System.out.println("----------------------");
if(e1.equals(e2)) {
System.out.println("Contents are Same");
}
else {
System.out.println("Contents are Different");
}
o/p:
false
---------------------
false
----------------------
Contents are Different
[email protected] 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) {
@Override
public void m1(String a) {
[email protected] 8
Java Notes
[email protected] 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() {
System.out.println("Object Created");
}
[email protected] 2
{
a = new Account();
}
else
{
System.out.println("Cannot Create");
}
}
}
1b.
package com;
Account.createObject();
Account.createObject();
Account.createObject();
o/p:
[email protected] 3
Object Created
Cannot Create
Cannot Create
2a.
package singleton;
private AadhaarCard() {
System.out.println("AadhaarCard Object Created");
}
2b.
package singleton;
[email protected] 4
public class Person {
AadhaarCard.createAadhaarCardObject();
AadhaarCard.createAadhaarCardObject();
AadhaarCard.createAadhaarCardObject();
AadhaarCard.createAadhaarCardObject();
o/p:
AadhaarCard Object Created
3a.
package singleton;
[email protected] 5
private static PrimeMinister pm; // pm = null
private PrimeMinister() {
System.out.println("PM got Elected");
}
3b.
package singleton;
PrimeMinister pm =
PrimeMinister.createAndReturnPMObject();
[email protected] 6
System.out.println("Name: "+pm.name);
o/p:
PM got Elected
Name: Modi
4a.
package singleton;
private Marriage() {
System.out.println("Got Married");
}
[email protected] 7
public static Marriage getInstance() {
if(m == null) {
m = new Marriage();
}
return m;
}
}
4b.
package singleton;
o/p:
[email protected] 8
Got Married
at the age of 29
[email protected] 9
Java Notes
[email protected] 1
String
-> String is pre-defined final class present in java.lang
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
[email protected] 2
1. toString()
2. hashCode()
3. equals()
[email protected] 3
// Converting an Array of Characters to String
String s3 = new String(ch);
System.out.println(s3);
}
o/p:
dinga
java
--------------------------------------
1.
[email protected] 4
package jspiders;
System.out.println("-----------------");
System.out.println("-----------------");
System.out.println(s1.equals(s2));
}
}
o/p:
[email protected] 5
jspiders.Student@15db9742
jspiders.Student@15db9742
-----------------
1829164700
-----------------
false
2.
package jspiders;
// String s = "java";
System.out.println("-----------------");
[email protected] 6
System.out.println("-----------------");
System.out.println(a.equals(b));
}
}
o/p:
java
java
-----------------
97
-----------------
true
System.out.println(s.length()); // 18
[email protected] 7
System.out.println("------------------");
System.out.println(s.toUpperCase());
System.out.println("------------------");
System.out.println(s.toLowerCase());
System.out.println("------------------");
System.out.println(s.startsWith("soft"));
System.out.println(s.startsWith("Soft"));
System.out.println("------------------");
System.out.println(s.endsWith("er"));
System.out.println(s.endsWith("Eloper"));
System.out.println("------------------");
System.out.println(s.contains("dev"));
System.out.println(s.contains("Dev"));
System.out.println("------------------");
System.out.println(s.concat(" in TY"));
System.out.println("------------------");
// Software Developer
System.out.println(s.charAt(2));
System.out.println(s.charAt(14));
System.out.println("------------------");
System.out.println(s.indexOf('t'));
System.out.println(s.indexOf('D'));
System.out.println(s.indexOf('e'));
System.out.println("------------------");
[email protected] 8
String a = "java";
String b = "JavA";
String c = "java";
System.out.println(a.equals(b)); // false
System.out.println(a.equals(c)); // true
System.out.println(a.equalsIgnoreCase(b));
System.out.println("------------------");
System.out.println(x.substring(3)); // lo dinga
System.out.println(x.substring(7)); // inga
System.out.println("------------------");
}
}
o/p:
18
------------------
SOFTWARE DEVELOPER
------------------
software developer
------------------
false
true
------------------
true
false
------------------
false
[email protected] 9
true
------------------
Software Developer in TY
------------------
f
o
------------------
3
9
7
------------------
false
true
true
------------------
lo dinga
inga
llo d
o ding
------------------
[email protected]
10
Java Notes
[email protected] 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
[email protected] 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.
[email protected] 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 java.util.Scanner;
System.out.println("start");
[email protected] 4
int b = scan.nextInt(); // 0
try
{
System.out.println(a/b); // 10/0 ->
ArithmeticException
}
catch(ArithmeticException e) // Specific
Exception Handler
{
System.out.println("Dabbafellow, do not
divide by 0");
}
scan.close();
System.out.println("end");
}
o/p:
start
Enter the value of a:
10
Enter the value of b:
[email protected] 5
0
Dabbafellow, do not divide by 0
end
2.
package com;
System.out.println("start");
try {
System.out.println(a[99]);
}
catch(ArrayIndexOutOfBoundsException e) {
// Specific Exception Handler
System.out.println("Invalid Index");
}
System.out.println("end");
o/p:
start
Invalid Index
end
3.
package com;
try {
System.out.println(10/0); // Object
of ArithmeticException is thrown
}
catch(ArithmeticException e) {
System.out.println("Invalid
Denominator");
}
[email protected] 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 {
System.out.println(10/0);
}
catch(ArrayIndexOutOfBoundsException e) {
[email protected] 8
System.out.println("Invalid Index
Position");
}
catch(NullPointerException e) {
System.out.println("Invalid");
}
catch(ArithmeticException e) {
System.out.println("Invalid
Denominator");
}
catch(Exception e) {
System.out.println("SuperClass
Exception Handler");
}
}
}
o/p:
Invalid Denominator
[email protected] 9
Java Notes
[email protected] 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.
[email protected] 2
1.
package org;
System.out.println("start");
try
{
System.out.println(10/0);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("end");
}
}
/*
Exception in thread "main"
java.lang.ArithmeticException: / by zero
[email protected] 3
at org.Demo.main(Demo.java:7)
*/
o/p:
start
java.lang.ArithmeticException: / by zero
at org.Demo.main(Demo.java:11)
end
2.
package org;
System.out.println("start");
try
{
System.out.println(10/0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
[email protected] 4
String message = e.getMessage();
System.out.println(message);
}
System.out.println("end");
}
}
/*
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at org.Test.main(Test.java:7)
*/
o/p:
start
/ by zero
/ by zero
end
3.
package org;
[email protected] 5
public class FinallyBlockExample {
System.out.println("start");
try
{
System.out.println(10/0);
}
catch(ArithmeticException e)
{
System.out.println("Invalid");
}
finally
{
System.out.println("Inside Finally
Block");
}
System.out.println("end");
}
}
[email protected] 6
o/p:
start
Invalid
Inside Finally Block
end
4.
package org;
try
{
try
{
}
catch (Exception e)
{
}
}
catch (Exception e)
finally
{
try
{
}
catch (Exception e)
{
}
}
}
}
5.
package org;
[email protected] 8
String s = "java";
char[] c = s.toCharArray();
System.out.println();
o/p:
java
avaj
[email protected] 9
Java Notes
throws
[email protected] 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 {
System.out.println(10/0);
}
// ArithmeticException -> Unchecked Exception
2.
package jspiders;
public class B {
[email protected] 2
public static void main(String[] args) {
System.out.println(a[1000]);
}
}
// ArrayIndexOutOfBoundsException -> Unchecked Exception
3.
package jspiders;
public class C {
try
{
[email protected] 3
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
// InterruptedException -> Checked Exception
4.
package jspiders;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class D {
try
[email protected] 4
{
FileReader f = new FileReader("demo.txt");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found");
}
5.
package jspiders;
[email protected] 5
System.out.println("start");
try
{
div();
}
catch (Exception e)
{
System.out.println("Handled");
}
System.out.println("end");
6.
package jspiders;
[email protected] 6
{
for (int i=1; i<=5; i++)
{
System.out.println(i);
Thread.sleep(3000);
}
}
try {
display();
}
catch (Exception e) {
e.printStackTrace();
}
7.
package jspiders;
[email protected] 7
import java.io.FileNotFoundException;
import java.io.FileReader;
try {
e.readData();
} catch (FileNotFoundException e1) {
System.out.println("File not present");
}
}
[email protected] 8
8a.
package example;
8b.
package example;
@Override
public int add(int a, int b) {
return a+b;
}
[email protected] 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 java.util.Scanner;
[email protected]
10
public static void main(String[] args) {
System.out.println("===================================
");
while(true) {
System.out.println("1:Addition\n2:Subtraction\n3:Multiplicat
ion");
System.out.println("4:Division\n5:Exit");
System.out.println("Enter Choice:");
int choice = scan.nextInt();
int a = 0;
int b = 0;
switch(choice) {
case 1:
int sum = c.add(a, b);
System.out.println("Sum: "+sum);
break;
case 2:
int diff= c.sub(a, b);
System.out.println("Difference: "+diff);
break;
case 3:
System.out.println("Product: "+c.mul(a, b));
break;
case 4:
System.out.println("Quotient: "+c.div(a, b));
[email protected]
12
break;
case 5:
System.out.println("Thank You!!");
System.exit(0);
default:
System.out.println("Invalid Choice");
}
System.out.println("--------------------------------------");
}
}
}
o/p:
---Welcome to Calculator Project---
===================================
1:Addition
2:Subtraction
3:Multiplication
4:Division
5:Exit
[email protected]
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
[email protected]
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!!
[email protected]
15
Java Notes
[email protected] 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;
1b.
package customexception;
import java.util.Scanner;
if(id.equals("admin")) {
if(password == 123) {
System.out.println("Login Successful");
}
[email protected] 3
else {
try {
// throw new
InvalidPasswordException();
InvalidPasswordException obj = new
InvalidPasswordException();
throw obj;
}
catch(InvalidPasswordException e) {
System.out.println("Invalid Password
Entered!!");
}
scan.close();
o/p:
[email protected] 4
Enter User Id:
admin
Enter Password:
126
Invalid Password Entered!!
2a.
package customexception;
2b.
package customexception;
import java.util.Scanner;
[email protected] 5
int balance = 10000;
if(amount<=balance) {
System.out.println("Withdrawal Successful");
}
else
{
try
{
throw new InsufficientBalanceException();
}
catch (InsufficientBalanceException e)
{
System.out.println("Not Enough Balance to
Withdraw! :(");
}
}
}
[email protected] 6
o/p:
Enter Amount to be Withdrawn:
15263
Not Enough Balance to Withdraw! :(
3a.
package customexception;
Employee(String name) {
this.name = name;
}
3b.
[email protected] 7
package customexception;
o/p:
Tom
4a.
package customexception;
AgeInvalidException(String message) {
[email protected] 8
this.message = message;
}
@Override
public String getMessage() {
return message;
}
4b.
package customexception;
import java.util.Scanner;
System.out.println("Enter Age:");
int age = s.nextInt();
[email protected] 9
if(age>=21) {
System.out.println("Get Married Soon!!!");
}
else
{
try
{
throw new AgeInvalidException("Have
Patience, You are not yet 21!!");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
o/p:
Enter Age:
[email protected]
10
12
Have Patience, You are not yet 21!!
[email protected]
11
1.
package day1;
import java.util.ArrayList;
System.out.println(l);
System.out.println("-------------");
System.out.println("-------------");
// System.out.println(l.get(250)); IndexOutOfBoundsException
System.out.println("-------------");
System.out.println("-------------");
System.out.println(l);
System.out.println(l);
System.out.println("-------------");
System.out.println(l.isEmpty());
System.out.println("=========================");
x.add(20);
x.add(10);
x.add(30);
x.add(10);
x.add(30);
x.add(10);
x.add(60);
System.out.println(x);
System.out.println("-------------");
System.out.println("-------------");
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 java.util 1. PDC in java.util
2. JDK 1.2 2. JDK 1.2
1.
package day2;
import java.util.LinkedList;
l.add(10);
l.add(20);
l.add(30);
l.add(40);
System.out.println(l);
System.out.println("--------------------");
System.out.println("--------------------");
System.out.println("--------------------");
String y = "java";
System.out.println(y.length());
System.out.println(l.size());
}
}
o/p:
[10, 20, 30, 40]
--------------------
10
20
30
40
--------------------
40
30
20
10
--------------------
3
4
4
2.
package day2;
import java.util.ArrayList;
import java.util.LinkedList;
al.add(10);
al.add(20);
System.out.println("Objects inside ArrayList: "+al+" Size:
"+al.size());
System.out.println("--------------");
/**
* addAll() is used to add all the objects of one collection
into another collection.
*/
ll.addAll(al);
ll.add(30);
System.out.println("Objects inside LinkedList: "+ll+" Size:
"+ll.size());
}
}
o/p:
Objects inside ArrayList: [10, 20] Size: 2
--------------
Objects inside LinkedList: [10, 20, 30] Size: 3
3.
package day2;
import java.util.*;
System.out.println("--------------");
ll.addAll(al);
ll.add(30);
System.out.println("Objects inside LinkedList: "+ll+" Size:
"+ll.size());
System.out.println("-----------------------");
/**
* containsAll() is used to check if all the objects of one
collection is present
* inside another collection or not.
*/
System.out.println(ll.containsAll(al)); // true
ll.remove(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 java.util.*;
public class Runner {
al.add(10);
al.add(20);
System.out.println("Objects inside ArrayList: "+al+" Size:
"+al.size());
System.out.println("--------------");
ll.addAll(al);
ll.add(30);
System.out.println("Objects inside LinkedList: "+ll+" Size:
"+ll.size());
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 java.util.ArrayList;
l.add(10);
l.add(20);
l.add(30);
}
}
o/p:
[10, 20, 30]
[10, 50, 20, 30]
[10, 50, 70, 30]
6.
package day2;
import java.util.ArrayList;
import java.util.Collections;
l.add(30);
l.add(40);
l.add(10);
l.add(20);
System.out.println("Before Sorting:");
for(int i=0 ;i<l.size(); i++) {
System.out.println(l.get(i));
}
Collections.sort(l);
System.out.println("After Sorting:");
for(int i=0 ;i<l.size(); i++) {
System.out.println(l.get(i));
}
}
}
o/p:
Before Sorting:
30
40
10
20
After Sorting:
10
20
30
40
1.
package day3;
System.out.println("---------");
for(int i : a) {
System.out.println(i);
}
System.out.println("---------");
for(double z : percentage) {
System.out.println(z);
}
System.out.println("---------");
}
}
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 {
System.out.println(a+" "+b);
System.out.println("--------");
System.out.println(x+" "+y);
System.out.println("==============================");
int i = 5;
Integer j = new Integer(i);
System.out.println(i+" "+j);
System.out.println("--------");
char p = 'z';
Character q = new Character(p);
System.out.println(p+" "+q);
System.out.println("=============================");
System.out.println("--------");
o/p:
10 10
--------
A A
==============================
5 5
--------
z z
=============================
50 50
--------
5.2 5.2
3.
package day3;
import java.util.ArrayList;
import java.util.LinkedList;
l.add("20");
l.add("sql");
l.add("java");
for(String s : l) {
System.out.println(s);
}
System.out.println("-------------");
x.add(10);
x.add(34);
x.add(67);
for(Integer i : x) { //for(int i : x) {
System.out.println(i);
}
System.out.println("-------------");
z.add(8.99);
z.add(102.34);
z.add(3.45);
for(double j : z) { // for(Double j : z) {
System.out.println(j);
}
o/p:
20
sql
java
-------------
10
34
67
-------------
8.99
102.34
3.45
4.
package day3;
import java.util.ArrayList;
import java.util.LinkedList;
int a = 10;
char b = 'z';
for(Object o : l) {
System.out.println(o);
}
System.out.println("--------------");
o/p:
10
20.45
z
--------------
10
java
1.2
Programs
1a.
package day4;
int age ;
String name;
1b.
package day4;
import java.util.ArrayList;
l.add(s1);
l.add(s2);
l.add(s3);
for(Student obj : l) {
System.out.println(obj);
System.out.println("Name:"+obj.name+" Age:"+obj.age);
System.out.println("-------------------");
}
}
}
o/p:
day4.Student@15db9742
Name:Tom Age:21
-------------------
day4.Student@6d06d69c
Name:Jerry Age:22
-------------------
day4.Student@7852e922
Name:Smith Age:23
-------------------
2a.
package day4;
@Override
public String toString() {
return "Id:"+id+" Name:"+name;
}
2b.
package day4;
import java.util.ArrayList;
l.add(e1);
l.add(e2);
l.add(e3);
System.out.println("------");
}
}
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 java.util.Vector;
public class Solution {
v.add(10);
v.add(20.45);
v.add("dinga");
for(Object o : v) {
System.out.println(o);
}
}
}
o/p:
10
20.45
dinga
4.
package day4;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Vector;
System.out.println("----------------------");
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 java.lang 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 java.util | 1. PDC in java.util
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 java.util.HashSet;
h.add(20);
h.add(20.67);
h.add(null);
h.add(20);
h.add("java");
for(Object obj : h) {
System.out.println(obj);
}
System.out.println("----------");
System.out.println(h);
System.out.println("----------");
System.out.println("Size: "+h.size());
}
}
o/p:
null
java
20
20.67
----------
[null, java, 20, 20.67]
----------
Size: 4
2.
package day5;
import java.util.LinkedHashSet;
lhs.add("java");
lhs.add("python");
lhs.add("java");
lhs.add("javascript");
o/p:
java
python
javascript
3.
package day5;
import java.util.TreeSet;
t.add(30);
t.add(40);
t.add(20);
t.add(30);
t.add(50);
t.add(10);
for(int i : t) {
System.out.println(i);
}
}
}
o/p:
10
20
30
40
50
4.
package day5;
import java.util.TreeSet;
Integer i;
t.add("Banana");
t.add("Cat");
t.add("Apple");
System.out.println(t);
System.out.println("----------");
for(String s : t) {
System.out.println(s);
}
o/p:
[Apple, Banana, Cat]
----------
Apple
Banana
Cat
5.
package day5;
import java.util.TreeSet;
String a = "A";
String b = "B";
System.out.println(a.compareTo(b)); // -1
System.out.println(b.compareTo(a)); // +1
System.out.println(b.compareTo(b)); // 0
System.out.println("--------");
Integer x = 10;
Integer y = 20;
System.out.println(x.compareTo(y)); // -1
System.out.println(y.compareTo(x)); // 1
System.out.println(x.compareTo(x)); // 0
System.out.println("-----------");
Double i = 2.4;
Double j = 3.5;
System.out.println(i.compareTo(j));
System.out.println(i.compareTo(i));
System.out.println(j.compareTo(i));
System.out.println("--------------");
t.add(10);
t.add("dinga");
t.add(10.4);
System.out.println(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) {
this.cost = cost;
}
@Override
public String toString() {
return "cost: "+cost;
}
@Override
public int compareTo(Car c) {
return this.cost - c.cost;
}
/*
public static void main(String[] args) {
Car c = new Car(100);
System.out.println(c);
import java.util.TreeSet;
class SortCar {
t.add(c1);
t.add(c2);
t.add(c3);
for(Car c : t) {
System.out.println(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 this.name.compareTo(s.name);
}
/*@Override
public int compareTo(Student s) {
return this.id - s.id;
}*/
}
2b.
package defaultsorting;
import java.util.TreeSet;
t.add(s1);
t.add(s2);
t.add(s3);
for(Student obj : t) {
System.out.println(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) (this.salary - e.salary); //2.4 - 1.1 ->
1.3 -> Explore -> Tomorrow
}*/
@Override
public int compareTo(Employee e) {
return e.name.compareTo(this.name);
}
// @Override
// public int compareTo(Employee e) {
// return e.id - this.id; //return this.id - e.id;
// }
3b.
package defaultsorting;
import java.util.TreeSet;
t.add(e1);
t.add(e2);
t.add(new Employee(4, "Tom", 12.67));
t.add(new Employee(3, "Jerry", 99.41));
for(Employee emp : t) {
System.out.println(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 java.util 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 java.util.Comparator;
@Override
public int compare(Student x, Student y) {
return x.age - y.age;
}
1c.
package customsorting;
import java.util.Comparator;
@Override
public int compare(Student x, Student y) {
return x.name.compareTo(y.name);
}
1d.
package customsorting;
import java.util.TreeSet;
t.add(s1);
t.add(s2);
t.add(s3);
for(Student std : t) {
System.out.println(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 java.util.Comparator;
@Override // descending
public int compare(Employee x, Employee y) {
return y.id.compareTo(x.id);
}
2c.
package customsorting;
import java.util.Comparator;
@Override
public int compare(Employee x, Employee y) {
return y.name.compareTo(x.name);
}
/*@Override
public int compare(Employee x, Employee y) {
return x.name.compareTo(y.name);
}*/
2d.
package customsorting;
import java.util.Comparator;
@Override
public int compare(Employee x, Employee y) {
return x.salary.compareTo(y.salary);
}
}
2e.
package customsorting;
import java.util.TreeSet;
t.add(e1);
t.add(e2);
t.add(new Employee(20, "Tata", 18.98));
t.add(new Employee(15, "Kotak", 18.34));
for(Employee emp : t) {
System.out.println(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 java.util package.
2. Jdk 1.2
3. Insertion Order is not Maintained.
4. Underlined Data Structure is HashTable.
----------------------------------------------------------------
LinkedHashMap
-------------
1. Pre-defined class in java.util package.
2. Jdk 1.4
3. Insertion Order is Maintained.
4. Underlined Data Structure is LinkedList and HashTable.
----------------------------------------------------------------
TreeMap
-------------
1. Pre-defined class in java.util 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 java.util.HashMap;
System.out.println(h);
System.out.println("-----------");
System.out.println("-----------");
System.out.println("-----------");
System.out.println("-----------");
System.out.println(h);
System.out.println(h);
System.out.println("-----------");
System.out.println(h.isEmpty());
System.out.println("-----------");
}
}
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 java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.TreeMap;
hm.put("tom", 22);
hm.put("jerry", 21);
hm.put("bheem", 23);
Set<String> s1 = hm.keySet();
System.out.println("-------------------");
lhm.put(10, "Java");
lhm.put(20, "Sql");
lhm.put(30, "Web");
Set<Integer> s = lhm.keySet();
for(int key : s) {
System.out.println(key+" --> "+lhm.get(key));
}
System.out.println("-------------------");
t.put(20, 1.5);
t.put(30, 2.5);
t.put(10, 4.5);
Set<Integer> s2 = t.keySet();
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 java.util.Set;
import java.util.TreeMap;
t.put("Mango", 23);
t.put("Apple", 20);
t.put("Banana", 15);
Set<String> s = t.keySet();
for(String key: s) {
System.out.println("Cost of 1Kg "+key+" is
"+t.get(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 java.util.HashMap;
h.put(1, "Sony");
System.out.println(h);
h.put(1, "Nokia");
System.out.println(h);
}
}
o/p:
{1=Sony}
{1=Nokia}