Parameter Passing Mechanisms and This in Java
Parameter Passing Mechanisms and This in Java
a
x
x
a
=
=
=
=
19,
19,
37,
19,
b
y
y
b
=
=
=
=
37
37
19
37
*/
// 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
*/
*/
// 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
*/
// 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
*/
*/
// 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
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]
*/
*/
// 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
*/