class and object
class and object
Object: object is an instance of a class and inorder access the fields and methods we need to create
an object for the class.
class Mobile {
public String brand;
public String model;
public double price;
public static int batteryCapacity;
System.out.println("\nMobile Details:");
myPhone.displayDetails();
class Mobile {
public String brand;
public String model;
public double price;
public static int batteryCapacity;
Example:Human
class Human {
public String name;
public int age;
public String gender;
Method Overloading :
It is the process of defining more than one method with the samename for different
purpose
In Method Overloading Method name must be same, list of arguments should not be
same , return type may or may not be same
Example :1
class Calculator {
int add(int a, int b) {
return a + b;
}
public void add(int a,int b,int c)
{
System.out.println("Addition of three integers is :"+(a+b+c));
}
String add(String a, String b) {
return a + " " + b;
}
double add(double a, double b) {
return a + b;
}
class Test {
static void display(int x) {
System.out.println("Display method with int: " + x);
}
static void display(String s) {
System.out.println("Display method with String: " + s);
}
void display(int x, String s) {
System.out.println("Display method with int and String: " + x + " " + s);
}
EX:2
class TestIQ {
void method1(byte b) {
System.out.println("byte : " + b);
}
void method1(short s) {
System.out.println("short : " + s);
}
void method1(int i) {
System.out.println("int : " + i);
}
EX:3
class TestIQ {
void method1(byte b) {
System.out.println("byte : " + b);
}
void method1(short s) {
System.out.println("short : " + s);
}
void method1(int i) {
System.out.println("int : " + i);
}
EX:4
class Testing {
void method1(float x) {
System.out.println("Mtd-1 Float : " + x);
}
EX:5
class IQ{
public static void main(String args[]) {
System.out.println("Hello Dear");
IQ i = new IQ();
int sq = i.main(5);
System.out.println("Result is : " + sq);
}
O/pHello Dear
Result is : 25
This :
EX:1
class Test
{
int x=111;
public void method1()
{
int x=222;
System.out.println(x);
System.out.println(this.x);
}
public static void main(String[] args) {
Test t=new Test();
t.method1();
}
}
void display() {
System.out.println("x value is : " + x);
System.out.println("y value is : " + y);
}
Type of Constructors :
Default constructor
Parameterized Constructor
Copy Constructor
Default constructor:
EX:1
class Rect {
float l, b;
Rect(){
l = 4.0f;
b = 4.0f;
}
float findArea() {
return (l * b);
}
2. Parameterized Constructor:
class Rect {
float l, b;
Rect(float l,float b){
this.l =l;
this.b =b;
}
float findArea() {
return (l * b);
}
3. Constructor Overloading :
4.constructor chaining
5. Copy Constructor :
class Sample {
int x, y;
Sample() {
x = 222;
y = 444;
}
Sample(Sample o) {
x = o.x;
y = o.y;
}
void display() {
System.out.println("x val is: " + x);
System.out.println("y val is: " + y);
}
Note: we should not declare static variable in the constructor , but we can use static variables in the
constructor
1.Class
2.object
3. Inheritance
4. Abstraction
5. Polymorphism
6. Encapsulation
Types Of Inheritance:
o Has-a relationship is the process of creating an object of the super class into
subclass
o By the reference of the super class we can access the properties of the
super into sub class
EX:Has A
class Superclass {
int x = 100;
class AnotherClass {
public static void main(String args[]) {
Subclass sb = new Subclass();
System.out.println("y val is: " + sb.y);
System.out.println("x val is: " + sb.sa.x);
sb.display();
sb.sa.display();
}
}
EX:is A
class SuperA {
private int x = 111;
int y = 222;
static int z = 333;
}
}
EX:2 :mlutilevel
class Parent {
int x = 10;
int y = 20;
static int z = 30;
}
}
3.Hierarchical Inheritance
class Parent {
int x = 10;
int y = 20;
static int z = 30;
}
}
EX:multiple
public class Parent{
int x = 10;
int y = 20;
static int z = 30;
EX:Hybrid
class Parent {
int x = 10;
int y = 20;
static int z = 30;
}
}
Note: “Java doesn’t support multiple and its related combinations using through
classes but, it is possible by using through interfaces.
If both instance field of the sub and super class are declared with the same
name the priority is given to instance field of the “subclass”. If you want
access instance field of the “superclass” then we have to make use of
“super” keyword
is not supported in the static context.
class SuperA {
int x = 111;
}
void method1() {
int x = 333;
System.out.println("local var " + x);
System.out.println("Instance var of SubB : " + this.x);
System.out.println("Instance var of SuperA : " + super.x);
}
}
class Main{
public static void main(String[] args) {
SubB sb = new SubB();
sb.method1();
}
}
EX:
class A {
int x = 10;
}
class B extends A {
int x = 20;
int getSuperX() {
return super.x;
}
}
class C extends B {
int x = 30;
void method1() {
System.out.println("x in C (Current Class): " + this.x);
System.out.println("x in B (Parent): " + super.x);
System.out.println("x in A (Grandparent): " + getSuperX());
}
}
public class Main{
public static void main(String args[]) {
C c = new C();
c.method1();
}
}
class Main{
public static void main(String args[]) {
SubB sb = new SubB();
sb.method1();
}
}
If Super class and Sub class both are defined with the parameterized
constructors ,then we must call the parameterized constructor of the super
class by the parameterized constructor of subclass explicitly. Other wise
parameterized constructor of the sub class is trying to call default
constructor of the super
EX 1:first point
class SuperA {
SuperA() {
System.out.println("Def const of SuperA");
}
}
class Main{
public static void main(String args[]) {
SubB sb=new SubB();
}
}
EX:2 point 2
class SuperA {
SuperA() {
System.out.println("Def const of SuperA"); //1
}
SuperA(int x) {
this();
System.out.println("Para const of SuperA X val : " + x); //2
}
}
class Main{
public static void main(String args[]) {
SubB sb = new SubB();
}
}
EX 3: point 3
class SuperA {
SuperA() {
System.out.println("Def const of SuperA");
}
SuperA(int x) {
System.out.println("Para const of SA " + x);
}
}
class Main{
public static void main(String args[]) {
SubB sb = new SubB(123);
}
}
Note : If you call either default or parameterized constructor of the subclass
then internally JVM will call “Default constructor “ of the Super class only
o if you want call an existed constructor inside of another constructor of the same
class then we have to make user of “this( )”
o If you want call an existed constructor of the super class into another
constructor of the sub class then we have to make use of “super( )”
Polymorphism:
Poly means many
Morphism means forms or behaviors
o Compile-time Polymorphism
o Run-Time Polymorphism
Compile-Time Polymorphism:
Run-time Polymorphism:
Overloading :
It is the process of defining more than one method with the same name
for different purpose
In method overloading , method name must be same, list of argument
should not be same,return type may or may not be same
Overloading can be done either in the same class or in its inherited class
Overriding :
It is the process of defining sub class method same as super class method
In overriding method name must be same, list of arguments must be same
and return type must be same
Overriding is possible only in its inherited class [is-a relationship]
Whenever you want use super class method in the sub class with different
implementation , then will go for overriding
EX:compile time
class Parent {
void method1(int a,int b) {
System.out.println("the sum of two integers is " + (a+b));
}
}
The super class reference variable can hold the same class object.and it can
also hold any of it’s subclass Object implicitly called upcasting or
generalization.
class SuperA {
void displaySuperA() {
System.out.println("This is SuperA");
}
}
class Main {
public static void main(String[] args) {
SuperA a = new SuperA();
SubB b = new SubB();
A SubClass reference variable can hold the object of same class . but it can’t hold
the object of it’s super class implicitly. But we can make it possible explicitly using
“downcasting” or specialization.
EX:1
class SuperA {
void displaySuperA() {
System.out.println("This is SuperA");
}
}
class Main {
public static void main(String[] args) {
SuperA a=new SubB(); //and SubB class
SubB b = new SubB(); // SubB is having the object of SuperA only
//b=a; CE
b=(SubB)a;
}
}
}
}
EX:IQ
import java.lang.Object.*;
class TestIQ {
public static void main(String args[]) {
Object o; // Object reference
Integer i = new Integer(10);
Float f = new Float(3.14f);
String s = new String("Shashi");
o = f; // Upcasting to Object
System.out.println(" object type f val is :"+o);
Float fCast = (Float) o; // Downcasting to Float
System.out.println("Float type f value: " + fCast);
o = s; // Upcasting to Object
System.out.println(" object type s val is :"+o);
String sCast = (String) o; // Downcasting to String
System.out.println("String type s value: " + sCast);
}
}
Abstraction :
Abstract Methods:
Example:
int sum(int x,int y) //non abstract method
{
int s; s=x+y; retrun s;
}
Example:
void sum(int x,int y) //null body method
{}
3.Abstract method
is method which is not having body, just it is a declaration
Example: abstract
void sum(int x,int y);
(*star)In the class we can define only non abstract methods, but not abstract
methods
If we want to work with abstract methods,then we have to declare that abstract
method in Abstract class.
Abstract class:
if we declare any class with abstract key word is called abstract class.
Note : Creating an object for an abstract is nothing but creating an object any of
its Concrete class
Concrete class is a class which is overridden all the abstract methods of its
super class
Every Concrete class is subclass , But Every subclass is not Concrete class
EX:we cant create object direcly 4rth point and star point
Ex:Shapes Example
abstract class Shapes {
abstract void findArea(float dim1, float dim2);
}
class Triangle extends Shapes {
void findArea(float base, float height) {
float area = 0.5f * base * height;
System.out.println("Area of Triangle: " + area);
}
}
class Rect extends Shapes {
void findArea(float length, float width) {
float area = length * width;
System.out.println("Area of Rectangle: " + area);
}
}
class Circle extends Shapes {
void findArea(float radius, float unused) {
float area = (float) (Math.PI * radius * radius);
System.out.println("Area of Circle: "+ area);
//System.out.printf("Area of Circle: %.2f\n", area);
}
}
class Square extends Shapes {
void findArea(float side, float unused) {
float area = side * side;
System.out.println("Area of Square: " + area);
}
}
public class Main{
public static void main(String[] args) {
Shapes s = new Triangle();
s.findArea(4, 4);
s = new Rect();
s.findArea(5, 5);
s = new Circle();
s.findArea(3,2);
s = new Square();
s.findArea(6,6);
}
}
import java.util.Scanner;
abstract class Bank {
abstract void calculateInterest(String name, String accNum, float depAmt);
}
class SBI extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 3;
} else if (depAmt <= 50000) {
rate = 5;
} else {
rate = 7;
}
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("SBI Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
class Axis extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 4;
} else if (depAmt <= 50000) {
rate = 6;
} else {
rate = 7;
}
System.out.println("----------------------------");
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("\nAxis Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
class ICICI extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 5;
} else if (depAmt <= 50000) {
rate = 6;
} else {
rate = 7;
}
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("----------------------------");
System.out.println("ICICI Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
class HDFC extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 5;
} else if (depAmt <= 50000) {
rate = 7;
} else {
rate = 8;
}
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("----------------------------");
System.out.println("HDFC Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
Interface is the standard and public ways of defining the classes Interface is
also known as pure abstract class
A class is collection of non abstract methods
An abstract class is the collection of both abstract or non abstract methods
An interface is the collection of abstract methods only
By default all the variables in the interface “public final static”
By default all the methods in the interface “public abstract”
EX:interface
interface IntA
{
int x=10; //public static final
void method1(); //public abstract
}
Note: What is difference between interface Functional Interface and Marker
interface ?
An Interface : is collection of abstract methods
import org.jcp.xml.dsig.internal.SignerOutputStream;
@FunctionalInterface
interface SuperA
{
void method1(); //by default public abstract
}
class SubB implements SuperA
{
public void method1()
{
System.out.println("overriden method in SubB class");
}
}
class Main{
public static void main(String args[]){
SuperA ia=new SubB();
ia.method1();
}
}
Marker interface is an interface which is not having any abstract methods in it. In
simple word it is an empty interface
o java.lang.Cloneable | java.awt.event.ActionListener
o java.io.Serializable
Note:Point1
interface SuperA{
void method1();
}
abstract class SubB implements SuperA
{
}
public class Main {
public static void main(String[] args) {
}
}
Note:Point2
interface SuperA{
void method1();
}
class SubB implements SuperA
{
@Override
public void method1()
{
}
}
class Main{
public static void main(String args[]){
SuperA ia=new SubB();
ia.method1();
}
}
Note: Creating an object for an interface is nothing but creating an object for any
of it’s implemented class.
interface SuperA{
public abstract void method1();
}
class SubB implements SuperA{
@Override
public void method1()
{
System.out.println("Overriden method1 in SubB");
}
}
class Main{
public static void main(String args[]){
SuperA ia=new SubB();
ia.method1();
}
}
interface IA {
void method1();
}
interface IB {
void method1();
}
class SubB implements IA, IB {
@Override
public void method1() {
System.out.println("Overridden method1 of IA");
}
@Override //we cant achive the overriding in the same class no use
public void method1() {
System.out.println("Overridden method2 of IB");
}
}
class Main {
public static void main(String[] args) {
SubB s=new SubB();
s.method1();
}
}
O/P:
Overridden method1 of IA
class A {
void method1()
{
System.out.println("this is method1 from class A");
}
}
class B {
void method1()
{
System.out.println("this is method1 from class B");
}
}
interface B{
int VALUE = 20;
}
class C implements A,B{
}
public class Main {
public static void main(String[] args) {
C obj = new C();
//System.out.println("Value by using obj ref" + obj.VALUE); //confusion
System.out.println("Static method from interface A: "+A.VALUE);
System.out.println("Static method from interface B: "+B.VALUE);
}
}
O/P:
Static method from interface A: 10
Static method from interface B: 20
class A {
int VALUE = 10;
}
class B{
int VALUE = 20;
}
class C implements A,B{
}
public class Main {
public static void main(String[] args) {
C obj = new C();
System.out.println("Value by using obj ref" + obj.VALUE); //confusion
}
}
class A {
public static int VALUE = 10;
}
class B{
public static int VALUE = 20;
}
class C extends A,B{ // this that first case
}
public class Main {
public static void main(String[] args) {
C obj = new C();
//System.out.println("Value by using obj ref" + obj.VALUE); //confusion
System.out.println("Static method from interface A: "+A.VALUE);//while working
with classes first case fails here
}
}
class A {
static int VALUE = 10;
}
class B extends A {
static int VALUE = 20;
}
}
}
//O/P:
Value from objB as B reference: 20
static VALUE from A : 10
static VALUE from B : 20
class A {
int value = 10;
}
class B extends A {
int value = 20;
}
interface A {
int VALUE = 10;
}
interface B extends A {
int VALUE = 20;
}
class C implements B{
}
public class Main {
public static void main(String[] args) {
C objC = new C();
System.out.println("Value from objC as C reference: " + objC.VALUE);
System.out.println("Static method from interface A: "+A.VALUE);
System.out.println("Static method from interface B: "+B.VALUE);
}
}
EX:IQ
interface IA {
void method1();
}
interface IB {
void method2();
}
class SubB implements IA, IB {
@Override
public void method1() {
System.out.println("Method1 from IA");
}
@Override
public void method2() {
System.out.println("Method2 from IB");
}
}
public class Main {
public static void main(String[] args) {
SubB s=new SubB();
s.method1();
s.method2();
IA ia = new SubB();
ia.method1(); // Valid: IA has method1()
//ia.method2(); // Compile-time error: IA doesn't have method2()
IB ib = new SubB();
ib.method2();// Valid: IB has method2()
//ib.method1(); // Compile-time error: IB doesn't have method1*/
}
}
interface IA {
void existingMethod();
default void newMethod()
{
System.out.println("Default method in interface IA");
}
}
class SubA implements IA {
@Override
public void existingMethod() {
System.out.println("Overridden existingMethod in SubA");
}
/*@Override
public void newMethod() {
System.out.println("Overridden default method in SubA");
}*/
}
class SubB extends SubA {
@Override
public void existingMethod() {
System.out.println("Overridden existingMethod in SubB");
}
/*@Override
public void newMethod() {
System.out.println("Overridden default method in SubB");
}*/
}
public class Main {
public static void main(String[] args) {
IA obj1 = new SubA(); // we can also give SubA s=new SubA();
obj1.existingMethod();
obj1.newMethod(); // Calls overridden version in SubA
IA obj2 = new SubB(); //we can also give SubB s=new SubB();
obj2.existingMethod();
obj2.newMethod(); // Calls overridden version in SubB
}
}
O/P:
interface IA {
default void method1() {
System.out.println("Executing method1...");
commonLogic();
}
Executing method1...
Common logic executed by both method1 and method2.
Executing method2...
Common logic executed by both method1 and method2.
EX:IQ
interface IA {
void method1(); // public abstract
}
interface IB extends IA {
void method2();
}
class SubB implements IB {
@Override
public void method1() {
System.out.println("method1 of IA");
}
@Override
public void method2() {
System.out.println("method2 of IB");
}
}
class InterfaceDemo {
public static void main(String args[]) {
IA ia = new SubB();
ia.method1();
// ia.method2(); // CE (Compile-time error)
IB ib = new SubB();
ib.method2();
ib.method1();
class A{ }
class B{ }
interface C{ }
interface E{ }
1.class D extends A{ } //valid
2.class D extends A,B{ } //invalid
3.class D extends A implements C{ } //valid
4.class D implements C extends A{ } // invalid
5.class D implements C extends A,B{ }//invalid
6.class D implements C,E extends A{ }//invalid
7.class D extends A implements C,E{ }//valid
In c and c++ in order to make any variable value as constant then we have to
make use of “const” keyword
class A{
final int VALUE = 100; // Declare final variable
void changeValue() {
// Attempting to modify the final variable
//VALUE = 200; // This line will cause a compilation error
}
Final Methods :
if we define any method with final modifier then those methods are not
overridden ,but those are inherited.
class Parent {
final void display() {
System.out.println("This is a final method in the Parent class.");
}
}
/*@Override
void display() {
System.out.println("Trying to override the final method in Child class.");
}*/
O/P:1
If you ovverride
Main.java:11: error: display() in Child cannot override display() in Parent
void display() {
^
overridden method is final
1 error
Final Classes:
Defining a class with “final” modifier. Final classes are not inherited . but we can
create an Object and we access the members of the classes using object ref
possible .
void display() {
System.out.println("This is a method in a final class.");
}
}
class SubClass extends FinalClass {
// point 1:This will throw a compilation error because FinalClass is final
}
public class Main {
public static void main(String[] args) {
// Point 2: Creating an object of the final class and accessing its members
FinalClass obj = new FinalClass();
System.out.println("Number: " + obj.number); SSYSO mand
obj.display();
}
}
outside of the class also we can access directly with out any restriction.(for
instance by using objref.varname).
class Customer {
int cID;
String cName;
long cNum;
public Customer(int cID, String cName, long cNum) {
this.cID = cID;
this.cName = cName;
this.cNum = cNum;
}
}
public class Main{
public static void main(String[] args) {
Customer c = new Customer(1, "Rohit", 9915245L);
/*c.cID=2; //update fileds directly
c.cName="venkatesh";
c.cNum=1233444;*/
System.out.println(c.cID); //acessing details outside out side of class
System.out.println(c.cName); //no security
System.out.println(c.cNum); //here we are using var names outside of the
class
}
}
2.User defined Packages: The Packages which are defined by us for our
application requirements Also known as customized packages
Access Modifiers:
package package_1;
public class A {
private int a = 100;
Same package
Sub class
package package_1;
public class B extends A{
public static void main(String[] args) {
B obj = new B();
System.out.println("Same Package Sub Class : "+obj.a);
}
Same package
package package_1;
public class C {
public static void main(String[] args) {
A obj = new A();
System.out.println("Same Package non Sub Class : "+obj.a);
}
}
Different package
Sub class
package package_2;
import package_1.A;
Same package
package package_2;
import package_1.A;
public class E {
public static void main(String[] args) {
A obj = new A();
System.out.println("different Package Non Sub Class : "+obj.a);
}
}
Varargs
Varargs is nothing but variable length arguments
Varargs should be taken as formal parameter in method definition
Varargs can take 0 arguments N.no.of arguments
Varargs internally works a Single dimensional Array and It is dynamic
If required we can also pass an array as an argument to the varargs
parameter
With the help of varargs we can avoid defining methods overloading
whenever you want perform same operation for irrespective
no.of.argument of same type
Varargs can be also takes along with other type of parameter but in this
case varargs should be last argument.
Method overloading:
class FindSum{
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
class Main
{
public static void main(String[] args)
{
FindSum f=new FindSum();
int a=f.sum(10,20);
System.out.println("first overloaded method sum :"+a);
int b=f.sum(10,20,30);
System.out.println("second overloaded method sum :"+b);
}
}
EX:var args We can pass any no.of arguments(point we can pass array var too)
class FindSum{
int sum(int... x) {
int s = 0;
for (int i : x) {
s = s + i;
}
return s;
}
}
public class Main{
public static void main(String args[]) {
FindSum f = new FindSum();
int s = f.sum(10, 20);
System.out.println("Sum is : " + s);
s = f.sum(10, 20, 30);
System.out.println("Sum is : " + s);
int[] a = {10, 20, 30, 40};
s = f.sum(a);
System.out.println("Sum is : " + s);
}
}
EX:we can pass diff type of arguments in this case var args should be last(point)
class Student {
void findResult(String name, int... m) {
System.out.println("Name is : " + name);
System.out.println("Marks:");
int s = 0;
for (int i : m) {
System.out.println(i);
s = s + i;
}
System.out.println("------------------");
System.out.println("Total is : " + s);
System.out.println("======================");
}
}
public class Main{
public static void main(String args[]) {
Student s = new Student();
s.findResult("Manasa", 40, 50, 60);
s.findResult("Mamatha", 40, 50);
s.findResult("Cnu", 30);
s.findResult("Anu");
}
}
}
}
EX: 3- We can’t convert string type values to any primitive type using ordinary
typecasting approach but we can achieve by using parsing methods from Wrapper
classes
EX:
class Test {
void method1() {
System.out.println("Mtd-1 of Test");
}
void method2() {
System.out.println("Mtd-2 of Test");
}
}
public class Main {
public static void main(String args[]) {
Test t = new Test(); // Named Object
t.method1();
t.method2();
new Test().method1(); // Nameless object
new Test().method2();
}
}
Methods: java.util.StringTokenizer
import java.util.StringTokenizer;
class Main{
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer("welcome to java programming");
int nt = st.countTokens();
System.out.println("No.of.Tokens are : " + nt);
while (st.hasMoreTokens()) {
String token = st.nextToken();
System.out.println(token.toUpperCase() + " .... " + token.length());
}
}
}
Exception Handling:
EX:logical error
EX:Handling exception
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
try {
System.out.println("Enter the numerator");
int a = scan.nextInt();
System.out.println("Enter the denominator");
int b = scan.nextInt();
int c = a / b; // May throw ArithmeticException if b is 0
EX:
import java.util.Scanner;
class Main{
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 numbers ");
int x = s.nextInt();
int y = s.nextInt();
try {
int z = x / y;
System.out.println("Result is : " + z);
} catch (ArithmeticException a) {
System.out.println("Sorry V R N D By Zero ..");
System.out.println("Enter 2nd value ");
y = s.nextInt();
int z = x / y;
System.out.println("Result is : " + z);
}
}
}
3.“throw” : is keyword which can be used to raise the user defined exception.
import java.util.Scanner;
class Main{
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
4.throws:
5.finally
import java.util.Scanner;
try {
System.out.println("Enter the numerator");
int a = scan.nextInt();
System.out.println("Enter the denominator");
int b = scan.nextInt();
int c = a / b;
Multi-Threading:
1.java.lang.Thread©
2.By using java.lang.Runnable(i)
java.lang.Thread
predefined constant variable of Thread class
public final static int NORM_PRIORITY (5)
public final static int MIN_PRIORITY (1)
public final static int MAX_PRIORITY (10)
Thread(String):
Thread t=new Thread("Shashi");
It will create thread object with specified name Thread(Runnable)
Thread t=new Thread(st); > It is a copy constructor it will create thread
object by taking the properties of Runnable Interface Objec
Methods : java.lang.Thread
import java.lang.Thread;
class Main{
public static void main(String args[]) {
A a = new A();
B b = new B();
a.start();
b.start();
Note : we should not call "run()" of Thread class .By chance if we call "run()" of
Thread then execution will be sequence.
import java.lang.Thread;
java.lang.Thread
1.public String getName(); - It will return name of the Thread Object
2. public void setName(String): - Used to Set the name of an existed Thread
import java.lang.Thread;
class Child extends Thread {
@Override
public void run() {
System.out.println("Child-Thread ...");
}
}
class Main{
public static void main(String args[]) {
Child c = new Child(); // Child <-- Thread Object
String tname = c.getName();
System.out.println("Thread Name is : " + tname);
c.setName("Child");
tname = c.getName();
System.out.println("Thread Name is : " + tname);
}
}
import java.lang.Thread;
class Main{
public static void main(String args[]) {
A a = new A();
B b = new B();
Note: the Thread which is having MAX_PRIORITY will be executed First. The
Thread Which is having MIN_PRIORITY then that thread will be executed at last
and the Threads which are having same priorities will be execute simultaneously.
Note: Based on our application requirements we can also delay the execution of
thread based on the particular period of type. Then we have to use the following
overloaded methods
//java.lang.Thread
//public static void sleep(long ms) ----throws InterruptedException
//public static void sleep(long ms,int ns)
import java.lang.Thread;
Note: Based the application requirements we also delay the execution of the
thread till another thread execution process is “completed”. Using “join()”
import java.lang.Thread;
a.join(); // Main thread will wait for thread A to finish before continuing
for (int i = 10; i <= 15; i++) { // Main thread prints numbers 20 to 30 after
A finishes
System.out.println("Main Thread ... : " + i);
}
}
}
What is synchronization ?
It is the process of restrict more than one thread to perform the operations
on the same functionality simultaneously
We can achieve thread safety by using “synchronized” keyword
Advantages are avoiding data inconsistency
Disadvantages are delaying the execution of the program
import java.lang.Thread;
class ATM {
// Synchronized method to handle withdrawals
public synchronized void wd(String s) {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("WD by Mr|Mrs ... : " + s);
}
}
}
class Thread1 extends Thread {
ATM a;
Thread1(ATM a) {
this.a = a;
}
@Override
public void run() {
a.wd("Sai"); // Sai is withdrawing money
}
}
class Thread2 extends Thread {
ATM a;
Thread2(ATM a) {
this.a = a;
}
@Override
public void run() {
a.wd("Balu"); // Balu is withdrawing money
}
}
class Main{
public static void main(String args[]) {
ATM a = new ATM(); // Create ATM object
Thread1 t1 = new Thread1(a); // Create Thread1 (Sai)
Thread2 t2 = new Thread2(a); // Create Thread2 (Balu)
import java.lang.Runnable;
import java.lang.Thread;
class Main{
public static void main(String args[]) {
A a = new A(); // Create an instance of A (Runnable)
Thread t = new Thread(a); // Create a new Thread with A as the Runnable target
t.start(); // Start the A thread
for (int i =10; i <=15; i++) { // Main thread prints numbers from 20 to 30
System.out.println("Main-Thread ... " + i);
}
}
}