Core Java
Core Java
[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
[email protected] 2
What is Java?
- Java is a high level, platform independent,
object-oriented programming language.
- 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
5. Once the Byte code is generated, we can
execute (interpret) the program on all
operating systems.
6. WORA stands for Write Once Run Anywhere.
Note: Refer Screenshot day3_2
Note:
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.
[email protected] 4
Variables
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.
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
1. Variable Declaration and Initialization
[email protected] 6
2. Variable Declaration and Initialization
[email protected] 7
Structure of a Java Program
class ClassName
{
public static void main(String[] args)
{
System.out.println();
}
}
Program
1.
class FirstProgram
{
public static void main(String[] args)
{
System.out.println("Hello World!!!");
}
}
o/p:
Hello World!!!
[email protected] 8
2.
class Greet
{
public static void main(String[] args)
{
System.out.println("Welcome to Java Online Session");
}
}
o/p:
Welcome to Java Online Session
3.
class Student
{
public static void main(String[] args)
{
int age;
age = 22;
String name = "jerry";
double height = 5.8;
System.out.println(age);
System.out.println(name);
System.out.println(height);
}
}
o/p:
22
jerry
5.8
[email protected] 9
4.
class Employee
{
public static void main(String[] args)
{
int id = 101;
String name = "tom";
double salary = 1500.67;
System.out.println(id);
System.out.println(name);
System.out.println(salary);
System.out.println("------------");
System.out.println("------------");
System.out.println(id+name+salary);
System.out.println("------------");
System.out.println("------------");
o/p:
101
tom
1500.67
------------
Employee Id: 101
Employee Name is tom
Employee Salary = 1500.67
------------
101tom1500.67
------------
101 tom 1500.67
------------
#40, Rajajinagar, Bengaluru-51
[email protected]
11
1. Arithmetic Operators
a. +
b. –
c. *
d. /
e. %
2. Assignment Operators
a. =
b. +=
c. -=
d. *=
e. /=
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
-- Decrement by 1
[email protected]
13
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 */
1.
class ArithmeticOperators
{
public static void main(String[] args)
[email protected]
14
{
int a = 10;
int b = 20;
int sum = a+b;
System.out.println("-------------");
System.out.println(a-7);
System.out.println(b*4);
System.out.println(10/5);
System.out.println(10%2);
}
}
o/p:
Sum of 10 & 20 is 30
Sum = 30
-------------
3
80
2
0
2.
[email protected]
15
class AssignmentOperators
{
public static void main(String[] args)
{
int x = 5;
System.out.println("Value of x: "+x);
x += 20;
System.out.println("Value of x: "+x);
System.out.println("---------------");
int a = 6;
System.out.println("Value of a: "+a);
o/p:
Value of x: 5
Value of x: 25
---------------
Value of a: 6
Value of a: 42
3.
[email protected]
16
class ComparisonOperators
{
public static void main(String[] args)
{
int x = 10;
int y = 20;
System.out.println(result1); // true
System.out.println(result2); // true
System.out.println("-------------");
System.out.println(x>y); // false
System.out.println(y>=21); // false
System.out.println(y>=20); // true
System.out.println("-------------");
System.out.println("-------------");
}
[email protected]
17
}
o/p:
true
true
-------------
false
false
true
-------------
true
false
-------------
false
true
4.
class LogicalOperators
{
public static void main(String[] args)
{
int a = 1;
int b = 2;
boolean result1 = a<b && b>a; // 1<2 && 2>1 // true &&
true
boolean result2 = a>5 && b<=2; // 1>5 && 2<=2 // false &&
true
System.out.println(result1); // true
System.out.println(result2); // false
[email protected]
18
System.out.println("---------");
System.out.println("---------");
System.out.println(!true); // false
System.out.println(!false); // true
System.out.println("---------");
o/p:
true
false
---------
true
false
---------
false
true
---------
false
true
[email protected]
19
5.
class UnaryOperators
{
public static void main(String[] args)
{
int i=5;
System.out.println("i: "+i); // 5
i++;
System.out.println("i: "+i); // 6
i++;
System.out.println("i: "+i); // 7
i--;
System.out.println("i: "+i); // 6
i--;
System.out.println("i: "+i); // 5
i++;
System.out.println("i: "+i); // 6
}
}
[email protected]
20
o/p:
i: 5
i: 6
i: 7
i: 6
i: 5
i: 6
6.
class Demo
{
public static void main(String[] args)
{
int a = 20;
int b = a++;
System.out.println(a+" "+b); // 21 20
System.out.println("-------------");
int x = 88;
int y = x--;
System.out.println(x+" "+y); // 87 88
System.out.println("-------------");
int i = 45;
int j = ++i;
System.out.println(i+" "+j); // 46 46
[email protected]
21
System.out.println("-------------");
int p = 10;
int q = --p;
System.out.println(p+" "+q); // 9 9
}
}
o/p:
21 20
-------------
87 88
-------------
46 46
-------------
9 9
[email protected]
22
Conditional Statements or Decisional Statements
- Conditional Statements are used to take some decision
based on the condition specified.
- They are used for decision making.
- Different Decisional Statements are as follows:
1. Simple If
2. If Else
3. If Else If
4. Nested If
5. Switch Statement
1. Simple If:
- It is a Decision-Making statement wherein we execute
a set of the instructions if the condition is true.
1.
class IfDemo
{
public static void main(String[] args)
{
System.out.println("Start");
int n = 10;
System.out.println("End");
}
}
o/p:
Start
10 is lesser than or equal to 10
En
[email protected]
23
2. 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.
2.
class IfElseDemo
{
public static void main(String[] args)
{
// Check if a No is Positive or Negative
int n = 10;
System.out.println("----------------------");
if(true)
{
System.out.println("I am in Bengaluru");
}
else
{
System.out.println("I am not in Bengaluru");
}
System.out.println("----------------------");
if(false)
{
System.out.println("java");
}
else
{
System.out.println("sql");
}
[email protected]
24
System.out.println("----------------------");
int x = 20;
int y = 100;
o/p:
10 is a Positive Number
----------------------
I am in Bengaluru
----------------------
sql
----------------------
x:20 y:100
y is largest
3.
class EvenOrOdd
{
public static void main(String[] args)
{
int number = 21;
o/p:
21 is a Odd Number
[email protected]
26
3. If Else If
- If Else If Condition is used when we need to check or
compare multiple conditions.
1.
class IfElseIfDemo
{
public static void main(String[] args)
{
int a = 20;
int b = 20;
System.out.println("a:"+a+" b:"+b);
if(a<b)
{
System.out.println("a is lesser than b");
}
else if(a>b)
{
System.out.println("a is greater than b");
}
else // else if(a==b)
{
System.out.println("a is equal to b");
}
}
}
o/p:
[email protected]
27
a:20 b:20
a is equal to b
2.
class MarksValidation
{
public static void main(String[] args)
{
int marks = -26;
o/p:INVALID MARKS
[email protected]
28
4. Nested If
- Nested If is a decision-making statement wherein one if
condition is present inside another if condition.
3.
class NestedIf
{
public static void main(String[] args)
{
int n = 70;
if(n<=10) // outer if
{
System.out.println(n+" is lesser than or equal to
10");
if(n==7) // inner if
{
System.out.println(n+" is equal to 7");
}
else // inner else
{
System.out.println(n+" is not equal to 7");
}
}
else // outer else
{
System.out.println(n+" is greater than 10");
}
}
o/p:
70 is greater than 10
4.
class LoginValidation
{
public static void main(String[] args)
{
String id = "pawar";
int password = 1234;
o/p:
User Id is Invalid
Login Unsuccessful
5.
class LargestOfThreeNumbers {
int a = 10;
int b = 50;
int c = 300;
}
}
o/p:
a=10 b=50 c=300
c is largest
[email protected]
32
Switch Statement:
Switch Statement is generally used for Character Comparison.
1.
class SwitchExample
{
public static void main(String[] args)
{
int choice = 30;
switch(choice)
{
case 1 : System.out.println("In Case 1");
1 break;
o/p:
Invalid Choice
[email protected]
33
2.
class GradeValidation
{
public static void main(String[] args)
{
char grade = 'C';
switch(grade)
{
case 'A' : System.out.println("Excellent");
break;
o/p:
Average
[email protected]
34
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.
1.
class ForLoopDemo
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("------------");
[email protected]
35
System.out.println("------------");
System.out.println("------------");
System.out.println("------------");
for(int i=2; i<=10; i=i+2) // i=i+2 -> i+=2 -> i++ ->
i+=1 -> i=i+1
{
System.out.println(i);
}
System.out.println("------------");
System.out.println("------------");
[email protected]
36
for(int i=3; i<=15; i+=3) // 3 6 9 12 15
{
System.out.println(i);
}
}
}
o/p:
Hello
Hello
Hello
Hello
Hello
------------
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
------------
1
2
3
4
5
------------
i: 156
i: 157
[email protected]
37
i: 158
i: 159
i: 160
------------
2
4
6
8
10
------------
1
3
5
7
9
------------
3
6
9
12
15
[email protected]
38
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.
1.
class WhileLoopDemo
{
public static void main(String[] args)
{
int i = 1;
while(i<=5)
{
System.out.println(i);
i++;
}
System.out.println("---------");
int n = 1;
do
{
[email protected]
39
System.out.println(n);
n++;
}
while(n<=5);
}
}
o/p:
1
2
3
4
5
---------
1
2
3
4
5
**********************************************************
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.
Break:
[email protected]
40
- Break is a keyword which is used to transfer the
control outside the currently executing loop.
1.
class BreakDemo
{
public static void main(String[] args)
{
System.out.println("start");
System.out.println(i); // 1 2
}
System.out.println("-------");
if(i==3)
{
break;
}
[email protected]
41
}
System.out.println("end");
}
}
o/p:
start
1
2
-------
1
2
3
end
Continue:
- Continue is a keyword which is used to transfer the
control back to the update part.
1.
class ContinueDemo
{
public static void main(String[] args)
{
System.out.println(i); // 1 2 3 5
}
System.out.println("------");
if(i==4)
{
continue;
}
}
System.out.println("------");
[email protected]
43
System.out.println(i); // 1 2 3 4 5
}
System.out.println("------");
System.out.println(i); // 1 4 5
}
}
}
o/p:
1
2
3
5
------
1
2
3
4
[email protected]
44
5
------
1
2
3
4
5
------
1
4
5
[email protected]
45
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.
System.out.println(s.age);
System.out.println(s.name);
System.out.println(s.height);
}
}
o/p:
20
Dinga
5.8
2.
class Car
{
String brand = "BMW";
int cost = 4500;
System.out.println(c.brand);
System.out.println(c.cost);
System.out.println("-------");
System.out.println(c.brand+" "+c.cost);
System.out.println("-------");
o/p:
BMW
4500
-------
BMW 4500
-------
Cost of BMW is Rs.4500
3a.
class Employee
{
int id = 101;
String name = "Tim Cook";
double salary = 1500.56;
[email protected]
48
}
3b.
/* Accessing non static members in different 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
Tim Cook
1500.56
[email protected]
49
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).
1.
class Person {
[email protected]
50
System.out.println(p1.age+" "+p1.name); // 10 Tom
System.out.println(p2.age+" "+p2.name); // 10 Tom
System.out.println("**************");
p1.age = 33;
p2.name = "Jerry";
o/p:
10 Tom
10 Tom
**************
33 Tom
10 Jerry
2.
class DefaultValuesDemo {
int a;
double b;
char c;
boolean d;
String e;
[email protected]
51
public static void main(String[] args) {
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
false
null
3.
class Student {
int age;
String name;
[email protected]
52
Student s1 = new Student();
Student s2 = new Student();
s1.age = 21;
s1.name = "Tom";
s2.age = 22;
s2.name = "Jerry";
System.out.println("Student Details");
System.out.println("---------------");
o/p:
Student Details
---------------
Tom is 21 years old
Jerry is 22 years old
4.
class Demo
{
[email protected]
53
public static void main(String[] args) {
System.out.println(10);
System.out.println(20);
System.out.println(30);
System.out.println("----");
System.out.print(1);
System.out.print(2);
System.out.print(3);
}
o/p:
10
20
30
----
123
5.
class Test
{
public static void main(String[] args) {
System.out.println(10);
System.out.print(20+"hello");
System.out.println(30+" ");
[email protected]
54
System.out.print("bye");
System.out.print(" java");
System.out.println("program "+" hi");
System.out.print("done");
o/p:
10
20hello30
bye javaprogram hi
done
[email protected]
55
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]
56
1.
class Demo
{
/* Method without arguments and without return statement */
void display() // non static method
{
System.out.println("Hello World");
}
System.out.println("end");
}
}
o/p:
start
Hello World
end
2.
/* Write a Java Program in order to create a method to add 2 nos */
class Addition
[email protected]
57
{
/* Method with arguments and without return statement */
void add(int a, int b)
{
int sum = a+b;
System.out.println("Sum of "+a+" & "+b+" is "+sum);
}
obj.add(4,8);
obj.add(10, 20);
obj.add(786, 234);
}
}
output:
Sum of 4 & 8 is 12
Sum of 10 & 20 is 30
Sum of 786 & 234 is 1020
3.
/* Write a Java Program in order to create a method
to find the product of 3 Numbers */
class Multiplication
{
void multiply(int x, int y, int z)
[email protected]
58
{
System.out.println(x*y*z);
}
m.multiply(2, 3, 4);
}
}
o/p:
24
4.
class Test
{
/* Method without arguments and with return statement */
String display()
{
return "dinga";
}
System.out.println(t.display());
}
}
o/p:
My Name is not dinga
dinga
5.
class Example
{
/* Method with argument and with return statement */
int findPower(int n)
{
return n*n;
}
System.out.println(e.findPower(4));
}
}
[email protected]
60
o/p:
25
16
6a.
class Solution {
[email protected]
61
6b.
class MainClass {
s.m1();
System.out.println("------");
s.m2("Guldu", 123);
System.out.println("------");
double x = s.m3();
System.out.println(x);
System.out.println(s.m3());
System.out.println("------");
System.out.println(s.m4(1.1, 7.2));
}
}
output:
Welcome to Java Online Session
------
[email protected]
62
Name: Guldu
Id: 123
------
45.6
45.6
------
4.4
8.3
[email protected]
63
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.
1.
package jspiders;
class Demo
{
public static void main(String[] args)
{
[email protected]
64
System.out.println("Hello World");
}
}
o/p:
Hello World
2a.
package com;
class Example
{
void display(int a)
{
System.out.println("a: "+a);
}
void display(double a)
{
System.out.println("a: "+a);
}
void display()
{
System.out.println("Hello DabbaFellow");
}
2b.
package com;
class Solution
{
public static void main(String[] args)
{
Example e = new Example();
e.display();
e.display(45);
e.display(10, "java");
e.display(45.6);
e.display("tom", 34);
}
}
[email protected]
66
o/p:
Hello DabbaFellow
a: 45
x:10 y:java
a: 45.6
x:tom y:34
3.
package com;
class Netflix
{
void login(String emailId, int password)
{
System.out.println("Email Id: "+emailId);
System.out.println("Password: "+password);
}
n.login(987745, 123);
[email protected]
67
System.out.println("-------");
n.login("[email protected]", 456);
}
}
o/p:
Contact No: 987745
Password: 123
-------
Email Id: [email protected]
Password: 456
4.
package com;
class Test
{
public static void main(int a)
{
System.out.println("java");
}
o/p:
hello
java
bye
[email protected]
69
Scanner
1. Scanner is a pre-defined class in java.util package.
2. Scanner class is used to accept dynamic input from the
User.
1. byte - nextByte()
2. short - nextShort()
3. int - nextInt()
4. long - nextLong()
5. float - nextFloat()
6. double - nextDouble()
7. boolean - nextBoolean()
[email protected]
70
8. String - next() or nextLine()
9. char - next().charAt(0)
1.
package com;
import java.util.Scanner;
System.out.println(a+b);
o/p:
Enter the value of a:
[email protected]
71
10
Enter the value of b:
20
30
2.
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 Height:");
double height = s.nextDouble();
System.out.println("---------------");
[email protected]
72
}
}
o/p:
Enter Age:
25
Enter Name:
tom
Enter Height:
5.6
---------------
tom is 25 years old and his height is 5.6
3.
package com;
import java.util.Scanner;
o/p:
Enter 2 Numbers:
1
2
Sum of 1 & 2 is 3
-----------------
Enter 2 Numbers:
5
36
Sum of 5 & 36 is 41
-----------------
Enter 2 Numbers:
896
5
Sum of 896 & 5 is 901
-----------------
[email protected]
74
4.
package com;
import java.util.Scanner;
void findPosOrNeg(int n) {
if(n>0) {
System.out.println(n+" is a Positive Number");
}
else {
System.out.println(n+" is a Negative Number");
}
/*int n = s.nextInt();
t.findPosOrNeg(n);*/
o/p:
Enter Number:
7
7 is a Positive Number
--------------
Enter Number:
-9
-9 is a Negative Number
--------------
Enter Number:
6
6 is a Positive Number
--------------
[email protected]
76
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.
1.
package com;
class Student {
[email protected]
77
static void study() {
System.out.println("Studying");
}
System.out.println(Student.age);
Student.study();
System.out.println("------");
}
}
o/p:
20
Studying
------
20
Studying
2a.
package com;
class Employee {
2b.
package com;
System.out.println(Employee.id);
Employee.work();
o/p:
1203
Working
[email protected]
79
3.
package com;
class Company {
String branchName;
Company.companyName = "Jspiders";
}
}
[email protected]
80
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 com;
class Demo {
static {
System.out.println("In Static Block-1");
}
[email protected]
81
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 com;
class Student {
static
{
System.out.println("Initializing age to 20");
[email protected]
82
age = 20; //Student.age = 20;
}
static
{
System.out.println("Initializing age to 30");
age = 30;
}
o/p:
Initializing age to 20
Initializing age to 30
Age: 30
[email protected]
83
}
1.
package com;
class Test
{
{
System.out.println("in non-static block-1");
}
{
System.out.println("in non-static block-2");
}
{
System.out.println("in non-static block-3");
}
}
[email protected]
84
o/p:
in non-static block-1
in non-static block-2
in non-static block-3
2.
package com;
class Employee {
int id;
{
id = 100;
}
{
id = 200;
}
}
[email protected]
85
// id = 0 -> 100 -> 200
o/p:
200
3.
package com;
class Solution
{
static
{
System.out.println(20);
}
{
System.out.println(30);
}
o/p:
[email protected]
86
20
10
30
4.
package com;
class Car
{
static int a; // 0 -> 20
int b; // 30
static
{
a = 20;
}
{
b = 30;
}
}
}
[email protected]
87
o/p:
20
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.
Class Loader
- Loads the Class from secondary storage to executable
area.
Interpreter
- Interprets the code line by line.
JVM
[email protected]
88
- 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
1.
package com;
class Example
{
static void m1(int a) // a=10
{
System.out.println("Hai");
System.out.println(m2(50));
System.out.println("Bye");
}
[email protected]
89
{
System.out.println("Start");
m1(10);
System.out.println("End");
}
}
o/p:
Start
Hai
150
Bye
End
[email protected]
90
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]
91
2. They are further categorized into 2 types:
i. Non-Parameterized Custom Constructor
ii. Parameterized Custom Constructor
class Car
{
/* Non Parameterized Custom/User-Defined Constructor */
Car()
{
System.out.println("In Car Class Constructor");
}
o/p:
start
In Car Class Constructor
end
2.
package com;
class Bike
{
/* Parameterized Custom/User-Defined Constructor */
[email protected]
93
Bike(String brand)
{
System.out.println("Brand: "+brand);
}
o/p:
Brand: suzuki
3.
package com;
class Kangaroo
{
double height = 5.5; // Member/Global Variable
void display()
{
double height = 4.4; // Local Variable
System.out.println(height);
System.out.println(this.height);
}
o/p:
4.4
5.5
4.
package com;
class Student
{
int age;
Student(int age)
{
this.age = age;
}
System.out.println("Age:"+s1.age);
System.out.println("Age:"+s2.age);
}
[email protected]
95
}
o/p:
Age:25
Age:24
5.
package com;
class Person {
String name;
Person(String name) {
this.name = name;
}
}
}
o/p:
Dinga Tom Dingi
[email protected]
96
6.
package com;
class Employee {
int id;
String name;
System.out.println("-------------------");
System.out.println("Employee Id of "+e1.name+" is
"+e1.id);
System.out.println("Employee Id of "+e2.name+" is
"+e2.id);
[email protected]
97
System.out.println("Employee Id of "+e3.name+" is
"+e3.id);
}
}
o/p:
Name: Tom Id: 101
Name: Ali Id: 102
Name: Ram Id: 103
-------------------
Employee Id of Tom is 101
Employee Id of Ali is 102
Employee Id of Ram is 103
[email protected]
98
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]
99
package singlelevel;
1c.
package singlelevel;
System.out.println(s.name+" "+s.age);
output:
Dinga 20
2a.
package multilevel;
class University {
[email protected]
100
String universityName = "VTU";
void conductExams() {
System.out.println("VTU is Conducting Examination");
}
2b.
package multilevel;
void providePlacements() {
System.out.println("Jspiders will provide Interview
Opportunities");
}
2c.
package multilevel;
void conductFest() {
[email protected]
101
System.out.println("CS Department planned an intra
college fest");
}
2d.
package multilevel;
System.out.println("------------");
d.conductExams();
d.providePlacements();
d.conductFest();
}
}
o/p:
[email protected]
102
University Name: VTU
College Name: Jspiders
Department Name: Computer Science
------------
VTU is Conducting Examination
Jspiders will provide Interview Opportunities
CS Department planned an intra college fest
3a.
package hierarchical;
class Vehicle {
String brand = "Audi";
}
3b.
package hierarchical;
void start() {
System.out.println("Car Started");
}
}
3c.
package hierarchical;
[email protected]
103
class Bike extends Vehicle {
void stop() {
System.out.println("Bike Stopped");
}
}
3d.
package hierarchical;
o/p:
Audi Petrol
Car Started
Audi 1000 Bike Stopped
[email protected]
104
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.
1a.
package hierarchical;
class Employee {
Employee() {
System.out.println("Hai");
}
Employee(int age) {
System.out.println("Age: "+age);
}
Employee(String name) {
System.out.println("Name: "+name);
}
1b.
package hierarchical;
}
}
o/p:
Age: 25
Name: tom Id:25
Hai
Name: jerryId:78 Name: smith
[email protected]
106
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 com;
class Demo
{
Demo()
{
this(999);
System.out.println(1);
[email protected]
107
}
Demo(int a)
{
System.out.println(2);
}
o/p:
2
1
2.
package com;
class Student {
o/p:
Height: 5.5
Age: 20
Name: tom
3.
package com;
class Employee
{
Employee(int id) // id=101
{
System.out.println(id);
}
[email protected]
109
Employee(int id, String name) // id=101 name="jerry"
{
this(id); // this(101);
System.out.println(name);
}
o/p:
101
Jerry
4.
package com;
class Car
{
Car()
{
this(20);
System.out.println("hai");
}
Car(int x) // x=20
{
System.out.println("bye");
[email protected]
110
}
System.out.println("end");
}
}
o/p:
start
bye
hai
end
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-
[email protected]
111
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;
1c.
package com;
[email protected]
112
public class Test {
}
}
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;
class Father
{
Father(int a)
{
System.out.println(1);
}
}
[email protected]
113
1b.
package com;
1c.
package com;
}
}
o/p:
1
2
2a.
[email protected]
114
package com;
class Vehicle
{
Vehicle(String brand)
{
System.out.println("brand: "+brand);
}
}
2b.
package com;
2c.
package com;
o/p:
brand: BMW
cost: 200
[email protected]
116
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
1a.
package com;
class Employee
{
int id = 30;
}
1b.
package com;
void display()
{
[email protected]
117
int id = 10;
d.display();
}
}
o/p:
10
20
30
[email protected]
118
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]
119
}
1b.
package com;
@Override
void bike() {
System.out.println("New Modified Son's Bike");
}
o/p:
New Modified Son's Bike
2a.
package com;
void start() {
[email protected]
120
System.out.println("Vehicle Started");
}
2b.
package com;
@Override
void start() {
super.start();
System.out.println("Bike Started");
super.start();
}
2c.
package com;
}
}
[email protected]
121
o/p:
Vehicle Started
Bike Started
Vehicle Started
3a.
package com;
void display() {
System.out.println("Single Ticks Supported");
}
3b.
package com;
@Override
void display() {
super.display();
System.out.println("Double Ticks Supported");
}
[email protected]
122
void call() {
System.out.println("Voice Call Supported");
}
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");
}
3d.
[email protected]
123
package com;
w3.display();
System.out.println("-------------");
w3.call();
System.out.println("-------------");
w3.story();
}
o/p:
Single Ticks Supported
Double Ticks Supported
Blue Ticks Supported
-------------
Voice Call Supported
Video Call Supported
-------------
Can upload images as Story
[email protected]
124
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]
125
[email protected]
126
1.
[email protected]
127
package com;
public Person() {
System.out.println("In Person Class Constructor");
}
}
}
o/p:
In Person Class Constructor
20
Person is Eating
[email protected]
128
2a.
package com;
public Person() {
System.out.println("In Person Class Constructor");
}
2b.
package com;
o/p:
In Person Class Constructor
20
Person is Eating
3a.
package com;
public Person() {
System.out.println("In Person Class Constructor");
}
[email protected]
130
}
3b.
package org;
import com.Person;
o/p:
In Person Class Constructor
20
Person is Eating
4.
package com;
[email protected]
131
/* Accessing Private Members In Same Class Same Package */
o/p:
2000
Chatting
5a.
package com;
[email protected]
132
public class Mobile {
5b. ERROR
package com;
}
}
--------------------------------------------------------
6.
package com;
Television() {
System.out.println("In Constructor");
}
void watchMovie() {
System.out.println("Watching Movie");
}
o/p:
In Constructor
Sony
Watching Movie
[email protected]
134
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]
135
}
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");
}
8b. ERROR
[email protected]
136
package org;
// import com.Television;
------------------------------------------
9.
package com;
protected Television() {
System.out.println("In Television Constructor");
}
}
}
o/p:
In Television Constructor
LG
Watching Movie
9a.
package com;
protected Television() {
System.out.println("In Television Constructor");
}
9b.
package com;
class User {
o/p:
In Television Constructor
LG
Watching Movie
10a.
package com;
[email protected]
139
/* Accessing Protected Members in Different class Different Package
*/
10b.
package org;
import com.Father;
o/p:
50
[email protected]
140
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.
1a.
package javabean;
[email protected]
141
public void setAge(int age)
{
this.age = age;
}
1b.
package javabean;
p.setAge(25);
System.out.println(p.getAge());
}
}
/*System.out.println(p.age);
p.age = 25; */
o/p:
Age: 25
25
2a.
package javabean;
2b.
package javabean;
e.setId(101);
e.setName("Tom");
System.out.println("Id: "+e.getId());
System.out.println("Name: "+e.getName());
o/p:
[email protected]
143
Id: 101
Name: Tom
3a.
package javabean;
if(age>0) {
System.out.println("Initializing age");
this.age = age;
}
else {
System.out.println("Cannot initialize");
}
3b.
package javabean;
s.setAge(25);
System.out.println(s.getAge());
}
[email protected]
144
}
o/p:
25
final
- final is a keyword which we can use it with a
variable, method and class.
- final variables cannot be re-initialized, it acts as
a constant.
- final methods cannot be overridden, but can be
inherited.
- final class cannot be inherited.
1.
package javabean;
//a=20;
System.out.println(a);
//a=30;
System.out.println(a);
2a.
package javabean;
[email protected]
145
public class A {
2b.
package javabean;
@Override
void m1() {
}
}
3a.
package javabean;
3b.
package javabean;
}
[email protected]
146
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.
1a.
package org;
/* Array Declaration */
int[] a;
/* Array Creation */
a = new int[3];
System.out.println("=======");
/* Array Initialization */
a[1] = 35;
[email protected]
147
a[2] = 12;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println("Length: "+a.length);
System.out.println("*****************");
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
names[0] = "dinga";
names[1] = "guldu";
names[2] = "dingi";
System.out.println("=======");
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
System.out.println("Length: "+names.length);
}
[email protected]
148
}
o/p:
0
0
0
=======
0
35
12
Length: 3
*****************
null
null
null
=======
dinga
guldu
dingi
Length: 3
2.
package org;
System.out.println("-----------");
}
}
o/p:
10
20
30
-----------
30
20
10
3.
package org;
[email protected]
150
public static void main(String[] args) {
int sum = 0;
System.out.println("Sum: "+sum);
System.out.println("Average: "+(sum/a.length));
o/p:
Sum: 60
Average: 20
4a.
package org;
[email protected]
151
Person(int id, String name)
{
this.id = id;
this.name = name;
}
}
4b.
package org;
4c.
package org;
4d.
package org;
}
}
o/p
101 Tom 34
222 Jerry 345.67
// Assignment
// 1. Similar
// 2. array -> No of occurrences
// a-> 10, 20, 30, 20, 10, 40
[email protected]
153
Advantages of Inheritance
1. Repetition/Redundancy is avoided.
2. Reusability of code is increased.
Naming Conventions
[email protected]
154
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]
155
1. Can abstract class have constructors?
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 org;
1b.
package org;
[email protected]
156
public class Son extends Father
{
Son()
{
// implicitly super();
System.out.println(2);
}
}
1c.
package org;
o/p:
1
2
2a.
[email protected]
157
package org;
2b.
package org;
2c.
package org;
[email protected]
158
public static void main(String[] args) {
o/p:
1
2
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:
[email protected]
159
- Converting Bigger type of data into Smaller type of
data.
- Narrowing happens Explicitly.
3.
package primitivecasting;
System.out.println("---Widening---");
int a = 10;
double b = a; // double b = 10;
System.out.println(a+" "+b); // 10 10.0
char c = 'A';
int d = c;
System.out.println(c+" "+d); // A 65
System.out.println("---Narrowing---");
double x = 3.56;
int y = (int) x;
System.out.println(x+" "+y); // 3.56 3
[email protected]
160
int i = 66;
char j = (char)i;
System.out.println(i+" "+j); // 65 B
System.out.println("-----------------------");
char z = 97;
System.out.println(z);
System.out.println("-----------------------");
System.out.println((char)98); // b
System.out.println("A"+"B"); // AB
System.out.println("A"+20); //A20
[email protected]
161
// ASCII Value -> American Standard Code for Information
Interchange
// A -> 65 -> 0101010
// a -> 97 -> 1010101
o/p:
---Widening---
10 10.0
A 65
---Narrowing---
3.56 3
66 B
-----------------------
a
-----------------------
b
78
AB
A20
131
117
4.
package primitivecasting;
[email protected]
162
public static void main(String[] args) {
System.out.println(10); // int
System.out.println(10.45); // double
System.out.println("-------------");
double a = 5.6;
float b = (float) a;
float i = 1.5f;
float j = 1.5F;
System.out.println("---------------");
}
}
[email protected]
163
o/p:
10
10.45
-------------
5.6 5.6 1.5 1.5 5.6
---------------
9999988877 9999988877
5.
package primitivecasting;
import java.util.Scanner;
System.out.println("Enter "+a.length+"
Elements:");
[email protected]
164
for(int i=0; i<a.length; i++)
{
a[i] = scan.nextInt();
}
System.out.println("-----------");
int sum = 0;
System.out.println("Sum: "+sum);
System.out.println("Average: "+ (sum/a.length));
[email protected]
165
}
o/p:
Enter the No of Elements to be inserted:
3
Enter 3 Elements:
10
50
30
Array Elements Are:
10
50
30
-----------
Sum: 90
Average: 30
[email protected]
166
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 nonprimitivecasting;
[email protected]
167
public class Father
{
int age = 40;
}
1b.
package nonprimitivecasting;
1c.
package nonprimitivecasting;
/* UPCASTING
Son s1 = new Son();
Father f = s1; */
/* DOWNCASTING */
Son s = (Son) f;
System.out.println(s.age+" "+s.name);
}
o/p:
40
--------
40 Dinga
2a.
package nonprimitivecasting;
void start() {
System.out.println("Vehicle Started");
}
}
[email protected]
169
2b.
package nonprimitivecasting;
void shiftGears() {
System.out.println("Shifting Gears");
}
2c.
package nonprimitivecasting;
[email protected]
170
System.out.println("-------");
Car c = (Car) v;
System.out.println(c.brand+" "+c.cost);
c.start();
c.shiftGears();
o/p:
BMW
Vehicle Started
-------
BMW 70000
Vehicle Started
Shifting Gears
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.
[email protected]
171
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]
172
1c.
package org;
1d.
package org;
Father obj;
obj = new Son();
}
}
/*
Father f = new Son();
Daughter s = (Daughter) f;
o/p:
Downcasting to Son
30 20
1e.
package org;
[email protected]
174
public static void main(String[] args) {
System.out.println("--------");
System.out.println("--------");
System.out.println("--------");
[email protected]
175
}
}
o/p:
true
true
--------
true
true
--------
true
false
false
--------
true
true
2a
package org;
[email protected]
176
2b.
package org;
2c.
package org;
2d.
package org;
}
}
o/p:
Brand: Suzuki Fuel: Diesel
3a.
package org;
3b.
package org;
[email protected]
178
public class Pizza extends Food {
3c.
package org;
3d.
package org;
3e.
package org;
3f.
package org;
[email protected]
180
Food obj = k.order(3); // Food obj = new
Sandwich();
}
}
o/p:
Eating Sandwich
4a.
package org;
[email protected]
181
4b.
package org;
4c.
package org;
4d.
package org;
/*
Beverage vendingMachine(int choice)
{
if(choice == 1)
{
Coffee c = new Coffee();
return c;
}
else if(choice == 2)
{
Tea t = new Tea();
return t;
}
else
{
[email protected]
183
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();
o/p:
Enter Choice:
1:Coffee
2:Tea
1
Drinking Coffee
[email protected]
185
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]
186
public class Myntra {
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
[email protected]
188
Cost: Rs.2500
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;
[email protected]
189
void work() {
System.out.println("Working");
}
1b.
package runtime;
@Override
void work() {
System.out.println("Developer is "
+ "developing an application");
}
1c.
package runtime;
@Override
void work() {
[email protected]
190
System.out.println("Tester is "
+ "testing an application");
}
1d.
package runtime;
}
}
o/p:
Developer is developing an application
Tester is testing an application
2a.
[email protected]
191
package compiletime;
2b.
package compiletime;
2c.
package compiletime;
[email protected]
192
@Override
void start() { // 2
System.out.println("Bike Started");
}
2d.
package compiletime;
o/p:
Car Started
Bike Started
2e.
package compiletime;
[email protected]
193
public class Demo {
d.invokeStart(new Car());
d.invokeStart(new Bike());
}
o/p:
Car Started
Bike Started
[email protected]
194
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]
195
Programs
1a.
package org;
1b.
package org;
@Override
public void eat() {
System.out.println("Eating");
}
System.out.println(Person.id);
[email protected]
196
Dinga d = new Dinga();
d.eat();
o/p:
101
Eating
2a.
package org;
2b.
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
[email protected]
198
3a.
package org;
void devlop();
3b.
package org;
void test();
3c.
package org;
void work() {
System.out.println("Working");
}
[email protected]
199
}
3d.
package org;
@Override
public void devlop() {
System.out.println("Developing");
}
@Override
public void test() {
System.out.println("Testing");
}
3e.
package org;
[email protected]
200
Uday u = new Uday();
u.devlop();
u.test();
u.work();
}
}
o/p:
Developing
Testing
Working
[email protected]
201
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]
202
1b.
package com;
@Override
public void work() {
System.out.println("Employee is Working");
}
1c.
package com;
[email protected]
203
}
o/p:
Employee is Working
2a.
package org.bankapp;
2b.
package org.bankapp;
@Override
[email protected]
204
public void deposit(int amount) {
System.out.println("Depositing Rs."+amount);
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]
205
public static void main(String[] args) {
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
------------------
[email protected]
206
Withdrawing Rs.4500
Amount Withdrawn Successfully
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:
[email protected]
207
System.out.println("Enter Amount to be
Deposited:");
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);
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("---------------------");
}
}
[email protected]
208
}
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
[email protected]
209
3:CheckBalance
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;
[email protected]
210
import java.util.Scanner;
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:
[email protected]
211
System.out.println("Invalid Choice");
}
System.out.println("----------");
o/p:
Enter Choice:
1
Hai
----------
Enter Choice:
2
Bye
----------
Enter Choice:
5
Invalid Choice
----------
Enter Choice:
3
[email protected]
212
3a.
package org.bankapp;
public interface A
{
void m1();
}
3b.
package org.bankapp;
public interface B
{
void m1(int a);
}
3c.
package org.bankapp;
}
[email protected]
213
@Override
public void m1(int a)
{
}
}