0% found this document useful (0 votes)
3 views

Java Notes

The document provides an overview of various types of constructors in Java, including default, parameterized, copy, private, and static constructors, along with examples for each. It also discusses inheritance, including single, multilevel, multiple, hierarchical, and hybrid inheritance, and explains the use of the 'super' and 'this' keywords. Additionally, it covers constructor overloading and instance blocks, emphasizing the importance of these concepts in object-oriented programming.

Uploaded by

Shristi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Notes

The document provides an overview of various types of constructors in Java, including default, parameterized, copy, private, and static constructors, along with examples for each. It also discusses inheritance, including single, multilevel, multiple, hierarchical, and hybrid inheritance, and explains the use of the 'super' and 'this' keywords. Additionally, it covers constructor overloading and instance blocks, emphasizing the importance of these concepts in object-oriented programming.

Uploaded by

Shristi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Name –shristi patel

Rollno-22070166
Course –bsc cs hons
4th sem

Shristi patel Page 1


Constructor Default Constructor:-
//example of constructor A constructor which does not have any parameter is
called default constructor.
class A{
int a; String name;

//constructor Syntax:-
A(){
a=8; Class A{
name="shristi";
} A(){ // no parameter
void show(){
System.out.println(a+" "+ name); //variable intitialization
}
}
} }
public class ConstructorExample {
public static void main(String[] args){
A ref=new A(); Note:- if we do not add default constructor then
ref.show(); compiler by itself add default constructor.

}
}

Example of default constructor:-


Types of constructor:-
class C{
1 Private Constructor int a; String b; boolean c;
C(){
2 Default Constructor a=100;
b="ankit";
3 Parameterized Constructor c=true;
}
4 Copy Constructor void display(){
System.out.println(a+" "+b+" "+c);
}

Shristi patel Page 2


} }
}
public class B {
public class ParameterizedConstructor {
public static void main(String[] args){ public static void main(String[] args){
C ref=new C(); D ref= new D(100,200);
ref.display(); ref.show();
} }
} }

Note :- In parameterized constructor only primitive


data type can be passed as a parameter.
Parameterized Constructor:-
A constructor through which we can pass one or
more parameters is called parameterized constructor. Copy constructor:-
Whenever we pass object reference to the
constructor then it is called copy constructor.
Syntax-
Class A{
Syntax:-
A(int x,int y){
Class class-name{
//-----
Class-name(obj ref){
------
//------
}
-----
}
}
Example of parameterized contructor:-
}
class D{
int x; Note:- copy constructor copies the data of another
int y; constructor.
D(int a,int b){
x=a;y=b; It copies the entire data of one object to any other
}
object with the help of reference variable.
void show(){
System.out.println(x+" "+y);

Shristi patel Page 3


}
Example of Copy constructor:- }
class copy{
int a; String b;
copy(int x,String y){ Note:- private constructor can be used in the same
a=x; class in which the constructor exist.
b=y;
System.out.println(a+" "+b);
}
copy(copy ref){
a=ref.a;
b=ref.b;
System.out.println(a+" "+b); Constructor overloading
}
} Two or more constructor with same name but different
parameter is called constructor overloading.
public class CopyConstructor {

public static void main(String[] args){


copy r1=new copy(100,"shristi"); Example:-
copy r2=new copy(r1);
} class Ov{
} int a;
int b;
double p;
String q;
Ov(){
a=100;
Private Constructor:-
b=200;
In java ,it is possible too write a constructor as p=23.56;
a private but according to the rule we can’t access q="ankit";
System.out.println(" r1:- "+a+" "+b+" "+p+" "+q);
private members outside of class.
}
Syntaxx:- Ov(int x){
a=x;
Class class-name{ System.out.println("r2:-- "+a);
}
Private class-name(){ Ov(int x, int y){
a=x;
//------- b=y;

Shristi patel Page 4


System.out.println("r3:--"+a+" "+b); Syntax:-
}
Ov(double y,String z){ Class class-name{
p=y;
q=z; {
//System.out.println("r4:- "+p+" "+q);
} //------Code
}
}
public class ConstructorOverloading {
}
public static void main(String[] args) {
Ov r1= new Ov(); Example of instance block:-
Ov r2=new Ov(52);
Ov r3 =new Ov(56,78); class Ib {
Ov r4 = new Ov(56.2,"shubham"); int a, b;
System.out.println(r4.p+" "+r4.q);
Ib() {
a = 10;
} b = 20;
} System.out.println(a + " " + b);
}
{
a=30; b=40;
System.out.println(a+" "+b);

}
Instance Block

}
Instance block is similar to method which has no public class InstanceBlock {
public static void main(String[] args) {
name,it can be written inside a class only but not
Ib r= new Ib();
inside a method. }
}
1 It always gets executed before the constructor.
2 We can use variable only inside the instance block
Static Block
not method.
Static block is such kind of block in java which
3 We write time consuming code inside a instance block
gets executed at the time of loading the .class file
like-JDBC connectivity.
into JVM memory.

Shristi patel Page 5


Static block gets executed befor instance block. 3 We can’t access private members of the class through
inheritance.
Syntax:-
4 A sub class contains all the features of super class
Class class-name{ So we should create the object of sub class.
Static{
//----code 5 Method overriding is only possible through
} inheritance.

}
Syntax:-
Class class-name1 //Super class
{
//---code
}
class class-name2 extends class-name1 //sub class
{
//---code

Inheritance }

When we construct a new class from existing class


in such a way that the new class access all the Types Of Inheritance:-
features and properties of existing class is called
inheritance.
1 Single Inheritance:-
1 The java extends keyword is used to perform
inheritance.
Super class
2 It provides code reusability.

Shristi patel Page 6


Class subclass extends superclass
{
//code
//code
}

2 Multilevel Inheritance:- Example of Simple inheritance:-


3 Multiple Inheritance:- import java.util.*;
class student
4 Hierarchial Inheritance:- {
int roll,marks;
5 Hybrid Inheritance:- String name;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter roll number");
roll = sc.nextInt();
Simple Inheritance:-
System.out.println("enter marks:-");
Simple inheritance is nothing but which contains marks= sc.nextInt();
System.out.println("enter name:-");
only one super class and only one sub class is called name=sc.next();
Simple inheritance.
}
}
class ankit extends student{
void display()
{

Syntax:- System.out.println(roll+" "+name+" "+"marks");


}
Class superclass public static void main(String[] args) {

{ ankit r= new ankit();


r.input();
//code r.display();
}
} }
Shristi patel Page 7
void add()
{
Multilevel Inheritance a=10;b=20;
c=a+b;
In Mulyilevel inheritance we have ony one super System.out.println("sum of numbers:- "+c);
class and multiple sub classes called multilevel }
inheritance . void sub(){
a=100;b=500;
In this the derived class inherits the property of c=b-a;
base class and also the derived class is also the base System.out.println("differncee of two number
is:-"+c);
class for any other classes.
}

}
Syntax:- class multi2 extends multi // first sub class
{
Class super void multiply()
{
{ a=56;
b=86;
//code c=a*b;
System.out.println("multiplication of a and b
} is :-"+c);
}
Class sub1 extends super
}
{
//code class multi3 extends multi2{ //second sub class
void division()
} {
a=200;
Class sub2 extends sub1 b=86;
c=a/b;
{ System.out.println("division of two number:-"+c);
}
//code }

}
public class MultilevelInheritance {
Example of multilevel inheritance:- public static void main(String[] args) {
multi3 r= new multi3();
class multi{ //Super class
r.add();
int a,b,c;
r.sub();

Shristi patel Page 8


r.multiply();
r.division();
} Class B
}
{
Void m1()

Multiple Inheritance {
//code

Why java doesn’t support multiple inheritance??? }

Whenever a sub class wants to inherit the property }


of two or more super classes that have same
method ,java compiler can’t decide which class method
it should inherit. Class C extends A,B

Then their might be a chance of memory duplication {


i.e. a reason java doesn’t support multiple inheritance
//C is in confusion which method to take as both
through classes.
super class contain same method.
}
Syntax:-
Class A
{
Hierarchical Inhertance
Void m1()
A inheritance which contain only one super class
{ and multiple sub class and all ssub class directky
extends super clas called hierarchical inheritance.
//code
Syntax:-
}
Class A
}
{
//code

Shristi patel Page 9


} h3 r3= new h3();
h2 r2=new h2();
Class B extends A r3.input();
r2.show();
{ r3.display();
//code }
}
}
Class C extends A
{ Super Keyword
//code
The super keyword in Java is a reference variable
} which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an


Example of hierarchical inheritance:- instance of parent class is created implicitly which is
referred by super reference variable.
class H
{
void input()
{
Super keyword refers to the object of super
System.out.println("enter your name:-");
}
class ,it is used when we want to call the super class
} variable, method and constructor through sub class
class h2 extends H{ object.
void show()
{
Whenever the super class and sub class variable
System.out.println("my name is ankit"); and method name both are same then it cannot be used
} only.
}
class h3 extends H To avoid the confusion between super class and
{ sub classes variables and methods that have same name
void display() we should use super keyword.
{
System.out.println("My name si Ankush");
}
} We can call variables , method and constructor using
public class HierarchicalInheritance { super keyword.
public static void main(String[] args) {

Shristi patel Page 10


Use of super with variables:-
// super keyword in java example

// Base class vehicle


class Vehicle1 {
int maxSpeed = 120;
}

// sub class Car extending vehicle


class Car1 extends Vehicle1 {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}
}

// Driver Program
class SuperVariable {
public static void main(String[] args)
{
Car1 small = new Car1();
small.display();
}
}

Use of super with method:-


// super keyword in java example

// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}

Shristi patel Page 11


} }
// Subclass Student }
class Student extends Person { // Subclass Student
void message() class Student1 extends Person1 {
{ void message()
System.out.println("This is student class"); {
} System.out.println("This is student class");
// Note that display() is }
// only in Student class // Note that display() is
void display() // only in Student class
{ void display()
// will invoke or call current {
// class message() method // will invoke or call current
message(); // class message() method
message();
// will invoke or call parent
// class message() method // will invoke or call parent
super.message(); // class message() method
} super.message();
} }
// Driver Program }
class SuperMethod { // Driver Program
public static void main(String args[]) class SuperMethod {
{ public static void main(String args[])
Student s = new Student(); {
Student1 s = new Student1();
// calling display() of Student
s.display(); // calling display() of Student
} s.display();
} }
}

Advantages of Using Java Super Keyword


Use of super with constructor:- The super keyword in Java provides many advantages in
object-oriented programming are as follows:
// super keyword in java example

// superclass Person  Enables reuse of code: Using the super keyword


class Person1 { allows subclasses to inherit functionality from
void message() their parent classes, which promotes the reuse of
{ code and reduces duplication.
System.out.println("This is person class\n");

Shristi patel Page 12


 Supports polymorphism: Because subclasses can 1. It helps to distinguish between instance variables
override methods and access fields from their parent and local variables with the same name.
classes using super, polymorphism is possible. This
allows for more flexible and extensible code. 2. It can be used to pass the current object as an
argument to another method.
 Provides access to parent class behaviour: 3. It can be used to return the current object from a
Subclasses can access and use methods and fields method.
defined in their parent classes through the super
keyword, which allows them to take advantage of 4. It can be used to invoke a constructor from another
existing behaviour without having to reimplement it. overloaded constructor in the same class.

 Allows for customization of behaviour: By overriding


methods and using super to call the parent Disadvantages of using ‘this’ reference
implementation, subclasses can customize and extend
the behaviour of their parent classes.
Although ‘this’ reference comes with many advantages
 Facilitates abstraction and encapsulation: The use there are certain disadvantages of also:
of super promotes encapsulation and abstraction by
allowing subclasses to focus on their behaviour 1. Overuse of this can make the code harder to read and
while relying on the parent class to handle lower- understand.
level details.
Note:- Super() is a Java keyword used to call a 2. Using this unnecessarily can add unnecessary
superclass constructor. Super keyword accesses overhead to the program.
superclass members and maintains inheritance
hierarchies. 3. Using this in a static context results in a compile-
time error.

4. Overall, this keyword is a useful tool for working


with objects in Java, but it should be used
This Keyword
judiciously and only when necessary.
This keyword is a reference variable that refers
to the current object. Example of this keyword:-
public class This {
void show()
Advantages of using ‘this’ reference {
There are certain advantages of using ‘this’ reference System.out.println(this);
in Java as mentioned below: }
public static void main(String[] args) {
This r= new This();
Shristi patel Page 13
System.out.println(r); }
r.show(); public static void main(String[] args) {
} This r= new This(45,85);
} r.show();
}
}

2.this can be used to invoke current class method


(implicity)
class This {
void display()
{
// calling function show()
this.show();

System.out.println("Inside display function");


}

void show()
{
System.out.println("Inside show function");
}

public static void main(String args[])


{
This t1 = new This();
Usage of java this keyword:- t1.display();
}
1 this can be used to refer current class instance }
variable.
public class This {
3 this can be used to invoke current class constructor.
int a,b;
This(int a,int b){
this.a=a; class This {
this.b=b; int a;
} int b;
void show()
{ // Default constructor
System.out.println(a+" "+b); This()

Shristi patel Page 14


{ A polymorphism which gets executed at the time of
this(10, 20); compilation is called compile time or early binding or
System.out.println( static compilation.
"Inside default constructor \n");
} It is also known as static polymorphism. This
type of polymorphism is achieved by function
// Parameterized constructor overloading or operator overloading.
This(int a, int b)
{
this.a = a; Note:- But java doesn’t support operator overloading
this.b = b;
System.out.println(
"Inside parameterized constructor");
} Method Overloading

public static void main(String[] args) When there are multiple functions with the same name
{ but different parameters then these functions are said
This object = new This(); to be overloaded. Functions can be overloaded by
} changes in the number of arguments or/and a change in
} the type of arguments.

Polymorphism Syntax:-

Polymorphism is considered one of the important


features of Object-Oriented Programming. Polymorphism
Return-value method-name(parameter1);
allows us to perform a single action in different
ways. In other words, polymorphism allows you to Return-value method-name(parameter1,parameter2);
define one interface and have multiple
implementations. The word “poly” means many and
“morphs” means forms, So it means many forms.
There are two types of polymorphism in java:-
1 Compile time polymorphism
2 Run time polymorphism
Example of method overloading:-
class method
Compile time polymorphism:- {
void add(){
int a=52;

Shristi patel Page 15


int b=96; Whenever we are writing method in super and sub
int c=a+b; classes in such a way that method name and parameter
System.out.println(c); must be same is called method overriding.
}
void add(int x,int y)
{
int c=x+y; Syntax:-
System.out.println(c);
Class A
}
{
void add(int x,double y){
double c=x+y; Void show()
System.out.println(c);
} {
public static void main(String[] args) { //code
method r=new method();
r.add(); }
r.add(42,85);
}
r.add(45,85.20);
Class B extends A
}
} {
Void show()
Run Time polymorphism
{
A polymorphism wwhich exists at the time of
execution of program is called runtime polymorphism. //code
}

It is also known as Dynamic Method Dispatch. It }


is a process in which a function call to the Overriding rules:-
overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. Method 1 if the method is not present in the super class then
overriding, on the other hand, occurs when a derived it wwill give compilation error.
class has a definition for one of the member functions
of the base class. That base function is said to 2 If it is there in super class then it will check
be overridden. whether the method is overridden or not .if it not
overridden then it will call super class method and if
Method overriding it is overridden then it will call sub class method.

Shristi patel Page 16


3. Supports dynamic binding, enabling the correct
method to be called at runtime, based on the actual
Example of method overriding:- class of the object.
class shape 4. Enables objects to be treated as a single type,
{ making it easier to write generic code that can
void draw() handle objects of different types.
{ Disadvantages of Polymorphism in Java
System.out.println("can't say shape type"); 1. Can make it more difficult to understand the
} behavior of an object, especially if the code is
complex.
} 2. This may lead to performance issues, as polymorphic
class square extends shape behavior may require additional computations at
{ runtime.
@Override
void draw()
{
super.draw(); Encapsulation
System.out.println("square shape");
} Encapsulation in Java is a fundamental concept in
} object-oriented programming (OOP) that refers to the
bundling of data and methods that operate on that data
class MethodOverriding within a single unit, which is called a class in Java.
{
public static void main(String[] args) { Java Encapsulation is a way of hiding the
square r= new square(); implementation details of a class from outside access
r.draw(); and only exposing a public interface that can be used
} to interact with the class.
}
In Java, encapsulation is achieved by declaring
Advantages of Polymorphism in Java the instance variables of a class as private, which
1. Increases code reusability by allowing objects of means they can only be accessed within the class. To
different classes to be treated as objects of a allow outside access to the instance variables, public
common class. methods called getters and setters are defined, which
2. Improves readability and maintainability of code by are used to retrieve and modify the values of the
reducing the amount of code that needs to be written instance variables, respectively. By using getters and
and maintained. setters, the class can enforce its own data validation
rules and ensure that its internal state remains
consistent.

Shristi patel Page 17


Encapsulation is a processs of wrapping code
and data together into a single unit.
Disadvantages of Encapsulation in Java
 Can lead to increased complexity, especially if not
Advantages of encapsulation:- used properly.
 Can make it more difficult to understand how the
 Data Hiding: it is a way of restricting the access system works.
of our data members by hiding the implementation  May limit the flexibility of the implementation.
details. Encapsulation also provides a way for data
hiding. The user will have no idea about the inner
implementation of the class. It will not be visible
to the user how the class is storing values in the Example of encapsulation:-
variables. The user will only know that we are
passing the values to a setter method and variables class capsule
are getting initialized with that value. {
private int value; //data hiding
 Increased Flexibility: We can make the variables of
public void setvalue(int x)
the class read-only or write-only depending on our
{
requirements. If we wish to make the variables read- value=x;
only then we have to omit the setter methods like }
setName(), setAge(), etc. from the above program or public int getvalue()
if we wish to make the variables write-only then we {
have to omit the get methods like getName(), return ++value;
getAge(), etc. from the above program }
}
 Reusability: Encapsulation also improves the re-
usability and is easy to change with new public class Encapsulation {
requirements. public static void main(String[] args) {
capsule r= new capsule();
r.setvalue(100);
 Testing code is easy: Encapsulated code is easy to System.out.println(r.getvalue());
test for unit testing.
}
 Freedom to programmer in implementing the details of }
the system: This is one of the major advantage of
encapsulation that it gives the programmer freedom
in implementing the details of a system. The only Abstraction
constraint on the programmer is to maintain the Abstraction is th process in which we only show
abstract interface that outsiders see. essential details/functionality to the user. The non-

Shristi patel Page 18


essential implementation details are not displayed to 5 We can define static method in an abstract class.
the user.
Data abstraction is achieved by interfaces and
abstract classes. Syntax:-

Data abstraction may also be defined as the Abstract class A


process of identifying only the required {
characteristics of an object ignoring the irrelevant
details. //code
}
Advantages of abstraction:-
1 Helps to increase the security of an application or Example of anbstract class:-
program as only essential details are provided to the
// Abstract class
user. abstract class Sunstar {
2 The enhancement will necome very easy because without abstract void printInfo();
}
affecting end users we can able to perform any type of
changes in out internal system. // Abstraction performed using extends
class Employee extends Sunstar {
void printInfo()
Abstraction can be implemented through abstract {
class and interfaces. String name = "avinash";
int age = 21;
float salary = 222.2F;

Abstract Class System.out.println(name);


System.out.println(age);
A class which contains the abstract keyword I System.out.println(salary);
its declaration is called abstract class. }
}
1 We can’t create object for abstract class.
2 an abstract class may or may not have all abstract // Base class
class AbstractClasss {
methods.Some of them can be concrete method. public static void main(String args[])
3 Constructors are allowed. {
Sunstar s = new Employee();
4 There can be a final method in abstract class but any s.printInfo();
abstract method in class cn not be declared as final }
}
Shristi patel Page 19
Abstract Method
A method which contain abstract modifier at the Example:-
time of declaration is called abstract method.
abstract class programming
The abstract method is used for creating {
blueprints for classes or interfaces. Here methods are public abstract void Developer();
defined but these methods don’t provide the }
class HTML extends programming{
implementation. Abstract Methods can be implemented
public void Developer()
using subclasses or classes that implement the {
interfaces. System.out.println("Tim Berners Lee is the developer
of HTML");

1 It can only be used in abstract classes. }

2 Anys class that contsin one or more abstract method }


must also be declared abstract.
class Java extends programming
3 Abstract method does not conatin any body and ends {
with semicolon public void Developer()
{
4 If a non-subclass extends an abstract class ,then System.out.println("James Gosling is the developer of
the class must implement all the abstract methods of java");
the abstract class else the concrete class has to be
declared as abstract as well.
}
5 Whenever the action is common but implementation are }
different then we should use abstract method.
class AbstractMethod
6 Illegal combination of abstract methods with:-- {
public static void main(String[] args) {
Final,static ,private abstract native,abstract programming p= new HTML();
synchronized,abstract strictfp. programming p1=new Java();
p.Developer();
p1.Developer();
Syntax:- }
}
Abstract return –type class-name();

Shristi patel Page 20


Interface Example of interface:-
Interface is just like a class which contains ony import java.util.Scanner;
abstract method. interface client
{
To achieve interface java provides a keyword called abstract void input();
implements. abstract void output();
}
An interface is the blueprint of a behaviour. class Raju implements client{
String name;
A java interface contains static constants and abstract double sal;
methods. public void input()
{
The interface in java is a mechanism to achieve Scanner sc =new Scanner(System.in);
abstraction and multiple inheritance and loose System.out.println("enter username:-");
coupling. name =sc.next();

System.out.println("Enter salary:-");
1 Interface methods are by default public and abstract. sal=sc.nextDouble();
}
2 Interface variables are by default public ,static and public void output()
final {
System.out.println(name+ " "+sal);
3 Interface method must be overridden inside the }
implementing classes.
public static void main(String[] args) {
4 Interface is nothing but deals between client and client c=new Raju();
developer. c.input();
c.output();

}
Syntax:- }
Interface interface-name
{ public class Interface {
}
//declare constants fields
//Abstract methods
}

Shristi patel Page 21


Class Interface Points Abstract Class Interface

In an interface, you must Methods are


In class, you can
initialize variables as they abstract by
instantiate Can have both
are final but you can’t create default; Java
variables and implemented and
an object. 8, can have
create an object. abstract methods.
Implementation default and
Method static methods.
A class can contain
The interface cannot contain
concrete (with A class can
concrete (without class can inherit
implementation) implement
implementation) methods. from only one
methods multiple
abstract class.
Inheritance interfaces.
The access
specifiers used Methods and
In Interface only one specifier
with classes are properties can Methods and
is used- Public.
private, protected, have any access properties are
and public. modifier (public, implicitly
Access protected, public.
Modifiers private).
Difference between abstract class and interface:-
Variables are
Can have member
implicitly
variables (final,
public, static,
Points Abstract Class Interface non-final, static,
and final
non-static).
Variables (constants).
Cannot be
Specifies a set
instantiated;
of methods a
contains both
class must
abstract (without
implement;
implementation) Multiple Inheritance
methods are
and concrete
abstract by We can achieve multiple inheritance through
methods (with
default. intefaces beacause interface contains only abstract
Definition implementation)
method,which implementation is provided by the sub
classes.

Shristi patel Page 22


class MultipleInheritance implements A1,B1
{
public void show()
Syntax of achieve multiple inheritance thorugh class {
and interface :- System.out.println("interface A1 and B1");
}
public void disp()
Interface Interface1 {
System.out.println("multiple inheritaance");
{ }

//code public static void main(String[] args) {


MultipleInheritance m= new MultipleInheritance();
} m.show();
m.disp();
Interface Interface2 }
{ }

//code
Syntax to achieve multiple through only interfaces:-
}
Class class-name implements Interface1,Interface2
Interface Interface-name
{
{
//code
//code
}
}
Interface interface-name2 extends interface-name
Example of multiple inheritance:-
{
interface A1
{ //code
void show();
} }
interface B1
{
void show(); Example :-
void disp();
}

Shristi patel Page 23


interface Gill
{
void add(); Final variable:-
}
interface Raj extends Gill Once we declare a variable as a final we can’t
{ perform re-assignment.
void sub();
}
class ankit1 implements Raj { Syntax:- final int A=10;
@Override
public void add()
{ Final method:-
int a=10; int b=20;int c;
c=a+b; Whenever we declare a method as a final it can’t
System.out.println("addition:-"+c); be overridden to our extended class.

} Final methods are used to prevent method


@Override overriding.
public void sub()
{ Syntax:-
int a=10; int b=20;int c; Final void method-name()
c=a-b;
System.out.println("substraction:-"+c); {
}
} //code

class MITI }
{
public static void main(String[] args) {
Raj r=new ankit1(); Final class:-
r.add();
r.sub(); Whenever we declare a class as a final it can’t be
} extended or inherited to sub class. Used to prevent
} Inheritance.

Final keyword
Syntax:-
Final is a non access modifier which provides
restriction. In java we can use final in three ways:- Final class A
1 variable 2 method 3 class {

Shristi patel Page 24


//code o Java.applet
o Java.awt
} o Java.net
o Java.sql
 User-defined

New Keyword:-
New keyword created new objects and it is used to
allocate dynamic memory at run time.
 It is used to create the object.
 It allocates the memory atr un time
 All objects occupy memory in the heap area.
 It invokes object constructor
 It requires a single ,postfix argument to call the
constructor.
Syntax:-
Class-name reference-variable= new class-name();

Advantages of packages:-
1 Reusability
2 Security
Packages:- 3 Fast searching
A package arrange number of classes interfaces and 4 naming conflicting
sub-package of same type into a particular group.
5 hiding

Note:- Package is nothing but folder in windows.


Disadavantage:- We cant’t pass parameter to package
Types:-
 Predefined
o Java.lang
o Java.util
o Java.io Pre-defined package:-

Shristi patel Page 25


The package which are already created by java 4 java.applet:-
developer are called pre-defined package.
This package mainly use to develop GUI related
application.
Applet programs are web related program created at
server but executed at client machine.
Ex- applet
1 java.lang:-
It is the default package also known as heart of
the java because without using this package we can’t 5 java.awt:-
write even a single program and we need not to import
this package. AWt stands for abstract indow tool kit.

Ex- System,Object,String,Integer etc


It is aslo used to develop GUI application . the only
difference between applet and awt program is , awt
2 java.util:- programs are stand alone program and it contain main()
unlike applet.
This package is used to implement data structure of
java. Ex- Frame, Button ,textFeild etc.
It contain utility classes also known as collection
framework.
Java.net:-
URL,inetaddress,ULConnection and so on
Ex-Linkedlist,Stack,vector,hashset, Treeset etc.

7 java.SQL:- Conncetion ,statement ,resultset etc


3 java.io:-
IO stands for input/output this package is very useful
to perform input/output operations on file. 8 javax.swing:- Jframe Jbutton ,JtextField etc.

Ex-File, Filewriter,Filereader etc. User-defined package:-

Shristi patel Page 26


The package which are created by java programmer or
user for their own use are called user-defined
package.

Syntax- package package_name;

Shristi patel Page 27


Unit-3 a mechanism to handle runtime error such as
ClassNotFoundException, IOException, RemoteException.
Exception Handling and multithreading

The object orientation mechanism has provided the


Exception:- following techniques to work with exception:-
An exception is unexpected/unwanted/abnormal 1 try
situation that occurred at runtime is called exception.
2 catch
When an exception occurs within a method, it
creates an object. This object is called the exception 3 throw
object. It contains information about the exception,
such as the name and description of the exception and 4 throws
the state of the program when the exception occurred. 5 finally

Major reasons why an exception Occurs Example of try and catch block:-
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
public class ExceptionHandling {
 Code errors public static void main(String[] args) {
 Out of bound System.out.println("main method started");
 Null reference int a=10,b=0,c;
 Type mismatch try{
 Opening an unavailable file c=a/b;
 Database errors System.out.println(c);
 Arithmetic errors }
catch(Exception e)
{
System.out.println("Cant divide number by 0");
}
Exception Handling:- System.out.println("main method ended");
}
In exception handling ,we should have an alternate
source through which we can handle the exception. }
Exception Handling is one of the effective means to
handle runtime error so that the regular flow of the Exception hierarchy
application can be preserved.Java exception handling is

Shristi patel Page 28


Throwable class is the super class or root class

of java exception hierarchy which contains two sub


classes that is-
1 exception
2 Error

Built in Exception:-
Built in Exceptions are the exceptions that are
available in java librarires .These exceptions are
suitable to explain certain error situations.
They are:-

 Checked Exceptions:-
Checked excpetions are called compile-time
exceptions beacause these exceptions are
Types of exception:- checked at compile –time by the compiler.
 Unchecked Exceptions:-
The unchecked exceptions are just opposite
to the checked exceptions. The compiler
will not check these exceptions at compile
time. In simple words, if a program throws
an unchecked exception, and even if we
didn’t handle or declare it ,the program
would not give a compilation error.

Shristi patel Page 29


User defined Exceptions:- 1 printStackTrace()
Sometimes ,the built in exceptions inn java are 2 toString()
not able to describe a certain situation. In such cases
users can also create exceptions , which are called 3 getMessage()
User defined exceptions.

//Program to print the exception information using


The advantages of Exception Handling in Java are as printstackTrace() method.
follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error- class NPE{
Handling Code public static void main(String[] args) {
3. Propagation of Errors String str=null;
try
4. Meaningful Error Reporting
{
5. Identifying Error Types System.out.println(str.toUpperCase());
}
catch(NullPointerException n)
{
Example of Null pointer exception:- n.printStackTrace();

class NPE{ }
public static void main(String[] args) { }
String str=null;
try
{ Output:-
System.out.println(str.toUpperCase());
} java.lang.NullPointerException: Cannot invoke
catch(NullPointerException n) "String.toUpperCase()" because "str" is null
{
System.out.println("NUll can't be casted"); at NPE.main(NullPointerException.java:6)

}
Process finished with exit code 0
}
}

Blocks and keywords used for exception Handling:-


built in methods to print the exception:-

Shristi patel Page 30


1 try block The throws keyword is used for exception handling
without try and catch block. It specifies the
The try block contains a set of statements where exceptions that a method can throw to the caller and
an exception occur. does not handle itself.
Syntax:-
Try 5 finally
{ It is executed after the catch block. We use it to
//statement that might cause exception put some common code(to be executed irrespective of
whether an exception has occurred or not) when there
} are multiple catch blocks.

2 catch block Try ,catch,finally block execution example:-


The catch block is used to handle the uncertain class Handling
condition of a try block. A try block is always {
followed by a catch block,which handles the exception public static void main(String[] args) {
that occurs in the associated try block.
try
{
System.out.println("learn coding");
Syntax:- int a=20,b=0,c;
c=a/b;
Catch System.out.println(c);
System.out.println("like share");
{
}
//statement that handle an exception catch(ArithmeticException a)
{
} System.out.println("number cannot be divides by
0");
}
finally{
3 throw keyword System.out.println("subscribe");
}
Throw keyword is used to transfer control from the
System.out.println("main method ended");
try block to the catch block. }
}

4 Throws keryword

Shristi patel Page 31


Throw Keyword:-
Errors Exceptions
Throw keyword is used to throw the user defined or
We can recover from Customized exception object to the JVM explicitly for
exceptions by either that purpose we use throw keyword.
Recovering from Error is
using try-catch block or
not possible. Throw keyword in java is used to explicitly throw
throwing exceptions back
to the caller. an exception from a method or any block of code.
We can throw any checked and unchecked exception.
Exceptions include both Throw keyword is mainly used to throw custom
All errors in java are
checked as well as exceptions.
unchecked type.
unchecked type.

Errors are mostly caused Syntax:-


Program itself is
by the environment in
responsible for causing Throw new exception_name(“statement to be printed
which program is
exceptions. exception”);
running.

Unchecked exceptions Example-


Errors can occur at occur at runtime whereas
compile time. checked exceptions occur Throw new ArthmeticException(“/by zero”);
at compile time

Program:-
They are defined in
They are defined in
java.lang.Exception // Java program that demonstrates the use of throw
java.lang.Error package. class ThrowDemo {
package
static void fun()
{
Examples : Checked try {
Exceptions : throw new NullPointerException("demo");
Examples : }
SQLException, IOException
java.lang.StackOverflowE catch (NullPointerException e) {
Unchecked Exceptions :
rror, System.out.println("Caught inside fun().");
ArrayIndexOutOfBoundExcep
java.lang.OutOfMemoryErr throw e; // rethrowing the exception
tion, }
or
NullPointerException, }
ArithmeticException.

Shristi patel Page 32


public static void main(String args[]) Syntax-
{
try { Type method_name(parameters) throws exception_list
fun();
}
catch (NullPointerException e) {
Program:-
System.out.println("Caught in main.");
} // Java program to demonstrate working of throws
} class ThrowsExecp {
}
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}

public static void main(String args[])


Throws keyword:- {
try {
Throws keyword is used when we doesn’t want to
fun();
handle the exception and try to send the exception to }
the JVM . catch (IllegalAccessException e) {
System.out.println("caught in main.");
Throws is a keyword in java that is used in the
}
signature of a method to indicate that this method }
might throw one of the listed type exceptions .The }
caller to these methods has to handle the exception
using a try catch block.
Throw Vs throws
 Throws keyword is only required for checked
exceptions and usage of the throws keyword for Throw Throws
unchecked exceptions is meaningless.
 Throws keyword is required oly to convince the Throw keyword is used to Throws keyword is used to
compiler and usage of the throws keyword doesn’t throw an exception object declare an exception as
not prevent abnormal termination of the program. explicitly. well as by pass the
 With the help of throws keyword ,we can provide caller.
information to the caller of the method about the Throw keyword is always Throws kwyword always used
exception. present inside method body with method signature.
We can throw only onne We can handle multiple
exception at a time exception using throws
keyword.
Throw is followed by an Throws is followed by a
Shristi patel Page 33
instance class
class InvalidAgeException extends Exception
{
Program:- InvalidAgeException(String msg)
{
System.out.println(msg);
}
class ThrowDemo }
{
void div(int a,int b) throws ArithmeticException public class UserDefinedException {
{
if(b==0) public static void vote(int age) throws
{ InvalidAgeException
throw new ArithmeticException(); {
} if(age<18)
else { {
int c=a/b; throw new InvalidAgeException("not eligible for
System.out.println(c); voting");
} }
} else
{
public static void main(String[] args) System.out.println("eligible for voting");
{ }
ThrowDemo d =new ThrowDemo(); }
try
{ public static void main(String[] args) {
d.div(45,0); try{
} vote(12);
catch(Exception e) }
{ catch(Exception e)
System.out.println("the value of b is 0"); {
} System.out.println(e);
} }
} }
}

Multithreading
User-defined exception handling

Shristi patel Page 34


Shristi patel Page 35

You might also like