SlideShare a Scribd company logo
1.what is the difference between a instance variable and an local variable.Explain clearly and
give an example.
2.what is the difference between call-by-vale and call by-reference when working with java
methods? explain clearly and given an example.
Solution
1)
Instance variables:
Instance variables area the variables whose new copy will be created when ever an object is
created.
They will be used to hold the data of an object.They can be accessible everywhere with in the
class.
For every new Object creation a new copy of instance variables will get created.
Rectangle.java
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
super();
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double calArea()
{
return getLength()*getWidth();
}
}
______________________________
TestClass.java
public class TestClass {
public static void main(String[] args) {
Rectangle rect1 =new Rectangle(9,10);
System.out.println("Area of the Rectangle#1 :"+rect1.calArea());
Rectangle rect2 =new Rectangle(11,13);
System.out.println("Area of the Rectangle#2:"+rect2.calArea());
}
}
_________________________________
output:
Area of the Rectangle#1 :90.0
Area of the Rectangle#2:143.0
_______________________________
Here in the above example Rectangle class contains length and width as instance variables.
When ever we created object for the Rectangle class a new copy of instance variables will be
created.
Rectangle rect1 =new Rectangle(9,10);
When the above statement is executed a Rectangle object will be created ,when ever Rectangle
object is created new copy of instance variables will be created which holds length=9 and
width=10 inside it.
Rectangle rect2 =new Rectangle(11,13);
When the above statement is executed another Rectangle object will be created ,when ever
Rectangle object is created again new copy of instance variables will be created which holds
length=11 and width=13 inside it.
Here first Rectangle object instance variable will not get overridden by the second Rectangle
object instance variables.Because those instance variables will stored inside each object
seperately in different memory locations.
When coming to the local variables.These are the variables which are declaredlocally inside the
method.Their scope is limited only to the method itself.If we have a local variables which is of
same name as the instance variable and if we are accessing the the variiable then priority will be
given to the local variables than instance variables.These local variables cannot be accessed be
other method of that obejct.Their scope is limited only to the method i which they heve been
declared.
Square.java
public class Square {
private double side;
public Square(double side) {
super();
this.side = side;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double gerArea()
{
double side=8;
return side*side;
}
}
____________________________
Here we are created Square class Object.Inside that we have created side as instance variable.But
if we observed the getArea() method inside the Square class.We can have a local variable whose
name is also side and initialized with the value 8.
Then when we call the getArea() method of the Square class Object.Though we are having an
instance variable as we are having the local variable which is of same name as the instance
variable.then priority will be given to the local variable instead of instance variables.Local
variables are powerful locally inside the method where they have been declared.
TestSquare.java
public class TestSquare {
public static void main(String[] args) {
Square sq=new Square(10);
System.out.println("Area of the Square :"+sq.gerArea());
}
}
________________________
This code is creating the Square class object by passing the 10 as argument.Then the instance
variable 'side' get initialized to 10.But when we are calculating the area of the square by calling
the method getArea() the result will be 64 instead of 100.Because we declared and initialized a
local variable inside the getArea() method.with the same name as the instance variable.When
while calculating the area as we are calliing the variable side then priority will be given to the
local variable than instance variable.That why we got the area s 64.
____________________________
2)Call by value:
Calling the method by passing the numeric value as argument is called call by value
Square.java
public class Square {
private double side;
public Square(double side) {
super();
this.side = side;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double gerArea()
{
double side=8;
return side*side;
}
}
___________________________________
TestSquare.java
public class TestSquare {
public static void main(String[] args) {
Square sq=new Square(10);
System.out.println("Area of the Square :"+sq.gerArea());
}
}
______________________________
Here while creating the Square class Object we are passing numeric value 10 as argument.As we
are passing the numeric value 10 as argument while creating Square class Object we are using
call by value .
Call By reference:
Calling the method by passing the reference of another object as argument is called call by
reference.
Lets discuss by taking an Example.
RoomDimension.java
public class RoomDimension {
//Declaring instance variables
private double length;
private double width;
//Parameterized constructor
public RoomDimension(double length, double width) {
super();
this.length = length;
this.width = width;
}
//Setters and getters
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
//This method will calculate the area of the carpet and return it.
public double getArea()
{
return getLength()*getWidth();
}
//toString() method is used to display the contents of an Object inside it.
@Override
public String toString() {
return "RoomDimension# Length=" + length + " Width=" + width;
}
}
________________________
Here RoomDimesion class contains length and width as instance variables.It has the method
which calculate the area.
Let have another class ,to that class constructor we are going to pass the RoomDimension class
reference which creating the object.
RoomCarpet.java
public class RoomCarpet {
//Declaring instance variables
private RoomDimension size;
private double carpetCost;
//Parameterized constructor
public RoomCarpet(RoomDimension size, double carpetCost) {
super();
this.size = size;
this.carpetCost = carpetCost;
}
//Setters and getters
public RoomDimension getSize() {
return size;
}
public void setSize(RoomDimension size) {
this.size = size;
}
public double getCarpetCost() {
return carpetCost;
}
public void setCarpetCost(double carpetCost) {
this.carpetCost = carpetCost;
}
//This method will calculate and return the total cost of the carpet
public double getTotalCost()
{
return size.getArea()*getCarpetCost();
}
//toString() method is used to display the contents of an Object inside it.
@Override
public String toString() {
return " RoomCarpet# "+size + " CarpetCost=" + carpetCost+" Area of The Carpet
:$"+getTotalCost();
}
}
__________________________________
TestClass.java
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
//Declaring variables
double length,width,carpetCost;
//Scanner class object is sued to read the inputs entered by the user
Scanner sc=new Scanner(System.in);
//Getting the length of the carpet entered by the user
System.out.print("Enter the Carpet Length (in ft):");
length=sc.nextDouble();
//Getting width of the carpet entered by the user
System.out.print("Enter the Carpet Width (in ft):");
width=sc.nextDouble();
//getting the cost of the carpet entered by the user
System.out.print("Enter the Cost of the Carpet (per sqft):$");
carpetCost=sc.nextDouble();
/* creating the object for the RoomDimesion class
* by passing the length and width as arguments
*/
RoomDimension size=new RoomDimension(length, width);
/* creating the object for the RoomCarpet class by passing
* the RoomDimension and carpet cost as arguments
*/
RoomCarpet rc=new RoomCarpet(size, carpetCost);
//Displaying the content of the RoomCarpet Class Object
System.out.println(rc.toString());
}
}
___________________________
Here in this TestClass we are creating RoomDimension class object by passing legth and width
as arguments.And next while we area creating RoomCarpet Class Object we are pasisng the
reference of RoomDimension class reference(size) and carpet cost as arguments.Hee we are
passing the reference of another object while creating the object means we are using call by
reference concept here.
_________Thank You

More Related Content

PPTX
Chap2 class,objects contd
PDF
DOCX
Lecture 21.07.2014
PPS
Class method
PPT
packages and interfaces
PPTX
Classes,object and methods java
PPTX
Class and Object.pptx from nit patna ece department
PPT
Class & Object - Intro
Chap2 class,objects contd
Lecture 21.07.2014
Class method
packages and interfaces
Classes,object and methods java
Class and Object.pptx from nit patna ece department
Class & Object - Intro

Similar to 1.what is the difference between a instance variable and an local va.pdf (20)

PPTX
Java As an OOP Language,Exception Handling & Applets
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
PPT
Chapter 4 - Defining Your Own Classes - Part I
PPT
Java căn bản - Chapter4
PDF
Java unit 7
PPTX
Lecture 5.pptx
PPT
Object and class
PPTX
Classes, objects in JAVA
PPT
PPS
Introduction to class in java
PPT
Java: Objects and Object References
PDF
Java unit2
PPTX
Chapter ii(oop)
DOCX
Java sessionnotes
PPTX
Lecture_4_Static_variables_and_Methods.pptx
PPT
Ch. 6 -Static Class Members.ppt programming
PPT
PPTX
Chapter 5:Understanding Variable Scope and Class Construction
PPTX
Java Foundations: Methods
PPT
4. Classes and Methods
Java As an OOP Language,Exception Handling & Applets
Class and Object JAVA PROGRAMMING LANG .pdf
Chapter 4 - Defining Your Own Classes - Part I
Java căn bản - Chapter4
Java unit 7
Lecture 5.pptx
Object and class
Classes, objects in JAVA
Introduction to class in java
Java: Objects and Object References
Java unit2
Chapter ii(oop)
Java sessionnotes
Lecture_4_Static_variables_and_Methods.pptx
Ch. 6 -Static Class Members.ppt programming
Chapter 5:Understanding Variable Scope and Class Construction
Java Foundations: Methods
4. Classes and Methods
Ad

More from archgeetsenterprises (20)

PDF
Need to revise working code below,A good design means the applicat.pdf
PDF
MolluscaIdentify the distinguishing characteristics of Phylum Moll.pdf
PDF
Match the directional term with its Correct ipsilateral media in.pdf
PDF
LithiumA. has a very narrow therapeutic range.B. completely cro.pdf
PDF
Let Z be the group of all integers under the operation of addition. E.pdf
PDF
In the United States today, nearly all of our electricity isproduc.pdf
PDF
In a radio link is required to send digital voice at 4800bps,but can.pdf
PDF
hi i have to write a java program involving link lists. i have a pro.pdf
PDF
Glial cells were originally thought to play a very minor role in the .pdf
PDF
Fungal reproductive cycle. Place the appropriate label in the correct.pdf
PDF
Explain the concept of distributive justiceSolutiondistributiv.pdf
PDF
Fecal-oral infections are often a result of _____ droplet transmissi.pdf
PDF
Dr. Z conducts a study examining the effect of socioeconomic status .pdf
PDF
Double branded DNA viruses (select only one answer) all insert their.pdf
PDF
Discuss the mechanisms by which antibiotic resistance genes can be h.pdf
PDF
Develop two biologically relevant and researchable questions comparin.pdf
PDF
Describe two methods for communicating the material in an Informatio.pdf
PDF
Describe the following structuresfunctions or cells Dermal, vascul.pdf
PDF
Describe the accounting and finance structure in an organization..pdf
PDF
Consider an assembly of thousands of people, all screaming, yelling,.pdf
Need to revise working code below,A good design means the applicat.pdf
MolluscaIdentify the distinguishing characteristics of Phylum Moll.pdf
Match the directional term with its Correct ipsilateral media in.pdf
LithiumA. has a very narrow therapeutic range.B. completely cro.pdf
Let Z be the group of all integers under the operation of addition. E.pdf
In the United States today, nearly all of our electricity isproduc.pdf
In a radio link is required to send digital voice at 4800bps,but can.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
Glial cells were originally thought to play a very minor role in the .pdf
Fungal reproductive cycle. Place the appropriate label in the correct.pdf
Explain the concept of distributive justiceSolutiondistributiv.pdf
Fecal-oral infections are often a result of _____ droplet transmissi.pdf
Dr. Z conducts a study examining the effect of socioeconomic status .pdf
Double branded DNA viruses (select only one answer) all insert their.pdf
Discuss the mechanisms by which antibiotic resistance genes can be h.pdf
Develop two biologically relevant and researchable questions comparin.pdf
Describe two methods for communicating the material in an Informatio.pdf
Describe the following structuresfunctions or cells Dermal, vascul.pdf
Describe the accounting and finance structure in an organization..pdf
Consider an assembly of thousands of people, all screaming, yelling,.pdf
Ad

Recently uploaded (20)

PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
PDF
Open folder Downloads.pdf yes yes ges yes
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Insiders guide to clinical Medicine.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
01-Introduction-to-Information-Management.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Basic Mud Logging Guide for educational purpose
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Cardiovascular Pharmacology for pharmacy students.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GDM (1) (1).pptx small presentation for students
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Open folder Downloads.pdf yes yes ges yes
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Insiders guide to clinical Medicine.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
01-Introduction-to-Information-Management.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Open Quiz Monsoon Mind Game Final Set.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
The Final Stretch: How to Release a Game and Not Die in the Process.
PPH.pptx obstetrics and gynecology in nursing
TR - Agricultural Crops Production NC III.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Basic Mud Logging Guide for educational purpose
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx

1.what is the difference between a instance variable and an local va.pdf

  • 1. 1.what is the difference between a instance variable and an local variable.Explain clearly and give an example. 2.what is the difference between call-by-vale and call by-reference when working with java methods? explain clearly and given an example. Solution 1) Instance variables: Instance variables area the variables whose new copy will be created when ever an object is created. They will be used to hold the data of an object.They can be accessible everywhere with in the class. For every new Object creation a new copy of instance variables will get created. Rectangle.java public class Rectangle { private double length; private double width; public Rectangle(double length, double width) { super(); this.length = length; this.width = width; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; }
  • 2. public double calArea() { return getLength()*getWidth(); } } ______________________________ TestClass.java public class TestClass { public static void main(String[] args) { Rectangle rect1 =new Rectangle(9,10); System.out.println("Area of the Rectangle#1 :"+rect1.calArea()); Rectangle rect2 =new Rectangle(11,13); System.out.println("Area of the Rectangle#2:"+rect2.calArea()); } } _________________________________ output: Area of the Rectangle#1 :90.0 Area of the Rectangle#2:143.0 _______________________________ Here in the above example Rectangle class contains length and width as instance variables. When ever we created object for the Rectangle class a new copy of instance variables will be created. Rectangle rect1 =new Rectangle(9,10); When the above statement is executed a Rectangle object will be created ,when ever Rectangle object is created new copy of instance variables will be created which holds length=9 and width=10 inside it. Rectangle rect2 =new Rectangle(11,13); When the above statement is executed another Rectangle object will be created ,when ever Rectangle object is created again new copy of instance variables will be created which holds length=11 and width=13 inside it. Here first Rectangle object instance variable will not get overridden by the second Rectangle object instance variables.Because those instance variables will stored inside each object seperately in different memory locations.
  • 3. When coming to the local variables.These are the variables which are declaredlocally inside the method.Their scope is limited only to the method itself.If we have a local variables which is of same name as the instance variable and if we are accessing the the variiable then priority will be given to the local variables than instance variables.These local variables cannot be accessed be other method of that obejct.Their scope is limited only to the method i which they heve been declared. Square.java public class Square { private double side; public Square(double side) { super(); this.side = side; } public double getSide() { return side; } public void setSide(double side) { this.side = side; } public double gerArea() { double side=8; return side*side; } } ____________________________ Here we are created Square class Object.Inside that we have created side as instance variable.But if we observed the getArea() method inside the Square class.We can have a local variable whose name is also side and initialized with the value 8. Then when we call the getArea() method of the Square class Object.Though we are having an instance variable as we are having the local variable which is of same name as the instance variable.then priority will be given to the local variable instead of instance variables.Local variables are powerful locally inside the method where they have been declared. TestSquare.java public class TestSquare { public static void main(String[] args) {
  • 4. Square sq=new Square(10); System.out.println("Area of the Square :"+sq.gerArea()); } } ________________________ This code is creating the Square class object by passing the 10 as argument.Then the instance variable 'side' get initialized to 10.But when we are calculating the area of the square by calling the method getArea() the result will be 64 instead of 100.Because we declared and initialized a local variable inside the getArea() method.with the same name as the instance variable.When while calculating the area as we are calliing the variable side then priority will be given to the local variable than instance variable.That why we got the area s 64. ____________________________ 2)Call by value: Calling the method by passing the numeric value as argument is called call by value Square.java public class Square { private double side; public Square(double side) { super(); this.side = side; } public double getSide() { return side; } public void setSide(double side) { this.side = side; } public double gerArea() { double side=8; return side*side; } } ___________________________________ TestSquare.java public class TestSquare {
  • 5. public static void main(String[] args) { Square sq=new Square(10); System.out.println("Area of the Square :"+sq.gerArea()); } } ______________________________ Here while creating the Square class Object we are passing numeric value 10 as argument.As we are passing the numeric value 10 as argument while creating Square class Object we are using call by value . Call By reference: Calling the method by passing the reference of another object as argument is called call by reference. Lets discuss by taking an Example. RoomDimension.java public class RoomDimension { //Declaring instance variables private double length; private double width; //Parameterized constructor public RoomDimension(double length, double width) { super(); this.length = length; this.width = width; } //Setters and getters public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) {
  • 6. this.width = width; } //This method will calculate the area of the carpet and return it. public double getArea() { return getLength()*getWidth(); } //toString() method is used to display the contents of an Object inside it. @Override public String toString() { return "RoomDimension# Length=" + length + " Width=" + width; } } ________________________ Here RoomDimesion class contains length and width as instance variables.It has the method which calculate the area. Let have another class ,to that class constructor we are going to pass the RoomDimension class reference which creating the object. RoomCarpet.java public class RoomCarpet { //Declaring instance variables private RoomDimension size; private double carpetCost; //Parameterized constructor public RoomCarpet(RoomDimension size, double carpetCost) { super(); this.size = size; this.carpetCost = carpetCost; } //Setters and getters public RoomDimension getSize() { return size; } public void setSize(RoomDimension size) { this.size = size; }
  • 7. public double getCarpetCost() { return carpetCost; } public void setCarpetCost(double carpetCost) { this.carpetCost = carpetCost; } //This method will calculate and return the total cost of the carpet public double getTotalCost() { return size.getArea()*getCarpetCost(); } //toString() method is used to display the contents of an Object inside it. @Override public String toString() { return " RoomCarpet# "+size + " CarpetCost=" + carpetCost+" Area of The Carpet :$"+getTotalCost(); } } __________________________________ TestClass.java import java.util.Scanner; public class TestClass { public static void main(String[] args) { //Declaring variables double length,width,carpetCost; //Scanner class object is sued to read the inputs entered by the user Scanner sc=new Scanner(System.in); //Getting the length of the carpet entered by the user System.out.print("Enter the Carpet Length (in ft):"); length=sc.nextDouble(); //Getting width of the carpet entered by the user System.out.print("Enter the Carpet Width (in ft):");
  • 8. width=sc.nextDouble(); //getting the cost of the carpet entered by the user System.out.print("Enter the Cost of the Carpet (per sqft):$"); carpetCost=sc.nextDouble(); /* creating the object for the RoomDimesion class * by passing the length and width as arguments */ RoomDimension size=new RoomDimension(length, width); /* creating the object for the RoomCarpet class by passing * the RoomDimension and carpet cost as arguments */ RoomCarpet rc=new RoomCarpet(size, carpetCost); //Displaying the content of the RoomCarpet Class Object System.out.println(rc.toString()); } } ___________________________ Here in this TestClass we are creating RoomDimension class object by passing legth and width as arguments.And next while we area creating RoomCarpet Class Object we are pasisng the reference of RoomDimension class reference(size) and carpet cost as arguments.Hee we are passing the reference of another object while creating the object means we are using call by reference concept here. _________Thank You