0% found this document useful (0 votes)
14 views49 pages

Stack vs Heap Memory Differences

The document outlines the differences between stack and heap memory areas, emphasizing that stack is used for method execution and local variables, while heap is for object creation. It also covers constructors, methods, and various types of inheritance in Java, including their characteristics and behaviors. Additionally, it discusses object initialization, typecasting, and the Object class methods such as toString(), hashCode(), and equals().

Uploaded by

Tulsi gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views49 pages

Stack vs Heap Memory Differences

The document outlines the differences between stack and heap memory areas, emphasizing that stack is used for method execution and local variables, while heap is for object creation. It also covers constructors, methods, and various types of inheritance in Java, including their characteristics and behaviors. Additionally, it discusses object initialization, typecasting, and the Object class methods such as toString(), hashCode(), and equals().

Uploaded by

Tulsi gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd

differences between stack area and heap area

stack area vs heap area

i) main method() get excuted in stack area while object gets created in
heap area.

ii) a local variable and object referneces will be available in stack area
but all the non static members are loaded inside the object in heap
area.

iii) stack area members provides faster excution while heap area
members provides slower excution then stack area members.

iv) stack area is fixed in size so " StackOverflowError" occurs in stack


areas but heap area can grow its size and so "OutOfMemoryError"
occurs in heap area.

*********************************************************

four every inportant points:

1. All the static members are loaded at one place inside class static area
so a static method can access any other static member directly.

2. all the non static members are loaded at one place inside object so a
non -static method can access ant other non-static member directly.

3. all the static members details are shared with object so a non-static
member can access any static members directly.

4. the detail of a non-static member is not shared with static members


so a static method can not directly call a non-static members. A static
method can call any non-static member only by using object
references .

intialization of Object:
[Link] value to the non-static variables of
a class is called initalization of object.
[Link] can be initalized in three ways :
[Link] using object refernces
2. by using non-static method
[Link] using constructor
1. by using object refernces: the details of the
object get stored on object refernces so object
referneces can be used initalize the object.
Ex: employes e = new employes();
[Link]="mohan";
[Link]=101;
2. by using non-static method:when an object is
created then all the non-static members are
loaded inside the object . a non-static method
can be used to initalize the object as below.
************************************************
I assignment of non-static method
design setVlaue() and getDetails() for
i)school ii)
weapon
iii)rectangle and circle (getDetails() ,
setValue() , getArea(), getPermiter())
II assigment of constructor
design setVlaue() and getDetails() for
i)school ii)
weapon
iii)rectangle and circle (getDetails() ,
setValue() , getArea(), getPermiter())
quesiv) design a program to have object
counter.
iv) design overloaded constructor for
i) browser ii) student iii)fruit.
ques v) apply the constructor chaining previous
program.
************************************************
This keywoard
1. This is a keywoard which is used to refer the
non-static member of same class.
2. this keywoard holds the references of curent
object enter the excution.
================================================
Constructor:
1. A Constructor is a special members of class
which is used to load and initalize the non-
static members of a class.
EX:
public class A{
A(){// constructor body
}
public void eat(){}// method call()
public void speed(){} // method call()
public static void main(String[] args){
A a = new A(); //A() is a constructor call()
[Link](); //body of method;
[Link]();//body of method;
}
}
================================================
differences between method() and constructor():
1. A method can have any name but the name of
constructor must be same as the class name.
2. A method must have the return statment but a
constructor will not have return statement.
3. A method can be static , abstract, final , or
synchorniszed but this keywoards anre not
allowed for constructor so a constructor will
never be static, abstract, final , or
synchorniszed.
4. A method is excuted by methoda call but a
constructor is excuted when object of the class
is created.
================================================
Types of Constructor:
1. Default Constructor=
2. user-Defined constructor:
1. no-argument constructor
2. parameterised constructor
================================================
1. Default constructor:
i. a constructor which is added by complier at
the time of compliation in .dot class file is
called default constructor.
ii. a default constructor is added only if there
is no user define constructor is designed by
programer in .dot java [Link] there will be any
user defined constructor then default
constructor will not be added by complier.
Use of Default Constructor:
1. default constructor help in object creation
even user have not designed constructor inside
the program.
================================================
types of user-defined constructor.
1. no-argument constructor:
i. if a user defined constructor does not take
any agrument then it is called no-argument
constructor.
2. parameterised constructor :
i). if a constructor takes different agruments
at its parameter then it is called parameterised
constructor.
ii). a parameterised constructor is used to
initalise the details of object and the time of
object creation.
================================================
constructor overloading:is a mechanism to have
multiple constructors inside a class with the
same name but the different agruments.
Different ways to achieve constructor
overloading.
by changing the number of arguments.
by chnaging the data types.
by changing the sequences of data.
================================================
=========
Constructor Chaining:it is process to connect
or chain one comstructor with another
constructor.
it is achived by two ways:
1. by using this() statement.
2 by using super() statement (with
inheritances).
[Link]() Statement : is used to conect or chain
one constructor with another constructor inside
the same class. constrcutor call() must be the
first statement inside the constructor so this()
must be written as the first statement of the
constructor.
Syntax: this(var1 , var2);
Note:one constructor can call() only .we can not
call() multiple constructors from one
constructor.
Note: it doesnot have any differences between
constructor overloading and constructor chaining
but constructor chaining code become shorter
(means it remove the length of coding).
================================================
every class is a non-primititve data
==============================================
ques 1. Design a simple project where user has
to travel from city A to city B by diferent
avaliable modes of transport. provide apporiate
implementation where user should select
apporpiate modes, should allowed to pay the
amount and he should be guide how to travel
through that selected mode of transport.
ques2. design a project for simple e-commerces
website where a user should be given options to
buy different products such as (shirt, jeans, t-
shirt, laptoop, tv, etc) user should be allowed
to select the product he wants to [Link] per
selected items set the details of product and
display the details of product user have got.
================================================
int [] x = new int[10];
[34, 52, 90, 0,0,0,72,91,37,57]
[0]=34
[1]=52
[2] =90
[3]=0
[4]=0
[5]=0
[6]=72
[7]=91
[8]=37
[9]=57
for(int i =0, i<[Link]; i++){
SOP(x[i]);
}
*************** find even number in array******
for(int i =0 , i<[Link];i++){
if(x[i]%2==0)
{
SOP(x[i])
}
}
============================================
3. design a project where we are allowed to
store multiple shirts objects. onces a shirts
object are stored then
1> access all the shirts with its details.
2> access all the shirts with the size 40.
3> access all the shirts with price range from
700 to 1500.
4> access all the shirts in blue color
5> access all the shirts from brand blackberry
with size 40.
6> access all the shirts with price >greater
than 2000 and size 40 or 42.
================================================
4. design a music player application where
details should be as titale, artist,type,etc
find
1> list of all songs
2> list of all songs from a given artist
3> list of all songs from the given type .
5. take 3 number input from user and print
second biggest.
================================================
two types of super() call
1) implicit super() = if super() call statment
is added by complier internally then it is
called implicit super() call [Link] case
to implicit super() call complier always calls
no argument constructor of parent class.
2) explicit super() = in case of super() call if
it is added by programer then it is called
explicit super() consturctor. in case of
explicit a programer can call any constructor of
parent class.
parent class is class have parent class called
object.
================================================
**Object Class = object class is the super most
parent class of every class in [Link]
class is avalibale in [Link] package and it
contains 11 [Link] ever a desgined a class
then it by defualt extends object class and all
the 11 methods of object class will be availbale
to every class.
================================================
Types of inheritnaces:

1. single-level inheritances= if there is one parent class and child class


then it is called single-level inheritances.

Ex: A is a parent class and B is a child class

2. multilevel inheritances= if there is a parent class and child class and


the child class is parent for another class then it is called multi-level
inheritances.

Ex: A is a parent class and B is a child class of A and parent class of C


and C is a child class B

3. heriachical inheritances=if there is one parent class and multiple


child class then it is called heriachical inheritances.

Ex: vechile is a parent class and bus,car and bike are child class

4. multiple inheritances= if there are multiple parents and single child


class then such inheritances is called multiple inheritances. multiple
inheritances is not Supported in java with class.

Ex: A, B are parent class and C is a child class of A and B

i). It is not allowed in java it gives Error because:one class can't have
more than one parent class.

ii). This structure is not allowed

iii). Ambiguity problem to call parent class constructor.

Ques =why multiple inheritances is not supported with class??

Ans= i). In Case of Multiple Inheritances ,ambiguity problem occurs at


the time of constructor() call from child class to parent class beacuse of
ambiguity problem multiple inheritances is not supported with class.

ii). The problem of Multiple Inheritances is aslo called Dimanod Shape


Problem in Programing [Link] shape problem is resloved
by the use of Interface.

5. hybird inheritances=Combination of two or more Inheritances is


called hybird [Link] will be supported if multiple inheritances is
not used in Structure.

=========================================================

Ques=Which types of Members from parent class are not Inherited to


child class??
Ans= i) Any private Members of Parent class is not inherited to Child
class .

ii). Constructor of Parent class is not inherited to Child class bacasuse


the constructor name must be same as class name whatever it is
[Link] Child class constructor can call() parent class
Cosntructor by use of super() call.

=========================================================

Variable Hidding= if parent class and child class will have variables with
the same name then variable get access from child class as per
references [Link] class variable get hidden which is called
variable hidding.

Super Keyworad= super is a keyword which is used to refer non-static


members of imedidate parent class.

==========================================================
======

Non-Primitve typecasting = when a non-prmititive data is converted


into another non-primitive data or when a class type data is converted
into another class type data then it is called non-primitve
[Link]-primitve typecasting is only achieve if classes will have
Is-A- Relationship or Inheritances.

Ex: Vechile Parent class is inherited to bike, car and bus child class.

***we can convert vechile into car or bike or bus because they have
parent and child relationship.

Ex: Animal parent class is inherited to cat and dog class.


***Vechile does not have any relation with animal so vechile details
cannot be converted into anmial type.

==========================================================
=====

2 types of Non-Primitive typecasting

1 Upcasting or Generalisation: i). upcastign is a process to store child


type object on parent references.

ii). upcasting is done by complier automatically so it is also called


Implicit Conversion.

Ex: parent class =Vechile an child class = Car , Bike, Bus;

Vechile v = new Car();

Vechile v1 = new Bike();

Vechile v2 = new Bus();

By upcasting details of only parents can be [Link] type details


cannot accesed.

=========================================================

2. Downcasting or Specialisation: i). Downcasting is a process to


convert parent type referneces into child type.

ii). By using downcasting we can access details of Parentas well as child


class.

Car() constructor will goto Car a=10 then Vechile x=20 then object 11
method.(c1 bhi usi object ko refer kre jisse v1 refer kr rha hai so we will
write it. Car c1 = (car)v1;
(type cast operator explicit
conversion)

(if phele se upcasting hua then only we need to we cando


downcasting.)

iv) donwcasting is not perform directly by complier it is achieved by


using typecast Operartor programmatically so it is called Explicit
conversion.

v) whenever parent references is stored on child references then it is


called downcasting.

when Psrent and child class will have the same name then child
method will update the parent class method and implementation will
be from child.

Ex:

Class Vechile {

public void start()

SOP("start Vechile");

public void stop()

SOP("Stop Vechile");}
}
Class Car extends Vechile

public void start()

SOP("Start Car");

=========================================================

Object Class = Object class is available in [Link] [Link] contains


11 methods which is by default available to every class.

Comand = javap [Link].

Method1 => toString() Mehtod

i). toString is a method avaliable in object class of [Link] ever an


object is created then toString method help to provide String
Reperentation of Oject.

ii). toString() method is recommended to override from child class so


that we can get useful information about object from object
references.

EX : Overridden toString

Class Object {

Public String toString()

{
return classname+"@"+hexadecimal;

}
public class Employ {

String name;
int id;
double salry;
Employ(){

}
Employ( String name , int id , double salry)
{
[Link]=name;
[Link]=id;
[Link]=salry;
}
public String toString() {
return name + id + salry;
}
Employ e1 = new Employ();
============================================
Method2 =>hashCode()

i). when ever an object is created then object is assigned with the
unqiue number that is hashCode.

II) it is recomended to override hashCode method() from our class to


provide the requried implementation.

EX: Overridden in hashCode()

class Object

public int hashCode()

{
return 567;

}
public int hashCode() {
return id;
}

==========================================================
======

Method 3 ==> equals(Object o)

1. equals() method is the method of object class which is used to


compare the internal details of object.

2. by using double equals we compare to primitve type data but in case


of non-primitve data it can compare object referneces of two object.

3. it is recomended to override equals() method so that we can


compare the internal detaisl of two objects.

EX: override in equals() method

class objct

public boolean equals(Object o)

class Employ

public boolean equals(Object o)

Employ x = (Employ)o;

return [Link]==[Link] && [Link]([Link]) &&

[Link] == [Link];

class Driver
{

public static void main(String[] args)

Employ e1 = new Employ("Roshni" , 67, 123.45);

=========================================================

Method4=> finalize()

[Link] for garbage collector =[Link]();

2. Finalize is a method of object class in [Link] ever an object is null


then it is the reonsibilty of garbage collector to earse the object of
memory before earsing the object of memory garbage collector
internally call finalize method to detach all the connections of [Link]
the manner the abnornmal behavoiur gets minmizesed.

3. we can call finalize method by calling garbage collector as


[Link]();

=========================================================

Polymorphism: polymorphism is a mechanicsm by which a memeber


behaves differently with the same name.

poly=many

morphism = forms

polymorphism=many forms
same name= different forms / Implementation

same method name = Different execution

same Object references = Different Behavoiur.

=========================================================th
ere are 2 Types of Polymorphism

1. Complie-Time / Static Polymorphism = if the execution of a memeber


remains same as per the connection providded by compiler at compile
time then it is called complie-time polymorphism.

What compiler sees/binds=same get executed by JVM at run time??

javac Driver java = connection gets provided by compier.

java Driver = Same get executed by JVM at run-time.

different ways to achieve compile time polymorphism

1. method overloading

2. constructor overloading

3. Operator overloading (Not supported in java)

=========================================================

[Link]-Time / Dynamic Polymorphism = if the exceution of the memeber


does not remain same as per the connection provide by compiler then
it is called run-time polymorphism.

What compiler sees /bind Same may not get executed by JVM at run-
time ??

javac Driver java = connection provide by complier


java Driver = execution will be decided by JVM as per Object created at
the run-time.

different ways to achieve run time polymorphism

1. Method Overriding.

2. Upcasting.

( Both work together in run-time polymorphism)

=========================================================

Ques = why operator overloading is not supported in java??

Ans = Opersator overloading is a mechanism by which a operator


behaves differently at different situations.

It is supported in c++ but it creates complexity in code.

to Keep java simple and more readable operator overloading is not


allowed in java

=========================================================

Method Overloading = i). when there are multiple methods inside a


class with the same name and different arguments then it is called
Method Overloading.

ii). In methodoverloading method can have any retun type and it can be
either static or non-static type method.

iii). in method overloading method same must be same and agrument


must be different.

we can achieve method overloading in three ways


1. By changing the number of arguments.

2. By chnaging the data type.

3. By changing the sequences of data.

=========================================================

Advantage of Method Overloading:

1. Method overloading helps to have simple and more readable code.

[Link] complexity is decaresed becasue we can have different forms by


using the same name.

EX: print() and println() are the overlaoded methods in


PrintStreamClass of java.( example of compile-time-polymorphism)

In Metod overloading we can achieve different forms with the same


name so it called by different names

1. Compile-Time Polymorphism

2. Static polymorphism

3. Static-Binding / Early-Binding

4. Static Method Dispatch

=========================================================

Ques Can we Overload main method of java ??

Ans = i). Yes we can overload main method of java where we can have
mutliple main methods inside same class but diferent agruments.

ii). main method are overload with different agument but JVM only call
that main method that have String agrument with main method and
other main method does not call without call inside the main method
with Sttring argument.

=========================================================

Method Overriding

1. when parent class and child class there are non-static method with
same name, same return type and same argument then it is called
Method Overriding.

2. In Method Overriding execution of method is poivded as per


objected created .

3. It will not depend as per referneces provided.

4. In method Method Overriding code implementation of parent get


modified by the new implementation from child class.

EX: Vechile v1 = new Car();

[Link](); ===> Execution of drive() will be as per Object


Created new Car() will be provided.

=========================================================

Ques = Can we Override the main Method of java ??

Ans = Method Overriding conecpt is apilcable only for non-static


methods in parent class and child class.

As main method is always static so Method overirding is not applicable


for main method.
=========================================================

differences between Overloading and Overridding

Overloading

1. in method overloading name must be same but argument should be


different .

2. Method overloading acchieved only from same class.

3. method overloading can performmed for static or non-static


method.

4. Method overloading is an example of complie time polymorphism.

Method Overridding

=========================================================

Data Hidding = Data Hidding is a process where data members of a class


are declared private so that they will not be visible or accessable from
other [Link] access the private type of data we need to design public
type of getters and setters method.

Beam class==== if fully encapsulated class where

1. all data members are private

2. public getters() and setters() are avaliable

3. only no-argument constructor are designed

4. it implements serializable interface.

such class called java beam class.


java beam class provides reuseablity feature so it widely used in
buliding projects.

class Employ implements serializable {

all data members are private

public getters() and setters() are avaliable

only no-argument constructor

Employ e1 = new Employ(); ---------->>>>>>Beam Object

=========================================================A
bstraction ---->>> Abstraction is a mechanism by which we show
functionality to user but we hide internal implementation from user.

in another word = abstraction is a mechanism to show what it does to


user but to hide how it does from user.

abstraction can be achieved two ways

1. By using Abstract class (To acheive 0 to 100% abstarction).

2. By using Interface (To achieve 100% abstraction ).

=========================================================

Static block =1. if a block is declared by using static keywoard then such
block is caled static block.
2. we can have multiple static block inside a class and they are loaded
class static area in the sequnecses they are written in the code.

3. Static block is executed the moment is loaded is class static area is


only one time.

Note= inside static block and non-static block we can intializse static or
non-static variable so it is also called initalizser block.

=========================================================Q
ues : run a program without main method??

Ans : we can run a program without main method if jdk version is


before jdk7.

jdk 7 and onwards versions mandatory requries to start the excution


of a program.

=========================================================N
on-Static block = 1. if a block is not declared by using static keywoard
then such block is called non-static block.

2. a non-static block is loaded inside object in heap area so it will be


excuted whenever object of the class is created.

Note= inside static block and non-static block we can intializse static or
non-static variable so it is also called initalizser block.

=========================================================

ques1. differneces between class and abstract class.

class

1. it is declared by using class keywoard.


2. object can be created.

3. methods are always concrete.

4. A class is not use to achieve hidding.

abstract class

1. it is declared by using abstract keywoard.

2. Object can't be created.

3. methods can be abstract as well as concrete.

[Link] is used to achieve 0% to 100% abtraction or hidding.

ques2. differences between class and interface.

Class

1. it is declared by using class.

2. Object can be cretaed.

3. Varaible can be static as well as non-static.

4. Constructors are allowed to intializse non-static memebers.

[Link] and non-static block are allowed.

[Link]-static methods are always concrete.

7. Default type method are not allowed.

8. Multiple Inheritances are not allowed.

Interface

1. it is declared by using interface.


2. Object can't be created.

3. Varaibles are by default static.

4. Constructors are not allowed.

5. Static or non-static blocks are not allowed.

6. Non-static methods are by default abstract.

7. Default types method are allowed sinces java8.

8. Multiple Inheritances is allowed.

ques3. differnces between abstract class and interface.

Abstract class

1. it is declared by using abstract class keywoard.

2. It is used to achieve 0% to 100% abstraction.

3. Methods can be abstract or concerte type.

4. Variables are static as well as non-static.

5. Constructors are allowed.

6. Static and non-static blocks are allowed.

7. Multiple inheritances are not allowed.

Interface

1. it is declared by using interfcae keywoard.

2. it is used to acheive 100% abstraction.

3. Methods are by default abstract type.


4. Variables are by default static.

5. Constructors are not allowed.

6. Static or non-static blocks are not allowed.

7. Multiple Inheritances are allowed.

Ques4 give some real time example of Interface /abstraction.

Ans:4.

1. while performing transcation at ATM machine a user is shown only


functionilty but internal working of ATM is not shown to user.

[Link] any e-commerces website a user is only shown a functionality such


as ADD TO CART , BUY, WISHLIST BUT ITS INTERNAL WORKING NOT
SHOWN TO USER.

3. while using any bank application a user it shown only functionality


such as SEND MONEY, BALANCES, HISTROY etc but its working is not
shown to user.

Ques5. features of java8

ans5:.java8 is the biggest update which was relased in 2014 with many
features.

1. Lambda Expression :: was the very inportant feature which was


added in java8.

2. StreamAPI :: was provided in java8 to work on large amount on


data.

3. TimeandDateAPI :: was added in java8 to work on time and date for


different zone.
4. Static Method :: static type method was allowed inside interface in
java8.

5. Default Method :: is a speacial type method which was allowed inside


interface in java8 feature.

6. Functional Interface :: Functional type Interfcae and it unnotation


was allowed in java8 feature.

=========================================================

Final Keywoard :: i. final is a keywoard which is used to retsrict


modification of a member.

final or abstract can work together.

ii. final can be

1. A Final class ::i. if a class will be declared by using keyoward final


then such class is called a final class.

ii. if a class is final then it cannot have any child class.

iii. Final class be child for some class but it cannot be parent for any
class.

Ex: final class Vechile {}

class Car extends Vechile{} ---->>> Error : a final class can't be parent
class.

2. A Final Method() :: i. if a method() is declared as final then such


method can be inherited to child class but it cannot be overridden from
child class.

EX: Class Vechile {


public final void start(){

SOP("Start the Vechile");

Class Car extends Vechile {

@override

public final void start() Error -->> Final Method can't be


overriden.

SOP("Start Car");

3. A Final Variable :: i. if a varaible is declared by using final keywoard


then it is called a final variable.

ii. the value of final variable can not change onces it is initalizsed.

Ex : final int x =60;

x =90; -->> Error : final variable can't be modoified.

final int y ; -->> blank final Variable

y = 35; in local variable.

a. Final Static Variable :: i. if a static variable is declared as final


Keywoard then it is called a static final variable.
ii. a static final variable shouble be initalised at the time of declaration
otherwise it should be intializse by using static [Link] it is not initalizse
then it will cause compilcation error.

EX: Class Car {

final static String brand;

static{

brand="tata";

b. Non-Static Final Variable :: if a non-static variable is declared by using


final Keywoard then it is callled non-static final variable. a non-static
final variable must be intializse from every constructor otherwise it will
give complication error.

=========================================================

Immutable class :: if a class is desgined in such a maaner that onces is


object is craeted then any of details cannot be modified then such
class is called immutable class.

Steps to create Immutable class

1. We have to declare the class as final.

2. declare all the variable private and final so that any kind of
modification will get restricted.

3. we have to desgin a constructor from where all the details shouble


be initalizse.

4. we have to design getters for every private data.


=========================================================
Wrapper class :: [Link] java every primitve data has in-bulit class avaliable
which is called wrapper class.

2. by using wrapper class we can convert a primitve data into non-


primitve data and non-primitve back into primitve type data.

Primitive ================================Non-Primitive data

byte=====================================Byte

short=====================================Short

int========================================Integer

long=======================================Long

float======================================Float

double=====================================Double

char=========================================Character

boolean======================================Boolean

=========================================================B
oxing/auto-boxing :: boxing is a mechanism to convert a primitve data
into non-primitive type.

In another word when a primitive type data is converted into class type
data then it is called [Link] is done by complier automaticaly so it is
also called auto-boxing.

int x=38;

Integer y =x; (int ko Integer bana that is called boxing)


-----------------------------------------------------------------------------------------------

Unboxing :: Unboxing is a process to convert a non-primtive data back


into primtitve [Link] is done by complier automatically so it is also
called auto-unboxing.

Integer p=48;

int q=p; (non-primitive data ko primitive bana that is called unboxing)

=========================================================F
eatures of Wrapper class ::::

1. Integer Wrapper class :: Integer Wrapper class provide static type


variable min value and max value by which we can get the value of
mininum and maximum type data.

EX:: [Link](Integer.MIN_VALUE);

[Link](Integer.MAX_VALUE);

2. by the user of wrapper class, we can convert any data into string type
by using toString Method()

EX:: x = 357085;

String s1=[Link](x);

[Link]("Total digit is " +


[Link]());

double d = 234.456;

String s2 = [Link](d);

[Link]("total digit is " +


([Link]()-1));
[Link] can convert a string type value into its
orginal form by using methods of wrapper class.
EX:: String s1 ="234567";

[Link](s1+100);

Integer p = [Link](s1);

int x = [Link](s1);

[Link](p+100);

[Link](x+1000);

EX:: String s2 = "345@78";

int a = [Link](s2);

SOP(a) ---->>> Exception ::


String can't be convert itno int type.

4. with the help of wrapper class we can store


any data in the form of object type
EX:: Object o1 ="mohan"; //upcasting or impicit.

Object o2= 34;

Object o3 =9.3;

Object o4='#';

Object o5=true;

[Link](o1);

[Link](o2);

[Link](o3);

[Link](o4);
[Link](o5);

5. by the use of wrapper class we can explictly


convert any object type data into its orginal
form.
EX:: Object o1 =67; // downcasting

int x = (Integer)o1; (possible)

double y = (Double)o1: (not possible -->>


it gice error)

=======================================================
==Instances of Keywoard:: is a Keywoard which is
used to check whether the given referneces holds
the object of a particular type or [Link]
checking it return true or false.
EX:: Object o1 =67;
SOP(o1 instanceof Integer); == true;

SOP(o1 instanceof String); ==


false;

=======================================================
==Package:: package is a phyiscal floder which
contains similaier types of files.A package is
created by using keywoard package
we can use the details of one package inside
another package by importing one package into
another package.
import keywoard is used to import a package into
another package.
types of package::
1. import/predefined package::java provides a
total of 14 packages under java library to
perform various [Link] it
contains 7thousand classes and 7lakh of methods.
EX:: [Link], [Link], [Link] , [Link] ,
[Link],[Link],[Link],[Link].
2. User defined package::a package created by
user is called user-deifned package. package is
created by using package keywoard and apropirate
name provided to package.
EX::package [Link];
[Link] = comapny specfication;
com=domain name;
wipro=company name;
[Link]= cilent specification;
hdfc=client name;
loan=project name;
home-loan=module of project;
================================================
Advantages of Package::
1. it provides better orgainisation of code.
=======================================================
==

Exception handling ::is a mechanism by which a


program maintains the formal flow of excution
even in case exception occurs in the program.
EX:: [Link] Expression;
[Link]

[Link]

[Link]

[Link]

[Link]

[Link] == java package


Arithmatic Expression,ArrayIndexOutOfBoundsException
=class in java

Exception :: Exception is an unexcepted situation


which occurs at run time an beacuse of exception a
program does not maintain the normal flow of excution.
it gets terminated in between.

different ways to handle the exception.


java provides 5 keywoards such as::

1. try [Link] 3. finally 4. throw 5. throws

to handle the exception.

try-catch block :: try-catch is a block which is uesd


to handle the exception and maintain the formal flow of
[Link] uses two block which are try block and
catch block.

try block : try is a block which is used to write


the statement which may cause an exception.

syntax:: try{ // try block statement


}.

when an exception occures in try block then object of


the exception is thrown by using try [Link] need to
catch this object in order to maintain the normal flow
of excution.

catch bloc is used with try block to catch this object.

Catch block : catch is a block which is used to catch


the exception object and maintain the normal flow.

synatx:: try{ // try block statement }


catch(Arthmatic exception e){

// catch statemnt }

every exception class have same parent class called


exception.

=======================================================
==Important points of about try and catch block::

1. we can not write any statment between try and catch


block. try block must be immedidatelty followed by
catch block.

2. once an exception ocurs in try block the contrl is


immdeidately transfered to catch [Link] statements
return in try block will not excute completely in case
exception occurs.
3. in catch block we should declare appropirate
exception otherwise exception will not be handled.

4. we can throw only one exception at a time from a try


[Link] exception cannot be thrown from one try
block at the same time.

5. we can have multiple catch blocks with one try block


to catch and handle different types of exceptions.

note:: child type exceptions should be declare


and then parent type exception should be declared in
the end.

6. we can have many try catch block inside a program


to generate and catch mulitple exceptions.

7. Exception reperents object which contains various


mthods that can we used when exception occurs.

8. the details of exception is always avaliable on


exception references so we can get exception details by
using exception references.

9. exception proviedes a message called getMessage() by


which we can get the message about the exception.

EX:: SOP([Link]()); --->> it will point the


message of exception.

10. we can trace the details of exception by calling a


method is PrintStackTrace() of Exception. it is a
method of throwable class.

EX:: [Link](); -->> it proivde complete


hirearchy of exception generated.

10. we can declare multiple exception on one catch


block by using simple pipline(|).
EX:: catch(ArrayIndexOutOfBoundsException|
ArithmaticException)

{ SOP([Link]()); }

catch(Exception)

{ SOP([Link]()); }

11. we can use try-catch block inside try block as well


as inside catch block which is called nested try-catch
block.

EX::try { [Link](x/index);

[Link](a[3]/a[index]);

catch(ArithmeticException|
ArrayIndexOutOfBoundsException e ) {
[Link]([Link]()); }

} catch(Exception e) {

[Link]([Link]());
}

=======================================================
==

Exception e = new ArithmaticException;

it craete the object then heap areas was created so

1. all methods of object class.

2. throwable class method.

3. runtime exception.

4. arithmetic exception

=======================================================
==

exception is unexcepted situation which occurs at run


time and it can be handled to maintain the normal of
excution.

error = while error is a situation which occurs at the


runtime which can not be handle to maintain the normal
of excution

=======================================================
==two types of exception

1. checked exception::if an exception is checked by


compiler wheter it is handled or not at compile time
then such exception is called checked exception.

if check type exception is not handled then it causes


compliation error.

2. unchecked exception::if an exception is not checked


by complier whether it is handled or not at compile-
time then such exception is called unchecked exception.

unchecked exception does not cause any error at compile


time.

=======================================================
==

differences between checked and uncheck exception.

checked Exception-->>1. it is checked by compiler


whether it is handleded or not.

2. checked exception cause error at compile time

[Link] is mandatory to handle checked exception at


compile time.
[Link] of checked exception are ::
InteruptedException, IOException,FilNotFoundException
etc.

uncheck exception-->>1. it is not checked by complier


whether it is handleded or not

2. unchecked exception does not cause any error at


compile time.

3. it is not mandatory to handle unchecked exception at


compile time.

4. examples of unchecked exception are:


ArithmaticException , NullPointerException,
ArrayIndexOutOfBoundException etc.

=======================================================
==Throw Keywoard::1. throw is a keywoard which is used
to throw the object of an exception.

2. it is the keywoard which genertaes the exception by


suing throw keywoard we can genertae pre-defineded
exception as well as custom exception.

[Link] the object which will be exception object can be


thrown by throw keywoard.

EX::throw new ArithmaticException -->>unchecked


exception

throw new InsufficentException -->> custom exception

throw new UnderAgeException -->> custom exception

=======================================================
==

Throws Keywoard ::is a keywoard which is used to handle


the exception of a method by the use of throws keywoard
the exception of method is propatageted at method
call().

it will be callers resonsiblity to handle the exception


by using trycatch at the time of method call.

by one throws keywoard we can handle multiple


exceptions.

ex::

import [Link];

public class Program7 {

public static void main(String[] args) {

try{

test();

catch(Exception e) {

[Link]("IO Exception occured.");

public static void test() throws Exception{

[Link]("this is test Method");

throw new IOException(); //it is way to call


the throws keywoard.

Exception e = new IOException(); //it is way to


call the throws keywoard.

throw e;
}

=======================================================
==

differences between throw and throws

throw keywoard ==1. is used to throw the exception


object or create the exception

2. we can throw only one exception object at a time by


using one throw keywoard.

3. throw keywoard is followed by the object of the


exception.

[Link] keywoard is used inside method body.

throws keywoard==1. is used to handle the exception of


method and propogate it to method call. (Mehtod
propogation).

2. we can handle multiple exceptions at a time by using


one throws keywoard.

3. throws keywoard is followed by the name of


exception.

4. throws keywoard is used at method declaration.

=======================================================
==

return by using try-catch

1. public static int test() {

try {

// statement1
return 45;

catch(Exception e) {

[Link]("catch block");

[Link] static int test() {

try {

// statement1

return 45;

catch(Exception e) {

[Link]("catch block");

return 50;

[Link] static int test() {

try {

// statement1

return 45;

catch(Exception e) {

[Link]("catch block");
return 50;

finally{
[Link]("catch
block");

return 8;

=======================================================
==

custom -->>exception created by user is called custom


exception or user-defined exception.

2. all custom exception are type checked exception


which will cause error compliation so it must be handle
at compile time.

Step to create custiom exception

1. create a class and extends exception to provide all


the features of exceptions.

2. to create custom exception we have to throw the


object of exception.

3. custom exception causes error so it has to be


handled by using throws keywoard at complation to
propagate the exception.

4. when ever this method is call then it should be


handled by using try and catch block.

You might also like