Learning Core Java
Core Java Session 1 Notes :
Various programming languages
C
C++
Java
Python
Etc
Java (sun, oracle)
- (Basic ) core java (sdk)
To develop standalone applications
-applications which run on only one machine at a time are called standalone applications
Ex: ms word, notepad, wordpad, paint etc
-j2ee (java 2 enterprize edition) advanced java
-we can develop web applications which runs multiple machines at a time (client server architecture), spring framework, springboot, hibernate, jpa, web services.
Ex : gmail, facebook, whatsapp
-j2me (j2micro edition)
We can Develop mobile applications
1. What is Java?
Java is a language to write programs,
Program means set of instructions (line).
2.Why we use java ?
-open source
-platform independent
-oops
To develop standalone, web applicatons, mobile applications, gaming, animation, real time applications.
3.How to use java?
-Goto below site and select java
4.what is software?
-Set of programs
What is program?
-set of instructions
5. what is java compiler ?
-Program which coverts source code into byte code and generates .class file is called compiler.
firstProgram.java --- firstProgram.class (byte code) -- firstProgram.obj (output)
6. what is java interpreter ?
-Program which runs byte code or .class file and show final output is called java interpreter
7. What is JIT ?
-Just in time compiler which compile program very fast.
8. What is JVM ?
- Stands for Java virtual machine and it Is a bunch of programs which executes byte code or class file.
9. What is JDK ?
- Java development kit which supports to write java programs and develop java applications
10. What is JRE ?
- Stands for Java Runtime Environment which runs programs and applications written in java.
12. What is keyword ?
- Vocabulary set of java
- word having predefined meaning in java
- ex : main, void, char, int, short, byte, long, float, double, for, while, do, if, else, switch, break, continue, goto, register etc.
12.2. what is variables ?
Name given to memory location to store value.
Rules : It should not start with symbol(except underscore) or number.
It should not be keyword.
Ex : int empNo = 20;
13. What is Constants ?
- constants are values which does not change during program execution.
Ex : final float pi = 3.14;
14. What is datatype ?
- Is a keyword which defines type of data.
Ex : int , char, float
int ( whole numbers ) : 1,2,3…..n
float ( whole numbers ) : 1.5,2.6,3.8…..n
char (characters): a, b, ^
Data Type | Size | Description |
Byte | 1 byte | Stores whole numbers from -128 to 127 |
Short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
Int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
Long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
Double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
Boolean | 1 bit | Stores true or false values |
Char | 2 bytes | Stores a single character/letter or ASCII values |
15. What is package
- package is like folder which is used to keep similar types of files at one place
-used to avoid accidental deletion
-should be start with small letter
-syntax : package basic;
15. What is Class ?
- class is a keyword which is used to declare class and class is an entity which contains variables, methods, blocks, constructors which can be reused many times using object.
Ex : class Student
16. What is Object ?
-Object is an instance of Class, used to access properties of class. In below stu1 is an object of Student class.
Ex : Student stu1
17. First java program to print your name
// write a program to print your name
public class FirstJavaProgram {
public static void main(String[] args) {
System.out.println("My name is Mahesh");
}
}
Session 1.2 control statements
1.if statement
if is keyword used to write condition.
Syntax :
if(condition){
stmts;
}
//write a program to check a number and print if it is positive
class IfStatement {
public static void main(String[] args) {
int number = 10;
// checks if number is greater than 0
if (number > 0) {
System.out.println("The number is positive.");
}
System.out.println("Statement outside if block");
}
}
2.if else
if else are keywords used to write condition
syntax :
if(condition){
stmt 1;
}
else{
stmt 2;
}
Flowchart :
//write a program to check a number and print wheather it is positive or negative
class Main {
public static void main(String[] args) {
int number = -10;
// checks if number is greater than 0
if (number > 0) {
System.out.println("The number is positive.");
}
// execute this block
// if number is not greater than 0
else {
System.out.println("The number is not positive.");
}
System.out.println("Statement outside if...else block");
}
}
3. else if ladder
To write more than one condition and only one condition should be executed then we use else if ladder.
Syntax :
if(condition){
}
else if(condition){
}
else if(condition){
}
.
.
else{
}
// write a program to declare a variable with value and print wheather it is positive/negative/zero
class Main {
public static void main(String[] args) {
int number = 0;
// checks if number is greater than 0
if (number > 0) {
System.out.println("The number is positive.");
}
// checks if number is less than 0
else if (number < 0) {
System.out.println("The number is negative.");
}
// if both condition is false
else {
System.out.println("The number is 0.");
}
}
}
4. Switch :
syntax :
switch(condition){
case 1:
stmts;
break;
case 2:
stmts;
break;
case 3:
stmts;
break;
.
.
.
case n:
stmts;
break;
default:
stmts;
}
/* write a program to take a number from user, and perform operation as per his choice for arithmetic operations */
/* write a program to take a number from user, and perform operation as per his choice for arithmetic operations */
package conditionalStmt;
import java.util.Scanner;
public class SwitchPractical {
public static void main(String[] args) {
int choice, num1=10, num2=5;
Scanner s = new Scanner(System.in);
System.out.println("Please enter your choice");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("Please enter choice.");
choice = s.nextInt(); //3
switch(choice){
case 1:
System.out.println(num1+num2);
break;
case 2:
System.out.println(num1-num2);
break;
case 3:
System.out.println(num1*num2);
break;
case 4:
System.out.println(num1/num2);
break;
default:
System.out.println("please enter correct choice");
break;
}
}
}
Looping Statements :
To execute some set of code repeatedly we use loops.
while loop :
While is entry controlled loop used to execute some set of code repeatedly.
syntax :
while(condition){
}
Program : write a program to print numbers from 1 to 100.
package loopPract;
public class WhileDemo {
public static void main(String[] args) {
int i=1;
while(i<=10) {
System.out.println(i);
i++; //11
}
}
}
do while loop :
do while loop is exit control loop.
syntax :
do{
}while(condition);
// program to print numbers from 1 to 10
package loopStmts;
public class DoWhilePractical {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
for loop
for loop is used to execute set of statements repeatedly
syntax :
for(initialization;condition;increment/decrement){
}
//Program 3 : Write a program to print 1 to 100 using for loop
package basicPrograms;
public class ForDemo {
public static void main(String[] args) {
for(int i=1;i<=10;i++) { //1,2,3,4.....9,10,11
System.out.println(i); //1,2,3...9,10
}
}
}
/*
sequence
step 1 : initialization
step 2 : condition (if condition is true then next steps will be executed)
step 3 : body
step 4 : increment/decrement
step 5 : repeat step 2 to 4 till loop condition is true
*/
//write a program to print below pattern using nested loop
/*
*
**
***
****
*****
*/
package loopPract;
public class PatternDemo {
public static void main(String[] args) {
//for lines
for(int i=1;i<=5;i++) { //6
//print
for(int j=1;j<=i;j++) { //
System.out.print(j);
}
System.out.println();
}
}}
for each loop :
· It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
//for…each loop with array :
package basicPrograms;
public class ForEachDemo {
public static void main(String[] args) {
int eids[]= {10,20,30,40};
for(int e : eids) {
System.out.println(e);
}
}
}
//for…each loop with arraylist :
package basicPrograms;
import java.util.ArrayList;
public class ForEachDemo {
public static void main(String[] args) {
ArrayList eids= new ArrayList();
eids.add(20);
eids.add(30);
eids.add(40);
eids.add(50);
for(int e : eids) {
System.out.println(e);
}
}
}
Session 3
Inheritance
Inheritance
Defination:
“accessing properties of old class into new class is called inheritance”.
Why to use Inheritance:
For to achieve reusability of code.
Types of Inheritance
1. Single Inheritance
2. Multilevel
3. Hierarchical
1. Single Inheritance:
Class A //super class / Base class / parent class
|
|
Class B extends A //sub class / Derived class / child class
2. Multilevel Inheritance
Class A //Base class
Class B extends A //Intermediate base class
|
Class C extends B //Derived class
3. Hierarchical inheritance:
|
Class B Class C Class D
| |
Class E Class F
Note: Multiple inheritance in java is not allowed because it creates ambiguity.
Class A Class B (Both class Has calculate method)
Class C extends A,B
C c=new C();
c.calculate();
-Here which calculate method (i.e of A class’s or of B class’s) to call, this is the confusion for JVM,
So multiple inheritance is not allowed in java.
-Multiple inheritance is achieved in java using interfaces or by writing repeated single inheritance.
Practicals:
Program 1:
1.Single Inheritance:
class P{
void DisplayP(){
System.out.println("Single Inheritance: This is Class P's Display method");
}
}
public class SingleInheritanceDemo2 extends P{
public static void main(String args[]){
SingleInheritanceDemo2 q=new SingleInheritanceDemo2();
q.DisplayP();
}
}
2.Multilevel Inheritance:
//Multilevel Inheritance
package Multilevel_Inheritance_Practical;
class X {
void DisplayX(){
System.out.println("Multilevel Inheritance: This is Class X's Display method");
}
}
class Y extends X{
void DisplayY(){
System.out.println("This is Class Y's Display method");
}
}
// Example of Multilevel Inheritance
public class Z extends Y{
public static void main(String args[]){
Z z=new Z();
z.DisplayX();
}
}
3.Hierarchical Inheritance:
package Hierarchical_Inheritance_Practical;
class R {
void DisplayR(){
System.out.println("Hierarchical_Inheritance: This is Class R's Display method");
}
}
class S extends R{
void DisplayS(){
System.out.println("Hierarchical_Inheritance: This is Class S's Display method");
}
}
class T extends R{
void DisplayT(){
System.out.println("Hierarchical_Inheritance: This is Class T's Display method");
}
}
//Example of Multilevel Inheritance
class U extends R{
void DisplayU(){
System.out.println("Hierarchical_Inheritance: This is Class U's Display method");
}
}
public class V extends T{
public static void main(String args[]){
V v=new V();
v.DisplayR();
}
}
Deep Dive in inheritance
Class A{ (Super/Base class/parent class)
M1(){
}
}
Class B extends A{ (Subclass/Derived class/Child class)
M1(){
}
}
1) A a = new A();
a.M1(); // here M1 of class A is called
2) A a = new B();
a.M1(); //here M1 of class B is called
(Method overriding)
3) A a = new A();
B b=new B();
a=b;
a.M1(); //here M1 of class B is called
(Method overriding)
- In above 2 and 3 object a can call all the methods of A and only those methods of B which are in A.
- In case of variables they can’t be overiden.
-
4) B b = new A(); // Not allowed
package Single_Inheritance_Practical;
class A1{
void M1(){
System.out.println("This is M1 method of Class A");
}
}
class B1 extends A1{
void M1(){
System.out.println("This is M1 method of Class B");
}
}
public class Rahul_Inheritance1 {
public static void main(String[] args) {
A1 a1=new A1();
a1.M1();
A1 a2=new B1();
a2.M1();
A1 a3=new A1();
B1 b3=new B1();
a3=b3;
a3.M1();
//B b= new A(); //not allowed
}
}
Session 4:
Polymorphism
Defination: The ability to exist in multiple forms is called polymorphism.
Types:
1. Dynamic polymorphism(Runtime polymorphism)
2. Static polymorphism(Compile time polymorphism)
1. Polymorphism exibited at runtime is called dynamic polymorphism.
2. JVM bind method call to method body, compiler doesn’t know but jvm know which method is to call, hence also called runtime polymorphism or dynamic binding.
3. JVM identifies which method to call by
a) Parameter type
b) No. of parameters
c) Sequence
Ex: a) void add(int a, float b)
void add(double a, double b)
b) void add(int a, int b)
void add(int a, int b, int c)
c) void add(int a, float b)
void add(float b, int a)
Dynamic polymorphism :
4. Method Overloading and Method Overiding
Method Overloading:
Writing two or more methods in the same class in such a way, that each method has same name but with different method signatures, is called Method Overloading.
Ex: void add(int a, int b)
void add(float a, int b)
Method Overiding:
Writing two or more methods in super and subclasses such that the methods have same name and same signature but different definition(Method body) is called method overriding.
Also called dynamic dispatch.
Ex: class One{
void Calculate(double x){
System.out.println(“Square value:”+(x*x));
}
}
Class Two extends One{
void calculate(double x){
System.out.println(“Square root:”+ Math.sqrt(x));
}
}
Difference between method overloading and method overriding
-Same name but different signatures -same name, same signatures
-same class -Super and Sub class
-return type: same or different -same
-JVM decides by method signatures -JVM decides by the class of the object.
-To extend the already available feature -To provide different implementation for the same feature.
-Code refinement -Code replacement.
Dynamic: Method overloading example.
package oops;
public class MethodOLDemo {
float area, perimeter, areaOfRectangle;
public void calculate(int r){
area= (float)3.14*r*r;
System.out.println("area of circle : "+ area);
}
public void calculate(int a, float r){
perimeter = (float) (a*3.14*r);
System.out.println("perimeter of circle is "+perimeter);
}
public void calculate(int l,int w){
areaOfRectangle = l*w;
System.out.println("areaOfRectangle : "+areaOfRectangle);
}
public static void main(String args[]){
MethodOLDemo mo=new MethodOLDemo();
//mo.calculate(20, 5);
mo.calculate(2, 8.2f);
//mo.sum(2.4, 8);
}
}
Dynamic polymorphism: Method overriding Example.
package Polymorphism_Practical;
// Method Overiding example using dynamic polymorphism
class Animal{
void eating(){
System.out.println("Animal-eating");
}
void running(){
System.out.println("Animal-running");
}
void sleeping(){
System.out.println("Animal-sleeping");
}
}
class Dog extends Animal{
void eating(){
System.out.println("Dog-eating");
}
void running(){
System.out.println("Dog-running");
}
void barking(){
System.out.println("Dog-barking");
}
}
class Cat extends Animal{
void eating(){
System.out.println("Cat-eating");
}
void running(){
System.out.println("Cat-running");
}
void barking(){
System.out.println("Cat-barking");
}
}
class Dynamic_MethodOveridingEx{
public static void main(String args[]){
Animal a= new Dog();
a.eating(); // Method overiding: Dog class's eating method called
a.running();
Animal a1=new Cat();
a1.eating(); // Method overiding: Cat class's eating method called
a1.running();
}
}
Static Polymorphism(Compile time polymorphism):
-Defination: Polymorphism exhibited at compile time is called static
polymorphism.
-Compiler knows which method is called, and at compile time compiler bind
method call to method body, Is called static binding.
- Achieving method overloading using static methods, Private methods and final methods are
examples for static polymorphism.
-All the methods maintain only one copy in memory, that is available to object of class, so java compiler know at compile time that which method is called.
-Only method overloading is possible.
Static Polymorphism: Method overloading Example
package Polymorphism_Practical;
// Method Overloading with static polymorphism example.
public class Static_MethodOverloadingEx {
static double result;
double result1;
private static void sum(int a,int b){
result= a+b;
System.out.println("Result of Two Int parameterised static sum method "+ result);
}
private void sum(int a,double b){
result1= a+b;
System.out.println("Result of int and double parameterised private sum method "+result1);
}
private final void sum(double a,int b){
result1= a+b;
System.out.println("Result of double and int parameterised final sum method "+result1);
}
public static void main(String args[]){
Static_MethodOverloadingEx mo=new Static_MethodOverloadingEx();
mo.sum(2,8);
mo.sum(2, 8.2);
mo.sum(2.4, 8);
}
}
Final class:
-To prevent inheritance
-To declare constants
-ex: final float pi=3.14;
-Method: to prevent overiding
Session 5:
Encapsulation
-Defination:
Binding of members of one entity or class in single unit is called encapsulation.
-Encapsulation is achieved using below 4 access modifiers.
1. private
2. default
2. public
3. protected
1.private: accessed within the class only.
2.default:
-Default are accessible within everywhere in same package. And are not accessible in another package.
3.public:
-Accessible everwhere i.e in same class, subclass, non-subclass within same package & within another package.
4. protected:
-If a member declared as protected then we can access that member anywhere within the current package but only in child classes of outside package.
-protected=default+kids.
-We can access protected members within the current package everywhere either by using parent reference or by child reference, but we can access protected members in outside package only in child classes and we should use child reference only, that is parent reference can not be used to access, protected members from outside package.
Modifiers with variables.
Practical:
package encap1_variable;
class A{
private int j=1;
int k=2;
protected int l=3;
public int m=4;
void MethodOfA(){
System.out.println("In Class A");
System.out.println(j);
System.out.println(k);
System.out.println(l);
System.out.println(m);
}
}
//subclass
class B extends A{
void MethodOfB(){
B b=new B();
System.out.println("In Class B\n");
//System.out.println(b.j);
System.out.println(b.k);
System.out.println(b.l);
System.out.println(b.m);
}
}
//Non-Subclass
class C{
void MethodOfC(){
A a=new A();
System.out.println("In Non-Subclass C\n");
//System.out.println(a.j);
System.out.println(a.k);
System.out.println(a.l);
System.out.println(a.m);
}
}
public class Lab {
private int n=5;
int o=6;
protected int p=7;
public int q=8;
public static void main(String args[]){
A a1=new A();
a1.MethodOfA();
B b=new B();
b.MethodOfB();
C c=new C();
c.MethodOfC();
}
}
package encap1_variable;
//subclass
public class D extends Lab{
public static void main(String args[]){
Lab a2=new Lab();
System.out.println("I am in class D");
//System.out.println(a2.j);
System.out.println(a2.k);
System.out.println(a2.l);
System.out.println(a2.m);
E e=new E();
e.MethodOfE();
}
}
//non-subclass
class E{
Lab a=new Lab();
void MethodOfE(){
System.out.println("MethodOfE");
//System.out.println(a.j);
System.out.println(a.k);
System.out.println(a.l);
System.out.println(a.m);
}
}
package encap2_variable;
import encap1_variable.Lab;
class F extends Lab{
public static void main(String args[]){
//Lab l=new Lab();
F f=new F();
System.out.println("I am in class F");
//System.out.println(f.n);
//System.out.println(f.o);
System.out.println(f.p);
System.out.println(f.q);
}
}
Encapsulation with methods:
Encapsulation with default private methods:
package encap1_method_private;
public class A{
private void m1(){
System.out.println("Class A: m1 method");
}
}
class B extends A{
public static void main(String[] args){
A b=new A();
b.m1();
/* A a=new A();
a.m1();*/
/*
A b=new A();
b.m1();
A a1=new A();
a1.m1();*/
}
}
package encap1_method_private;
public class D extends A{
public static void main(String[] args) {
D d=new D();
d.m1();
}
}
package encap2_method_private;
import encap1_method_private.A;
class C extends A{
public static void main(String[] args) {
/*A a=new A();
A.m1();*/
C c1=new C();
c1.m1();
/*A a1=new C();
a.m1();*/
}
}
Encapsulation with default methods:
package encap1_method_default;
class B{
void m1(){
System.out.println("Class A: m1 method.......");
}
}
public class A extends B{
public static void main(String[] args){
/*B a=new B();
a.m1();*/
A b=new A();
b.m1();
/*B a1=new B();
a1.m1();*/
}
}
package encap1_method_default;
public class D extends A{
public static void main(String[] args) {
D d=new D();
d.m1();
/*B a=new B();
a.m1();*/
}
}
package encap2_method_default;
import encap1_method_default.A;
class C extends A{
public static void main(String[] args) {
/*A a=new A();
A.m1();*/
C c=new C();
c.m1();
/*A a1=new C();
a.m1();*/
}
}
Encapsulation with protected method:
package encap1_method_protected;
class A{
protected void m1(){
System.out.println("Class A: m1 method");
}
}
class B extends A{
public static void main(String[] args){
A b=new A();
b.m1();
/*A a=new A();
a.m1();
A b=new A();
b.m1();
A a1=new A();
a1.m1();*/
}
}
package encap1_method_protected;
class D{
public static void main(String[] args) {
D d=new D();
d.m1();
/*
B a=new B();
a.m1();*/
}
}
package encap2_method_protected;
import encap1_method_protected.A;
class C extends A{
public static void main(String[] args) {
/*A a=new A();
A.m1();*/
C c=new C();
c.m1();
/*A a1=new C();
a.m1();*/
}
}
Encapsulation with public method:
package encap1_method_public;
public class A{
public void m1(){
System.out.println("Class A: m1 method....");
}
}
class B extends A{
public static void main(String[] args){
/*A a=new A();
a.m1();
*/
A b=new A();
b.m1();
/*
B a1=new B();
a1.m1();
*/
}
}
package encap2_method_public;
package encap1_method_public;
public class D extends A{
public static void main(String[] args) {
D d=new D();
d.m1();
}
}
package encap2_method_public;
import encap1_method_public.A;
class C extends A{
public static void main(String[] args) {
/*A a=new A();
A.m1();*/
C c=new C();
c.m1();
/*A a1=new C();
a.m1();*/
}
}
Modifier | Classes | Methods | Variables | blocks | Interfaces | enums | Constructors | |||
| Outer | Inner |
|
|
| Outer | Inner | Outer | Inner |
|
|
|
|
|
|
|
|
|
|
|
|
public | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes | Yes | Yes |
private | No | Yes | Yes | Yes | No | No | Yes | No | Yes | Yes |
protected | No | Yes | Yes | Yes | No | No | Yes | No | Yes | Yes |
(default) | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
final | Yes | Yes | Yes | Yes | No | No | no | No | No | No |
abstract | Yes | Yes | Yes | No | No | Yes | Yes | No | No | No |
static | No | yes | Yes | Yes | Yes | No | Yes | No | Yes | No |
synchronized | No | No | Yes | yes | Yes | No | No | No | No | No |
native | No | No | Yes | No | No | No | No | No | No | No |
strictfp | Yes | Yes | Yes | No | No | Yes | Yes | Yes | Yes | No |
transient | No | No | No | yes | No | No | No | No | No | No |
volatile | No | No | No | Yes | No | No | No | No | No | no |
What is volatile :
Volatile keyword is used to modify the value of a variable by different threads.
Ex : volatile int a;
What is strictfp keyword ?
Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable.
Abstraction:
-Defination: The user requires only some part of the available data, in this case, we can hide the unnecessary data from the user and expose only that data, that is of interest to the user, this is called abstraction.
-In java, Abstraction is achieved using abstract class and interface.
Abstract method:
-Doesn’t contain any body.
-Abstract method is written when the same method has to perform different tasks depending on the object calling it.
Real time example car:
3 entities:
1.You(Know only driving car)
2.Local mechanic(know some part of car & driving).
3.Expert(know everything(All details) of car.
-JVM restrict to create object of abstract class, because unimplemented methods are there in abstract class.
-Contains 0 or more abstract methods.
-We can create reference variable to abstract class.
-Why to use abstract class?
To insist programmers to implement only method names which we specified.
-It is preferable to create reference of abstract class and assign object to it and use it.
-Can contain concrete methods(implemented methods)
-All abstract methods of abstract class should be implemented in it’s subclasses.
-If any abstract method is not implemented then that subclass should be declared as abstract, in this case we can’t create object to subclass, we should create another subclass to this subclass and implement the remaining abstract methods there.
-We should not declare abstract class as final because abstract class depends on it’s subclasses for it’s implementation and final keyword restrict inheritance.
-Abstract methods can’t be static, private or final.
-Abstract class can have constructor.
-All rules of method overriding are applied to abstract class.
Program:
// Achieving Abstraction using Abstract class
package AbstractionPract;
abstract class Different{
abstract void calculate(int x);
}
class Sub1 extends Different{
int Result;
void calculate(int x){
Result=x*x;
System.out.println("Square is: "+Result);
}
}
class Sub2 extends Different{
int Result;
void calculate(int x){
Result=x*x*x;
System.out.println("Cube is: "+Result);
}
}
class Sub3 extends Different{
int Result;
void calculate(int x){
Result=(int) Math.sqrt(x);
System.out.println("SquareRoot is: "+Result);
}
}
class Abstraction_Ex{
public static void main(String args[]){
Different d1=new Sub1();
Different d2=new Sub2();
Different d3=new Sub3();
d1.calculate(4);
d2.calculate(6);
d3.calculate(81);
}
}
Session 6
Interfaces
1.Defination: Interface is a special java class which is fully abstract.
-Ex: CreditCard(Interface)
PayMethods-----> Rupees,Dollars,Pounds(These are implementation classes).
- Have 0 or more abstract methods which are all public and abstract by default.
- Interface can have variables which are public, static, final by default.
- None of the methods can be private, protected or static.
- We can’t create object to an interface, but can create reference of it.
- All the methods of interface should be implemented in it’s implementation classes, if any method is not implemented then that implementation class should be declared as abstract.
- Interface reference can refer to the objects of it’s implementation classes.
- When an interface is written, any third party vendor can provide implementation classes to it.
- An interface can extend another interface.
- An interface can’t implement another interface.
- It is possible to write a class within an interface.
- Java compiler checks wheather all the methods are implemented in the implementation classes or not.
- we can implement multiple inheritance using multiple interfaces.
- Interface can’t be run, because all the methods of interface are abstract, and main method can’t be made abstract.
interface A{
getData();
}
interface B{
getData();
}
interface D{
getData();
}
Class C implements A,B,D{
getData(){
}
}
- When a class is implementing 2 or more interfaces, which has common method, then you have to override that method only once in the subclass, that single implementation provided in subclass will be considered for all the interfaces.
Difference between Abstract class and interfaces
Abstract class | Interface |
1. Abstract class doesn’t support multiple inheritance.
| 1. Interface supports multiple inheritance. |
2. Abstract class can have final, non-final, static, non-static variables. | 2. Interface can have only final and static variables. |
3. abstract class can contain some abstract methods and some concrete methods. | 3. Interface contains only abstract methods. |
4. Abstract class can contain static methods, main method, constructor. | 4. Interface can not contain static method, main method, constructor. |
5. Abstract class can provide implementation of interface. | 5. Interface can not provide implementation of abstract class. |
6. Abstract class is declared using abstract keyword. | 6. Interface is declared using interface keyword. |
// Interface example
package Abstraction_Practical;
interface i1{
int a=30;
public final static int b=20;
void m1();
public abstract void m2();
void show();
}
class Hello implements i1{
public void m1(){
System.out.println("m1");
}
public void m2(){
}
public void show(){
}
}
public class InterfaceDemo {
public static void main(String[] args) {
i1 obj=new Hello();
obj.m1();
obj.m2();
obj.show();
System.out.println(i1.a);
System.out.println(i1.b);
System.out.println(Hello.a);
System.out.println(Hello.b);
}
}
Output:
m1
m2
30
20
m1
m2
30
20
30
20
30
20
Program2:
// Interface example
package Interface_Pract;
interface MyInter{
void Connect();
void Disconnect();
}
class OracleDb implements MyInter{
public void Connect(){
System.out.println("Connected to OracleDb");
}
public void Disconnect(){
System.out.println("Disconnected to OracleDb");
}
}
class SybaseDb implements MyInter{
public void Connect(){
System.out.println("Connected to SybaseDb");
}
public void Disconnect(){
System.out.println("Disconnected to SybaseDb");
}
}
public class InterfaceDemo1 {
public static void main(String[] args) {
MyInter mi1 =new OracleDb();
MyInter mi2 =new SybaseDb();
mi1.Connect();
mi1.Disconnect();
mi2.Connect();
mi2.Disconnect();
}
}
Program 3:
package RahulT.Abstraction_Practical;
interface Car{
void Indigo();
void Zen();
}
class Engineer1 implements Car{
public void Indigo(){
System.out.println("Indigo Internal working 1");
}
public void Zen(){
System.out.println("Zen Internal working 1");
}
}
class Engineer2 implements Car{
public void Indigo(){
System.out.println("Indigo Internal working 2");
}
public void Zen(){
System.out.println("Zen Internal working 2");
}
}
public class InterfaceDemo1 {
public static void main(String[] args) throws Exception {
Car c=new Engineer1();
System.out.println("Methods of Engineer1 class accessed using reference variable of interface Car ");
c.Indigo();
c.Zen();
Car c1=new Engineer2();
System.out.println("Methods of Engineer2 class accessed using reference variable of interface Car");
c1.Indigo();
c1.Zen();
}
}
Output:
Methods accessing using object of subclass
Indigo Internal working 1
Zen Internal working 1
Methods accessing using reference variable of interface Car
Indigo Internal working 1
Zen Internal working 1
Methods accessing using another subclass
Indigo Internal working 2
Zen Internal working 2
Session 7
this keyword
- This is the reference variable that refers to the current object.
1.’this’ keyword can be used to refer current class instance variable.
2. ‘this’ can be used to
invoke current class constructor.
1. ’this’ keyword can be
used to refer current class instance variable.
If we don’t use this keyword let we see what happens.
Program:
package This_Pract;
public class This_Ex {
int eid;
String
ename;
public This_Ex(int eid,String ename){
eid=eid;
ename=ename;
}
void show(){
System.out.println(eid +" " +ename);
}
public static void main(String[] args) {
This_Ex
t=new This_Ex(1,"Rahul");
This_Ex
t1=new This_Ex(2,"Pavan");
t.show(); // 1
Rahul
t1.show(); // 2 Pavan
}
}
o/p:
0 null
0 null
-
In the above example, parameter and
instance variables are same, so answer comes 0
null, hence this keyword is used
to distinguish between local variable and instance variable.
-
We can solve the above problem by ‘this’
keyword, as shown in the following program.
package This_Pract;
public class This_Ex2 {
int eid;
String
ename;
public This_Ex2(int eid,String ename){
this.eid=eid;
this.ename=ename;
}
void show(){
System.out.println(eid +" " +ename);
}
public static void main(String[] args) {
This_Ex2
t=new This_Ex2(1,"Rahul");
This_Ex2
t1=new This_Ex2(2,"Pavan");
t.show();
t1.show();
}
}
o/p: 1 Rahul
2 Pavan
2.
‘this’ can be used to invoke current class constructor.
- This approach is better if we have
many constructors(Constructor chaining) in the class and want to reuse that
constructor.
Program:
//‘this’
can be used to invoke current class constructor.
package ThisPack;
public class ThisEx3 {
int eid;
String
ename;
public ThisEx3() {
System.out.println("Student
details are as follows");
}
public ThisEx3(int eid, String ename) {
//ThisEx3 t =
new ThisEx3(); // we can call
constructor by creating object but memory will be wasted
this();
this.eid = eid;
this.ename = ename;
}
void show1(){
System.out.println(eid +" " +ename);
}
public static void main(String[] args) {
ThisEx3
t1=new ThisEx3(51,"Ahir");
t1.show1();
}
}
Comment
-
Comments are used in java to write
down about the author, purpose and information of the program.
-
Single line comment: //
Compiler ignores only the sentence
which is written after comment.
Ex: //This is single line comment
-
Multiline
Comment
Compiler ignores whatever is written
in between /* and */.
Ex:
/* This is multiline comment, remember it
This is multiline comment, remember it
again
*/
Session 8
Packages
-keyword, used to keep similar types of files
together, to avoid accidental deletion, files will be easily accessible.
-syntax : package package_name;
-predefined and userdefined, predefined like Date
class available in java.util, java.sql
1.Classes or interfaces which handle same task
are put into the same directory, this directory or folder is called package.
2.Ex: import java.io.*;
-Here java is a directory name and io is
a subdirectory name within it.
3. Advantages:
-All the
classes and interfaces performing the same task placed together in same
package.
-Hide the classes and interfaces in a
subdirectory, so that accidental deletion of classes and interfaces will be
avoided.
-Classes and Interfaces of a package are isolated
from the classes and interfaces of another package.
Ex: There is a date class in java.util package
and also there is another date class available in java.sql package.
-Classes and interfaces of a package are like
books in a liabrary and can be reused several times.
Types of Packages:
-Built in package
-Userdefined package
-Built in package
-Some of the important packages of Java SE
1. java.lang:
-lang stands for language. This package got
primary classes and interfaces, essential for developing basic java program.
It consists of wrapper classes which convert
primitive datatypes into objects.
-gc() method (Garbage collection) in both runtime
and system classes of java.lang package.
2. java.util:
-util stands for utility, contains stack,linked
list,Hashset,vector,array etc.
These classes are called collections.
3. java.io:
io stands for input and output. Helps to store
data in the form of files.
4. java.sql:
Helps to connect to database like sql etc.
Userdefined packages:
-Users of java language can also create their own
packages, these are called userdefined packages.
-syntax:
package package_name;
// to create a package
package package_name.subPackageName; // to create a
subpackage within a package
Program:
//Creating a package pack and store
Multiplication class in it.
package RT;
public class PackageEx {
void Mul(int a1,int a2){
int ans;
ans=a1*a2;
System.out.println("Multiplication="+ans);
}
public static void main(String[] args) {
int a1=5,a2=3;
PackageEx
p=new PackageEx();
p.Mul(a1,a2);
}
}
Exception
handling
1.Defination:
Exceptions are events that occour during the
execution of programs that interrupt the normal flow of instructions.
2.Why we use Exception handling:
Because, to handle compile time exceptions and At
the time of running the program, exception can be occoured, this time program
can be closed abnormally, and related important data can be lossed, or some
devices may crash, so to avoid the abnormal closing of the program, we handle
the exceptions. To handle such a exceptions we use Exception handling.
3. At the time of running the program,
we may get some problems.
When problem arises in program then
following tasks happen.
-Firstly control will transfer to jvm.
-JVM analizes the problem.
-JVM identifies the corresponding java
class(Exception or Error).
-Creates the object of the java class identified.
-Throws the object created.
-If our program is not catching the object thrown
by jvm, then jvm catches the object.
-Displays the corresponding message.
-Terminates the program execution.
4. Problems coming in the program can
be devided into 2 types.
1.Exceptions
2.Errors.
Both Exception and Errors are java
classes.
Java.lang(package)
Object(Class)
Throwable(Class)
Exception(Class)
Error(Class)
ArithmeticException(extends NoClassDefFoundError(extends
RuntimeException(Class)) LinkageError(class))
5.Types:
a. Built-in exception
b. User defined exception
a. Built-in exceptions:
Exceptions which are already implemented along
with java or other technologies are called as built-in exceptions.
Ex:
a. Arithmetic Exception
b. SQLException
c. IOException
d. IllegalTypeException
e. ArrayIndexOutOfBoundsException
f. NullPointerException.
b. Userdefined Exception:
Exceptions which are implemented by developer as
per application requirement, such exceptions are called Userdefined exception.
6. Try and Catch Block
If we want to monitor java statements for
problems(Exception/Error)
Then place those statements in try block.
Ex:
try{
statement
1;
statement
2;
Statement
3;
}
Catch(Exception e){
Statement
4;
}
Statement
5;
Case 1:
Assume that statement 2 is raising an exception
then following statements will run.
Statement 1
Statement 2
Statement 4
Statement 5
When exception will raised in try block statement
then control will transfer to catch block by skipping the statements after the
statement which raised exception.
Case 2:
Assume that no exception is raised then following
statements will be executed.
Statement 1;
Statement 2;
Statement 3;
Statement 5;
When exception is not raised in a try block then
control will not go to catch block.
Rules:
1.We can write multiple try catch inside try
block .
2.We should not write any statement between try
block and catch block.
6.Nested try catch blocks:
try catch blocks written in try catch block are
called nested try catch block.
Ex: Class ExceptionEx{
Public
static void main(String args[]){
try{
stmts
try{
stmts
}
catch(){
stmt;
}
}
catch(Exception
e){
stmt;
}
}
}
Need for implementation of nested try
catch block:
Syntax:
try{
try{
stmt
1;
stmt
2;
stmt
3;
stmt
4;
}
catch(){
System.out.println(“Please check the
Internet connectivity”);
}
stmt
5;
try{
stmt 6;
stmt 7;
stmt 8;
stmt
9;
}
catch(){
System.out.println(“Please
check the Memory capacity”);
}
stmt
10;
stmt
11;
}
catch(){}{
System.out.println(“Please check the
syntax of above code”);
}
Program:
package
ExceptionPract;
//Program to handle arithmetic
exception
public class
ExceptionNestedTryCatchEx {
public static void main(String[] args) {
try {
int x,a=0;
x=10/a;
System.out.println("Division
is:" +x);
}
catch(Exception e) {
System.out.println("please
divide by non-zero number.");
}
System.out.println("close
all connections");
}
}
7. finally:
-To execute set of statements always without
fail, then these statements are placed in a finally block.
-finally block must be placed after try or catch
block.
-Why to use finally:
To release the resources like
DBconncetion,iostreams.
-following are some cases where statements after
the catch block will not be executed.
1.When return statement is there before the
statement, may be inside try or inside catch block.
Ex:
package
ExceptionPract;
public class Test {
public static void main(String[] args) {
try{
int x,a=5;
x=10/a;
System.out.println(x);
return;
}
catch(Exception e){
e.printStackTrace();
//System.out.println("Please provide the value to variable
a exceptio");
}
finally{
System.out.println("I am in finally
block");
}
}
}
-We can also write finalize() method to release
the resourses, but finally block is recommended.
Various scenarios of try catch finally
block:
Case 1:
try{
}
catch(X e){
}
--> Valid
Case 2:
try{
}
catch(X e){
}
catch(X e){
}
-->Invalid
CE(Compile time error): Exception X has already
been caught.
Note: In catch block, exceptions should not be
repeated.
Case 3:
try{
}
catch(X e){
}
catch(Y e){
}
-->Valid.
Note: Order of catch block exceptions should be
child to parent.(Child exceptions first then parent exceptions).
Ex:
try{
}
catch(ArithmeticException ae){
}
catch(Exception e){
}
--> Valid
try{
}
catch(Exception e){
}
catch(ArithmeticException ae){
}
-->InValid.
CE(Compile time error): Exception ArithmeticException
has already been caught.
Case 4:
try{
}
-->Invalid:
Compile time Error: try without catch or finally
Case 5:
catch{
}
-->Invalid:
Compile time Error: catch without try
Case 6:
finally{
}
-->Invalid:
Compile time Error: finally without try
Case 7:
try{
}
finally{
}
-->valid:
Note: Here, In above, question may arise that, we
not written catch block then what is the need of try block.
-->In above, exception may arise in try block,
if exception occour then before closing the program abnormally, the statements
written in finally block will be executed. In finally block, the important
statements like closing connection statement or closing network statement may
be there.
Case 8:
try{
}
System.out.println(“Welcome User…”);
catch(Exception e){
}
-->Invalid:
CE: try without catch or finally
Or
catch without try
Case 9:
try{
}
catch(ArithmeticException e){
}
System.out.println(“Welcome User…”);
catch(Exception e){
}
-->Invalid
CE: catch without try
Case 10:
try{
}
catch(Exception e){
}
System.out.println(“Welcome User…”);
finally{
}
-->Invalid
CE: finally without try
Case 11:
try{
}
catch(Exception e){
}
try{
}
finally{
}
-->Valid
Case 12:
try{
}
finally{
}
catch(Exception e){
}
--> Invalid
CE: catch without try
Case 13:
try{
}
catch(Exception e){
}
finally{
}
finally{
}
--> Invalid
CE: finally without try
Case 14:
try{
try(){
}
catch(X e){
}
finally(){
}
}
catch(X e){
}
--> Valid.
Case 15:
try{
}
catch(X e){
try(){
}
finally(){
}
}
--> Valid.
Case 16:
try{
stmt;
}
catch(X e){
}
finally{
try(){
}
finally(){
}
}
--> Valid.
Note:
1. Curly braces are mandatory for try,catch or
finally block, although it contains one statement or more than one statement.
Difference between final,finally and
finalize()
final:
1.final is used to apply restrictions on
class,
method and variable. Final class can't be
inherited,
final method can't be overridden and final
variable
value can't be changed.
2. final is a keyword.
finally
1.finally is used to execute
important code, it will be executed whether exception is handled or not.
2.finally is a block.
finalize()
1.finalize is used to perform clean up processing just before object
is garbage collected.
2. finalize is a method.
Types of Exception:
-Checked
Exception(Compile time exception)
-SQLException
-IOException
-Unchecked Exception(Run time
exception)
-ArithmeticException
-ArrayIndexOutOfBoundException
Checked Exception:
1.Defination: The exceptions which are checked by
the compiler for smooth execution of program are called checked exceptions.
2.Ex:
-IOException
-SQLException
-DataAccessException
-ClassNotFoundException
Unchecked exception:
1.Defination: Exceptions
which are not checked by compiler are called unchecked exceptions.
2.Ex:
-NullPointer Exception
-ArrayIndexOutOfBoundException
-IllegalArgumentException
-IllegalStateException
-ArithmeticException
Difference between checked and
unchecked exceptions
|
Checked |
UnChecked |
|
Required
to be handled at compile time |
-Not
required to be handled at compile time. |
|
Direct
subclass of Exception |
Direct
Subclass of Runtime Exception |
|
Represent
scenario with higher failure rate |
Are
mostly programming errors |
Summary:
-Both are handled using try,catch,finally.
-Both have same functionality.
-JDK 7 provides catching multiple exceptions in
one catch block.
Difference between Exception and Error:
-Exceptions
can be handled but error can’t be handled.
-Exception
examples
-ArithmeticException
-IOException
-Error
examples
-NoSuchMethodError
-NoClassDefFoundError
-OutOfMemoryError
-StackOverFlowError
throw keyword:
1.Why to use: throw is a keyword, used to explicitly
throw an exception, which we do not want to handle.
-we can either throw checked or unchecked
exception.
-Programmer throws exception object and jvm
catches it.
-The method in which the exception is raised,
this method is responsible to send the exception object to jvm,then jvm checks
the program and if the exception is not handled then this exception object is
handed over to ‘default exception handler’ and
‘default exception handler’ terminates the program abnormally and print
the exception information to the console, all this happens implicitly.
Ex:
Class XYZ{
Public
static void main(String args[]){
System.out.println(10/0);
}
}
Message will be printed on console i.e “Exception
in thread main: java.lang.AE: / by zero at XYZ.main.
-If we want to send the exception object
explicitly then we should use ‘throw’ keyword.
-Sending the exception object to jvm explicitly.
Ex:
Class XYZ{
Public
static void main(String args[]){
throw
new ArithmeticException(“divide by zero”);
}
}
}
Message will be printed on console i.e “Exception
in thread main: java.lang.AE: devide by zero at XYZ.main.
-Best use of throw keyword is for to show
userdefined or customized exceptions.
-Case 1:
throw ae:
if e refers null then we will get null pointer exception else we will
get arithmetic exception in following.
Ex:
package
ExceptionPract;
public class ExceThrowCase1_1 {
static ArithmeticException ae=new ArithmeticException();
public static void main(String[] args) {
throw ae;
}
}
Msg:
RE:
Exception in thread "main" java.lang.ArithmeticException
-package ExceptionPract;
public class ExceThrowCase1_2 {
static ArithmeticException ae;
public static void main(String[] args) {
throw ae;
}
}
Msg:
RE:
Exception in thread "main" java.lang.NullPointerException
Case 2: After throw, we are not allowed to write
any statement after it, otherwise we will get compile time error “unreachable
statement”.
- package ExceptionPract;
public class ExceThrowCase2_2 {
public static void main(String[] args) {
throw new ArithmeticException("/ by 0");
System.out.println("How
are you...");
}
}
Output:
CE: unreachable code
Case 3:
We can use throw keyword only for throwable
types, if we are trying to use for normal java objects, then we will get
compile time error,saying incompatible types.
- package
ExceptionPract;
public class ExceThrowCase3_1 {
public static void main(String[] args) {
throw new
ExceThrowCase3_1();
}
}
Output:
CE:
error: incompatible types
throw new ExceThrowCase3_1();
required: Throwable
-package
ExceptionPract;
public class ExceThrowCase3_2 extends RuntimeException {
public static void main(String[] args) {
throw new ExceThrowCase3_2();
}
}
Output:
RE:
Exception in thread main
throws:
1.why:
-throws is a keyword, which is used to declare an
exception.
-To declare the method level exception.
-If programmer doesn’t want to handle checked
exception, he should throw them out using throws clause, otherwise there will
be an error flagged by java compiler.
In our program, if there is a possibility of
rising checked exception then compulsory we must handle that checked exception
otherwise we will get compile time error saying “Unreported exception x must be
caught or declared to be thrown”.
2.Program:
/* Author : Mahesh Hundekari
purpose : throws demo
*/
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public class ThrowsDemo1 {
public static void main(String args[]) throws IOException,
InterruptedException{
//declare
variables
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
//read input
System.out.println("Enter
number");
String name = br.readLine();
//Display
result
System.out.println("You
entered : "+name);
Thread.sleep(1500);
}
}
If we not throws exception then it will
show following compile time error.
error: unreported exception IOException; must be
caught
or declared to be thrown
-If the main thread is sleeping then there may be
chance of other thread will become interrupted.
If we not throws Interrupted exception
then it will show following compile time error.
error: unreported exception InterruptedException;
must be caught
or
declared to be thrown
Note 1 : We can handle the above exception by
writing try catch block or we can deliver it to other(Caller(jvm/other method))
using throws keyword.
Note 2:
throws keyword is used only for checked exception and not used with
unchecked exception, if we want to use it with unchecked exception then we can
but no impact of it.
Note 3: throws keyword is used, only to convince
the compiler, usage of throws keyword doesn’t prevent, abnormal termination of
program so it is recommended that use try catch block.
throws keyword scenario:
Ex:
package ExceptionPract;
public class
ExceptionThrows4 {
public static
void main(String[] args) throws InterruptedException{
//// what if we remove
"throws InterruptedException" from here
startWork();
}
public static
void startWork() throws
InterruptedException{ // what if we remove "throws
InterruptedException" from here
startMoreWork();
}
public static
void startMoreWork()throws InterruptedException{ ////
what if we remove "throws InterruptedException" from here
Thread.sleep(2100);
}
}
In the above program if we remove anyone of above
throws, then the code won’t compile.
Case
1: We can use throws keyword for constructor
and
methods
but not for class.
Ex:
package
ExceptionPract;
public class
ExceptionThrows5 /* throws Exception*/ {
//If I write throws Exception above then
code will not get compiled
ExceptionThrows5() throws
Exception{
}
void Method1()throws
Exception{
}
public static void
main(String[] args) {
System.out.println("Hi this is throws testing...");
}
}
Output: Hi this is throws testing...
Case
2: we can use throws keyword only for Throwable types.
Ex
1:
package
ExceptionPract;
public class ExceptionThrows6 {
public static void main(String[] args) throws ExceptionThrows6{
System.out.println("This is testing for
throws");
}
}
Output:
CE:
Incompatible types
public
static void main(String[] args) throws ExceptionThrows6{
required:
Throwable
Ex 2:
package
ExceptionPract;
public class ExceptionThrows7 extends RuntimeException{
public static void main(String[] args) throws ExceptionThrows7{
System.out.println("This is testing for
throws");
}
}
Output:
This is testing for throws
Interview questions
on throws :
1. difference
between throw and throws keyword.
|
It is used to create a new Exception object
and throw it |
It is used in method definition, to declare
that a risky method is being called. |
|
Using throw keyword you can declare only one
Exception at a time |
Using throws keyword you can declare
multiple exception at a time. |
|
Example: throw new
IOException("can not open connection"); |
Example: throws IOException,
ArrayIndexBoundException; |


Comments
Post a Comment