Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
126 views

Parameter Passing Mechanisms and This in Java

The document discusses various parameter passing mechanisms in Java like pass by value, pass by reference, and pass by constant value. It provides examples to illustrate how primitive types, objects, and arrays are passed to methods. The document also discusses how the this keyword is used to refer to instance variables when a local variable has the same name. It demonstrates how constructors can be used to initialize instance variables differently.

Uploaded by

ashoku2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views

Parameter Passing Mechanisms and This in Java

The document discusses various parameter passing mechanisms in Java like pass by value, pass by reference, and pass by constant value. It provides examples to illustrate how primitive types, objects, and arrays are passed to methods. The document also discusses how the this keyword is used to refer to instance variables when a local variable has the same name. It demonstrates how constructors can be used to initialize instance variables differently.

Uploaded by

ashoku2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Parameter Passing Mechanisms and this Keyword in Java

/* An Incorrect Attempt to Write a swap( ) Method to Swap Values


of Two Primitive Types in Java */
// BadSwapTest.java
public class BadSwapTest {
public static void swap(int x, int y) {
System.out.println("#2: x = " + x + ", y = " + y);
int temp = x;
x = y;
y = temp;
System.out.println("#3: x = " + x
}
public static void main(String[] args)
int a = 19;
int b = 37;
System.out.println("#1: a = " + a
// Call the swap() method to swap
BadSwapTest.swap(a, b);
System.out.println("#4: a = " + a
}
}
/*
#1:
#2:
#3:
#4:
*/

a
x
x
a

=
=
=
=

19,
19,
37,
19,

b
y
y
b

=
=
=
=

+ ", y = " + y);


{
+ ", b = " + b);
values of a and b
+ ", b = " + b);

37
37
19
37

/* An Example of Pass by Constant Value

*/

// PassByConstantValueTest.java
public class PassByConstantValueTest {
// x uses pass by constant value and y uses pass by value
public static void test(final int x, int y) {
System.out.println("#2: x = " + x + ", y = " + y);
/* Uncommenting following statement will generate a compiler error */
// x = 79; /* Cannot change x. It is passed by constant value */
y = 223; // Ok to change y
System.out.println("#3: x = " + x + ", y = " + y);
}
public static void main(String[] args) {
int a = 19;
int b = 37;
System.out.println("#1: a = " + a + ", b = " + b);
PassByConstantValueTest.test(a, b);
System.out.println("#4: a = " + a + ", b = " + b);
}
}
/*
#1: a = 19, b = 37
#2: x = 19, y = 37
#3: x = 19, y = 223
#4: a = 19, b = 37
*/

/* An Example of a Pass by Reference Value

*/

// PassByReferenceValueTest.java
public class PassByReferenceValueTest {
public static void main(String[] args) {
// Create a Car object and assign its reference to myCar
Car myCar = new Car();
// Change model, year and price of Car object using myCar
myCar.model = "Civic LX";
myCar.year = 1999;
myCar.price = 16000.0;
System.out.println("#1: model = " + myCar.model +
1

Parameter Passing Mechanisms and this Keyword in Java

", year = "


+ myCar.year +
", price = "
+ myCar.price);
PassByReferenceValueTest.test(myCar);
System.out.println("#4: model = " + myCar.model +
", year = "
+ myCar.year +
", price = "
+ myCar.price);
}
public static void test(Car xyCar) {
System.out.println("#2: model = " + xyCar.model +
", year = "
+ xyCar.year +
", price = "
+ xyCar.price);
// Let us make xyCar refer to a new Car object
xyCar = new Car();
System.out.println("#3: model = " + xyCar.model +
", year = "
+ xyCar.year +
", price = "
+ xyCar.price);
}
}

/* Car Class with Three Public Instance Variables

*/

// Car.java
public class Car {
public String model = "Unknown";
public int year
= 2000;
public double price = 0.0;
}
/*
#1: model = Civic LX, year = 1999, price = 16000.0
#2: model = Civic LX, year = 1999, price = 16000.0
#3: model = Unknown, year = 2000, price = 0.0
#4: model = Civic LX, year = 1999, price = 16000.0
*/

/* Another Example of Pass by Reference Value Parameter Passing in


Java */
// PassByReferenceValueTest2.java
public class PassByReferenceValueTest2 {
public static void changeString(String s2) {
System.out.println("#2: s2 = " + s2);
s2 = s2 + " there";
System.out.println("#3: s2 = " + s2);
}
public static void main(String[] args) {
String s1 = "hi";
System.out.println("#1: s1 = " + s1);
PassByReferenceValueTest2.changeString(s1);
System.out.println("#4: s1 = " + s1);
}
}
/*
#1: s1 = hi
#2: s2 = hi
#3: s2 = hi there
#4: s1 = hi
*/

/* An Example of Using the Simple Name of an Instance Variable in


an Instance Method
*/
// ThisTest4.java
public class ThisTest4 {
int num = 1982; // An instance variable
void printNum() {
System.out.println("Instance variable num: " + num);
}
public static void main(String[] args) {
2

Parameter Passing Mechanisms and this Keyword in Java

ThisTest4 tt4 = new ThisTest4();


tt4.printNum();
}
}
/*
Instance variable num: 1982
*/

/* Variables Name Hiding - Lets modify the printNum() method of


the ThisTest4 class so it accepts an int parameter. Lets name the
parameter num.
*/
// ThisTest5.java
public class ThisTest5 {
int num = 1982; // An instance variable
void printNum(int num) {
System.out.println("Parameter num: " + num);
System.out.println("Instance variable num: " + num);
}
public static void main(String[] args) {
ThisTest5 tt5 = new ThisTest5();
tt5.printNum(1969);
}
}
/*
Parameter num: 1969
Instance variable num: 1969
*/

/* Using the this Keyword to Refer to an Instance Variable Whose


Name Is Hidden by a Local Variable */
// ThisTest6.java
package com.jdojo.cls;
public class ThisTest6 {
int num = 1982; // An instance variable
void printNum(int num) {
System.out.println("Parameter num: " + num);
System.out.println("Instance variable num: " + this.num);
}
public static void main(String[] args) {
ThisTest6 tt6 = new ThisTest6();
tt6.printNum(1969);
}
}
/*
Parameter num: 1969
Instance variable num: 1982
*/

/* Passing an Array as a Method Parameter

*/

// Swap.java
public class Swap {
public static void main(String[] args) {
int[] num = {17, 80};
System.out.println("Before swap");
System.out.println("#1: " + num[0]);
System.out.println("#2: " + num[1]);
// Call the swpa() method passing the num array
swap(num);
System.out.println("After swap");
System.out.println("#1: " + num[0]);
System.out.println("#2: " + num[1]);
}
// The swap() method accepts an int array as argument and swaps the values
// if array contains two values.
public static void swap (int[] source) {
3

Parameter Passing Mechanisms and this Keyword in Java

if (source != null && source.length == 2) {


// Swap the first and the second elements
int temp = source[0];
source[0] = source[1];
source[1] = temp;
}
}
}
/*
Before swap
#1: 17
#2: 80
After swap
#1: 80
#2: 17
*/

/* Modifying an Array Parameter Inside a Method */


// ModifyArrayParam.java
import java.util.Arrays;
public class ModifyArrayParam {
public static void main(String[] args) {
int[] origNum = {101, 307, 78};
System.out.println("Before method call:" + Arrays.toString(origNum));
// Pass the array to the method
tryArrayChange(origNum);
System.out.println("After method call:" + Arrays.toString(origNum));
}
public static void tryArrayChange(int[] num) {
System.out.println("Inside method-1:" + Arrays.toString(num));
// Create and store a new int array in num
num = new int[]{110, 20, 15, 5, 80};
Arrays.sort(num);
System.out.println("Inside method-2:" + Arrays.toString(num));
}
}
/*
Before method call:[101, 307, 78]
Inside method-1:[101, 307, 78]
Inside method-2:[5, 15, 20, 80, 110]
After method call:[101, 307, 78]
*/

/* Modifying Elements of an Array Parameter Inside a Method */


// ModifyArrayElements.java
import java.util.Arrays;
public class ModifyArrayElements {
public static void main(String[] args) {
int[] origNum = {10, 89, 7};
String[] origNames = {"Mike", "John"};
System.out.println("Before method call, origNum:" +
Arrays.toString(origNum));
System.out.println("Before method call, origNames:" +
Arrays.toString(origNames));
// Call methods passing the arrays
tryElementChange(origNum);
tryElementChange(origNames);
System.out.println("After method call, origNum:" +
Arrays.toString(origNum));
System.out.println("After method call, origNames:" +
Arrays.toString(origNames));
}
public static void tryElementChange(int[] num) {
// If array has at least one element, store 1116 in its first element
if (num != null && num.length > 0) {
4

Parameter Passing Mechanisms and this Keyword in Java

num[0] = 1116;
}
}
public static void tryElementChange(String[] names) {
// If array has at least one element, store "Twinkle" in its first element
if (names != null && names.length > 0) {
names[0] = "Twinkle";
}
}
}
/*
Before method call, origNum:[10, 89, 7]
Before method call, origNames:[Mike, John]
After method call, origNum:[1116, 89, 7]
After method call, origNames:[Twinkle, John]
*/

/* changing the state of the object referred to by the elements of


the array. */
// An Item Class - Item.java
public class Item {
private double price;
private String name;
public Item (String name, double initialPrice) {
this.name = name;
this.price = initialPrice;
}
public double getPrice() {
return this.price;
}
public void setPrice(double newPrice ) {
this.price = newPrice;
}
public String toString() {
return "[" + this.name + ", " + this.price + "]";
}
}

/* Modifying the States of Array Elements of an Array Parameter


Inside a Method */
// ModifyArrayElementState.java
public class ModifyArrayElementState {
public static void main(String[] args) {
Item[] myItems = {new Item("Pen", 25.11), new Item("Pencil", 0.10)};
System.out.println("Before method call #1:" + myItems[0]);
System.out.println("Before method call #2:" + myItems[1]);
// Call the method passing the array of Item
tryStateChange(myItems);
System.out.println("After method call #1:" + myItems[0]);
System.out.println("After method call #2:" + myItems[1]);
}
public static void tryStateChange(Item[] allItems) {
if (allItems != null && allItems.length > 0) {
// Change the price of first item to 10.38
allItems[0].setPrice(10.38);
}
}
}
/*
Before method call #1:[Pen, 25.11]
Before method call #2:[Pencil, 0.1]
After method call #1:[Pen, 10.38]
After method call #2:[Pencil, 0.1]
*/
5

Parameter Passing Mechanisms and this Keyword in Java

/* A SmartDog Class That Declares Two Constructors to Initialize


Instance Variables Differently
*/
// SmartDog.java
public class SmartDog {
private String name;
private double price;
public SmartDog() {
// Initialize the name to Unknown and the price to 0.0
this.name = "Unknown";
this.price = 0.0;
System.out.println("Using SmartDog() constructor");
}
public SmartDog(String name, double price) {
// Initialize name and price instance variables
// with the name and price parameters
this.name = name;
this.price = price;
System.out.println("Using SmartDog(String, double) constructor");
}
public void bark() {
System.out.println(name + " is barking...");
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void printDetails(){
System.out.print("Name: " + this.name );
if (price > 0.0) {
System.out.println(", price: " + this.price );
}
else {
System.out.println(", price: Free" );
}
}
}

/* A Test Class to Demonstrate the Use of the SmartDog Class

*/

// SmartDogTest.java
public class SmartDogTest {
public static void main(String[] args) {
// Create two SmartDog objects
SmartDog sd1 = new SmartDog();
SmartDog sd2 = new SmartDog("Nova", 219.2);
// Print details about the two dogs
sd1.printDetails();
sd2.printDetails();
// Make them bark
sd1.bark();
sd2.bark();
// Change the name and price of Unknown dog
sd1.setName("Opal");
sd1.setPrice(321.80);
// Print details again
sd1.printDetails();
sd2.printDetails();
6

Parameter Passing Mechanisms and this Keyword in Java

// Make them bark one more time


sd1.bark();
sd2.bark();
}
}
/*
Using SmartDog() constructor
Using SmartDog(String, double) constructor
Name: Unknown, price: Free
Name: Nova, price: 219.2
Unknown is barking...
Nova is barking...
Name: Opal, price: 321.8
Name: Nova, price: 219.2
Opal is barking...
Nova is barking...
*/

/* An Example of Using a static Initializer in a Class

*/

/* An instance initializer is executed once per object whereas a static initializer


is executed only once for a class when the class definition is loaded into JVM. */
// StaticInitializer.java
public class StaticInitializer {
private static int num;
// A static initializer. Note the use of the keyword static below.
static {
num = 1245;
System.out.println("Inside static initializer.");
}
// An instance initializer
{
System.out.println("Inside instance initializer.");
}
// Constructor
public StaticInitializer() {
System.out.println("Inside constructor.");
}
public static void main(String[] args) {
System.out.println("Inside main() #1. num: " + num);
// Declare a reference variable of the class
StaticInitializer si;
System.out.println("Inside main() #2. num: " + num);
// Create an object
new StaticInitializer();
System.out.println("Inside main() #3. num: " + num);
// Create another object
new StaticInitializer();
}
}
/*
Inside static initializer.
Inside main() #1. num: 1245
Inside main() #2. num: 1245
Inside instance initializer.
Inside constructor.
Inside main() #3. num: 1245
Inside instance initializer.
Inside constructor.
*/

You might also like