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

Java notes

The document provides an overview of various types of constructors in Java, including default, parameterized, copy, and private constructors, along with their syntax and examples. It also discusses inheritance concepts such as single, multilevel, multiple, hierarchical, and hybrid inheritance, along with the use of the 'super' and 'this' keywords. Additionally, it highlights the advantages and disadvantages of using these keywords in Java 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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java notes

The document provides an overview of various types of constructors in Java, including default, parameterized, copy, and private constructors, along with their syntax and examples. It also discusses inheritance concepts such as single, multilevel, multiple, hierarchical, and hybrid inheritance, along with the use of the 'super' and 'this' keywords. Additionally, it highlights the advantages and disadvantages of using these keywords in Java 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 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


Default Constructor:-
Constructor
A constructor which does not have any parameter is
//example of constructor called default constructor.
class A{
int a; String name;
Syntax:-
//constructor
A(){ Class A{
a=8;
name="shristi"; A(){ // no parameter
}
void show(){ //variable intitialization
System.out.println(a+" "+ name);
} }

}
}

public class ConstructorExample {


public static void main(String[] args){ Note:- if we do not add default constructor then
A ref=new A();
ref.show();
compiler by itself add default constructor.

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

public class B {

Shristi patel Page 2


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
}
void show(){
object with the help of reference variable.
System.out.println(x+" "+y);
}
}

public class ParameterizedConstructor { Example of Copy constructor:-

Shristi patel Page 3


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";
private members outside of class. System.out.println(" r1:- "+a+" "+b+" "+p+" "+q);
}
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;
System.out.println("r3:--"+a+" "+b);
} }
Ov(double y,String z){
} p=y;

Shristi patel Page 4


q=z; {
//System.out.println("r4:- "+p+" "+q);
} //------Code
}
}
public class ConstructorOverloading {
public static void main(String[] args) { }
Ov r1= new Ov();
Ov r2=new Ov(52); Example of instance block:-
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 {
name,it can be written inside a class only but not public static void main(String[] args) {
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


not method. Static Block

3 We write time consuming code inside a instance block Static block is such kind of block in java which
like-JDBC connectivity. gets executed at the time of loading the .class file
into JVM memory.

Syntax:-
Static block gets executed befor instance block.
Class class-name{
Syntax:-
Shristi patel Page 5
Class class-name{ 4 A sub class contains all the features of super class
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
features and properties of existing class is called Types Of Inheritance:-
inheritance.

1 Single Inheritance:-
1 The java extends keyword is used to perform
inheritance.
Super class
2 It provides code reusability.
3 We can’t access private members of the class through
inheritance.

Shristi patel Page 6

Sub class
//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:-");
marks= sc.nextInt();
Simple inheritance is nothing but which contains
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();
}
} }

Class subclass extends superclass


{
Shristi patel Page 7
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
}
{
class multi3 extends multi2{ //second sub class
//code 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();
void add() r.multiply();
{ r.division();

Shristi patel Page 8


} 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
through classes. //C is in confusion which method to take as both
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


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 instance


Example of hierarchical inheritance:- 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 class
System.out.println("enter your name:-");
}
,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) {
h3 r3= new h3();
h2 r2=new h2();

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");
}
}
// Subclass Student

Shristi patel Page 11


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");
}  Supports polymorphism: Because subclasses can
} override methods and access fields from their parent

Shristi patel Page 12


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) {
1. It helps to distinguish between instance variables This r= new This();
and local variables with the same name. System.out.println(r);
r.show();

Shristi patel Page 13


} 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()
} {
public static void main(String[] args) { this(10, 20);

Shristi patel Page 14


System.out.println( It is also known as static polymorphism. This
"Inside default constructor \n"); type of polymorphism is achieved by function
} overloading or operator overloading.
// Parameterized constructor
This(int a, int b) Note:- But java doesn’t support operator overloading
{
this.a = a;
this.b = b;
System.out.println( Method Overloading
"Inside parameterized constructor");
} When there are multiple functions with the same name
but different parameters then these functions are said
public static void main(String[] args) to be overloaded. Functions can be overloaded by
{ changes in the number of arguments or/and a change in
This object = new This(); the type of arguments.
}
}
Syntax:-
Polymorphism
Polymorphism is considered one of the important Return-value method-name(parameter1);
features of Object-Oriented Programming. Polymorphism Return-value method-name(parameter1,parameter2);
allows us to perform a single action in different
ways. In other words, polymorphism allows you to
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 Example of method overloading:-
2 Run time polymorphism class method
{
void add(){
Compile time polymorphism:- int a=52;
int b=96;
A polymorphism which gets executed at the time of int c=a+b;
compilation is called compile time or early binding or System.out.println(c);
static compilation. }

Shristi patel Page 15


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.
Whenever we are writing method in super and sub
classes in such a way that method name and parameter
must be same is called method overriding. Example of method overriding:-

Shristi patel Page 16


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
3. Supports dynamic binding, enabling the correct rules and ensure that its internal state remains
method to be called at runtime, based on the actual consistent.
class of the object. Encapsulation is a processs of wrapping code
and data together into a single unit.

Shristi patel Page 17


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

Shristi patel Page 18


Data abstraction is achieved by interfaces and Syntax:-
abstract classes.
Abstract class A
Data abstraction may also be defined as the
process of identifying only the required {
characteristics of an object ignoring the irrelevant //code
details.
}

Advantages of abstraction:-
Example of anbstract class:-
1 Helps to increase the security of an application or
program as only essential details are provided to the // Abstract class
user. abstract class Sunstar {
abstract void printInfo();
2 The enhancement will necome very easy because without }
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 String name = "avinash";
class and interfaces. int age = 21;
float salary = 222.2F;

System.out.println(name);
Abstract Class 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.
// Base class
2 an abstract class may or may not have all abstract class AbstractClasss {
methods.Some of them can be concrete method. public static void main(String args[])
{
3 Constructors are allowed. Sunstar s = new Employee();
s.printInfo();
4 There can be a final method in abstract class but any }
abstract method in class cn not be declared as final }
5 We can define static method in an abstract class.
Abstract Method

Shristi patel Page 19


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();

Interface

Shristi patel Page 20


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
Class Interface
}
In an interface, you must
In class, you can
initialize variables as they
Example of interface:- instantiate
are final but you can’t create

Shristi patel Page 21


Class Interface Points Abstract Class Interface

variables and an Methods are


create an object. object. abstract by
Can have both
default; Java
implemented and
8, can have
A class can contain abstract methods.
The interface cannot contain Implementation default and
concrete (with Method static methods.
concrete (without
implementation)
implementation) methods.
methods
A class can
class can inherit
implement
The access from only one
multiple
specifiers used abstract class.
In Interface only one specifier Inheritance interfaces.
with classes are
is used- Public.
private, protected,
and public. Methods and
properties can Methods and
have any access properties are
modifier (public, implicitly
Difference between abstract class and interface:-
Access protected, public.
Modifiers private).

Points Abstract Class Interface Variables are


Can have member
implicitly
variables (final,
Cannot be public, static,
Specifies a set non-final, static,
instantiated; and final
of methods a non-static).
contains both Variables (constants).
class must
abstract (without
implement;
implementation)
methods are
and concrete
abstract by
methods (with
default.
Definition implementation) Multiple Inheritance
We can achieve multiple inheritance through
intefaces beacause interface contains only abstract
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.io
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
sub-package of same type into a particular group. 4 naming conflicting
5 hiding

Note:- Package is nothing but folder in windows.


Types:- Disadavantage:- We cant’t pass parameter to package

 Predefined
o Java.lang
o Java.util

Shristi patel Page 25


Pre-defined package:-
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 application can be preserved.Java exception handling is
a mechanism to handle runtime error such as
Exception Handling and multithreading ClassNotFoundException, IOException, RemoteException.

Exception:- The object orientation mechanism has provided the


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

Major reasons why an exception Occurs


 Invalid user input Example of try and catch block:-
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors public class ExceptionHandling {
 Out of bound public static void main(String[] args) {
 Null reference System.out.println("main method started");
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

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


built in methods to print the exception:-
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
}
}

Shristi patel Page 30


Blocks and keywords used for exception Handling:- 4 Throws keryword
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. }
}

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:-
{
Throws keyword is used when we doesn’t want to try {
handle the exception and try to send the exception to fun();
}
the JVM . catch (IllegalAccessException e) {
Throws is a keyword in java that is used in the System.out.println("caught in main.");
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.

Shristi patel Page 33


Throw is followed by an Throws is followed by a User-defined exception handling
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
throw new ArithmeticException(); InvalidAgeException
} {
else { if(age<18)
int c=a/b; {
System.out.println(c); throw new InvalidAgeException("not eligible for
} voting");
} }
else
public static void main(String[] args) {
{ System.out.println("eligible for voting");
ThrowDemo d =new ThrowDemo(); }
try }
{
d.div(45,0); public static void main(String[] args) {
} try{
catch(Exception e) vote(12);
{ }
System.out.println("the value of b is 0"); catch(Exception e)
} {
} System.out.println(e);
} }
}
}

Shristi patel Page 34


Multithreading

Shristi patel Page 35

You might also like