You are on page 1of 61

// Java2701.java // This demonstrates how <String> class objects are printed.

public class Java2701 { public static void main (String args[]) { System.out.println("\nJava2701.java\n"); String stringVar = "Tango"; System.out.println(stringVar); System.out.println(); System.out.println("Literal String"); System.out.println(); } }

// Java2702.java // This demonstrates how <int>, <double>, <char> and <boolean> // variables are printed. public class Java2702 { public static void main (String args[]) { System.out.println("\nJava2702.java\n"); int intVar = 100; double dblVar = 3.14159; char chrVar = 'A'; boolean blnVar = true; System.out.println(intVar); System.out.println(dblVar); System.out.println(chrVar); System.out.println(blnVar); System.out.println(); } }

// Java2703.java // This program demonstrates how Java <int> and <double> arrays are // displayed when only the object identifier is printed. public class Java2703 { public static void main (String args[]) { System.out.println("\nJava2703java\n"); int intList[] = {11,22,33,44,55,66,77,88,99}; System.out.println("intList: " + intList); System.out.println(); double dblList[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; System.out.println("dblList: " + dblList); System.out.println(); String strList[] = {"Tom","Joe","Sue","Meg"}; System.out.println("strList: " + strList); System.out.println(); } }

How Arrays Work


All an array object stores is the memory location of the first element in the array. intList @720eeb dblList @3179c3 strList @310d42

720eeb 11

3179c3 1.1

310d42 Tom

// Java2704.java // In this program the user-defined <Student> class uses the <toString> method inherited from the // <Object> class. The <Object> class <toString> method returns an actual string representation of // the object value, which is a memory address. public class Java2704 { public static void main (String args[]) { System.out.println("\nJava2704.java\n"); Student student1 = new Student("Tom",21,3.85); Student student2 = new Student("Joe",17,3.65); Student student3 = new Student("Sue",18,2.85); Student student4 = new Student("Meg",19,3.90); System.out.println("student1: " + student1); System.out.println("student2: " + student2); System.out.println("student3: " + student3); System.out.println("student4: " + student4); System.out.println(); } } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } }

The Original toString Method


print and println request display instructions from the toString method.
Method toString is defined by the Object class. The Object class is the superclass for ALL Java classes.

This means that every class has access to the toString method.
The toString method, as defined by the Object class, returns the actual string representation values of all the primitive types like int, double, char and boolean.

toString returns the class name followed by the memory


reference of any variable object.

The Object Class


The Big Mamma Class Up in the Sky

toString equals

// Java2705.java // This program demonstrates <toString> behaves differently for the <ArrayList> // class. Note that "referenced" values are displayed, not the references. import java.util.ArrayList; public class Java2705 { public static void main (String args[]) { System.out.println("\nJaba2705.java\n"); ArrayList<String> names = new ArrayList<String>(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names: " + names); System.out.println(); } }

// Java2706.java.java // The <toString> method of an ArrayList object displays the contents of the <ArrayList> // object, but the non-Java class <Student> objects display memory addresses. import java.util.ArrayList; public class Java2706 { public static void main (String args[]) { System.out.println("\nJava2706.java\n"); ArrayList<Student> students = new ArrayList<Student>(); students.add(new Student("Tom",21,3.85)); students.add(new Student("Joe",17,3.65)); students.add(new Student("Sue",18,2.85)); students.add(new Student("Meg",19,3.90)); System.out.println("students: " + students); System.out.println(); } }

class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } }

// Java2707.java. // This program examples shows that <toString> manages to handle objects of objects very nicely. // In this case you see a display of an <ArrayList> object or <ArrayList> objects. // Observe how generics are handled with an <ArrayList> object of <ArrayList> objects.import java.util.ArrayList; public class Java2707 { public static void main (String args[]) { System.out.println("\nJava2707.java\n"); ArrayList<String> cats = new ArrayList<String>(); cats.add("Lions"); cats.add("Tigers");

ArrayList<String> swimmers = new ArrayList<String>(); swimmers.add("Whales"); swimmers.add("Dolphins");


ArrayList<String> primates = new ArrayList<String>(); primates.add("Gorillas"); primates.add("Chimpanzees"); ArrayList<ArrayList<String>> mammals = new ArrayList<ArrayList<String>>(); mammals.add(cats); mammals.add(swimmers); mammals.add(primates); System.out.println(mammals); System.out.println(); }

ArrayList and toString


ArrayList objects display the actual individual array elements and not the memory reference of the object. The output format looks like [Tom, Sue, Joe, Kathy].

This means that the toString method is redefined for the ArrayList class or some superclass of ArrayList.

// Java2708.java // This program demonstrates defining a <toString> method // in the <Student> class so that it displays the name field of a <Student> object. import java.util.ArrayList; public class Java2708 { public static void main (String args[]) { System.out.println("\nJava2708.java\n"); Student student1 = new Student("Kathy Alexander",21,3.75); Student student2 = new Student("Peter VanVliet",18,2.265); System.out.println(student1.toString()); System.out.println(student2.toString()); System.out.println(); } } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; }

public String toString() { return name; }


}

// Java2709.java // This program is almost identical to the previous program. This time the <toString> method is not // called by any <Student> object. Yet the result is the same because <println> uses the // string representation of <toString> for its output. import java.util.ArrayList; public class Java2709 { public static void main (String args[]) { System.out.println("\nJava2709.java\n"); Student student1 = new Student("Kathy Alexander",21,3.75); Student student2 = new Student("Peter VanVliet",18,2.265); System.out.println(student1); System.out.println(student2); System.out.println(); } } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; }

public String toString() { return name; }


}

// Java2710.java // This program demonstrates "redefining the <toString> method in the // <Student> class so that it displays every field of a <Student> object. // Note how this implementation resembles the <ArrayList> format. import java.util.ArrayList; public class Java2710 { public static void main (String args[]) { System.out.println("\nJava2710.java\n"); Student student1 = new Student("Kathy Alexander",21,3.475); Student student2 = new Student("Peter VanVliet",18,2.265); System.out.println(student1); System.out.println(student2); System.out.println(); } } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; }

public String toString() { return "[" + name + "," + age + "," + gpa + "]"; }
}

// Java2711.java // This program uses a <TimeTest> class, which displays the elapsed time // in hh:mm:ss.fractions between some event. This <toString> method // includes control structures to determine the correct format. import java.util.Scanner; import java.text.DecimalFormat; public class Java2711 { public static void main(String args[]) { System.out.println("\nJava2711.java\n"); Scanner input = new Scanner(System.in); TimeTest time = new TimeTest(); { System.out.print("Press <Enter> to start the clock ===>> "); String dummy = input.nextLine(); time.startClock(); System.out.println(); System.out.print("Press <Enter> to stop the clock ===>> "); dummy = input.nextLine(); time.stopClock(); } System.out.println(); System.out.println(time); System.out.println(); } }

class TimeTest { private long startNanos; private long endNanos; private long nanos; private long hours; private long minutes; private long seconds; private long fractions;

// tick count at the start of the test // tick count at the end of the test // elapsed number of nano seconds // elapsed hours // elapsed minutes // elapsed seconds // elapsed fractions of a second

public TimeTest() { startNanos = 0; endNanos = 0; nanos = 0; hours = 0; minutes = 0; seconds = 0; fractions = 0; }


public void startClock() { startNanos = System.nanoTime(); } public void stopClock() { endNanos = System.nanoTime(); computeTime(); }

private void computeTime() { nanos = endNanos - startNanos; hours = nanos / 3600000000000L; long leftOver = nanos % 3600000000000L; minutes = leftOver / 60000000000L; leftOver = leftOver % 60000000000L; seconds = leftOver / 1000000000L; fractions = leftOver % 1000000000L; }
public String toString() { DecimalFormat twos = new DecimalFormat("00"); DecimalFormat nines = new DecimalFormat("000000000"); String temp = twos.format(hours) + ":"; temp = temp + twos.format(minutes) + ":"; temp = temp + twos.format(seconds) + "."; temp = temp + nines.format(fractions); return temp; }}

// Java2712.java // This program repeats the <TimeTest> class with a different output // format for the <toString> method. import java.util.Scanner; public class Java2712 { public static void main(String args[]) { System.out.println("\nJava2712.java\n"); Scanner input = new Scanner(System.in); TimeTest time = new TimeTest(); { System.out.print("Press <Enter> to start the clock ===>> "); String dummy = input.nextLine(); time.startClock(); System.out.println(); System.out.print("Press <Enter> to stop the clock ===>> "); dummy = input.nextLine(); time.stopClock(); } System.out.println(); System.out.println(time); System.out.println(); } }

class TimeTest { private long startTicks; private long endTicks; private long millis; private long hours; private long minutes; private long seconds; private long fractions;

// tick count at the start of the test // tick count at the end of the test // elapsed number of ticks // elapsed hours // elapsed minutes // elapsed seconds // elapsed fractions of a second

//These 4 methods are the same as the last program public TimeTest() public void startClock() public void stopClock() private void computeTime()

public String toString() { String temp = "Hours: temp = temp + "Minutes: temp = temp + "Seconds: temp = temp + "Fractions: return temp; }
}

" " " "

+ + + +

hours + "\n"; minutes + "\n"; seconds + "\n"; fractions + "\n";

Redefining toString
Every class has indirect access to the toString method defined by the Object class.

If some output is desired with println that is different from the default toString output, you must redefine toString in the class that you are using with a method, like the one shown below.

public String toString() { String temp = "Hours: temp = temp + "Minutes: temp = temp + "Seconds: temp = temp + "Fractions: return temp; }

" " " "

+ + + +

hours + "\n"; minutes + "\n"; seconds + "\n"; fractions + "\n";

// Java2713.java // This program demonstrates how <String> objects respond to the == operator.

import java.util.Scanner;
public class Java2713 { public static void main (String args[]) { Scanner input = new Scanner(System.in); System.out.println("\nJava2713.java\n"); System.out.print("Enter string 1 ===>> "); String s1 = input.nextLine(); System.out.print("Enter string 2 ===>> "); String s2 = input.nextLine();

if (s1 == s2)
System.out.println("They are equal");
else System.out.println("They are not equal"); System.out.println(); }

Why == Does Not Work with String


Since a String is actually a class and not a primitive data type, a String object stores the memory address of the String, not the String value itself.

string1 @720eeb

== compares

string2 @3179c3

720eeb Foxtrot

equals compares

3179c3 Foxtrot

// Java2714.java // This program demonstrates how the <equals> methods properly handles // <String> objects. import java.util.Scanner; public class Java2714 { public static void main (String args[]) { Scanner input = new Scanner(System.in); System.out.println("\nJava2714.java\n"); System.out.print("Enter string 1 ===>> "); String s1 = input.nextLine(); System.out.print("Enter string 2 ===>> "); String s2 = input.nextLine();

if (s1.equals(s2))
System.out.println("They are equal");
else System.out.println("They are not equal"); System.out.println(); }

Redefining equals
The == operator compares the immediate values stored by variables. This means that == only works correctly for primitive data types. Java has an equals method, which works correctly for comparing String objects.

// Java2715.java // This program demonstrates how the <equals> method behaves with <ArrayList> objects. import java.util.ArrayList; public class Java2715 { public static void main (String args[]) { System.out.println("\nJava2715.java\n");

ArrayList<String> list1 = new ArrayList<String>(); list1.add("John"); list1.add("Greg"); ArrayList<String> list2 = new ArrayList<String>(); list2.add("John"); list2.add("Greg"); ArrayList<String> list3 = new ArrayList<String>(); list3.add("Maria"); list3.add("Heidi");

if (list1.equals(list2))
else

System.out.println("They are equal"); System.out.println("They are not equal"); System.out.println();

if (list2.equals(list3))
else

System.out.println("They are equal"); System.out.println("They are not equal"); System.out.println(); }

// Java2716.java // This demonstrates how the <equals> method handles user-defined <Student> objects. public class Java2716 class Student { { public static void main (String args[]) private String name; { private int age; System.out.println("\nJava2716.java\n"); Student student1 = new Student("Tom",21); Student student2 = new Student("Tom",21); Student student3 = new Student("Meg",20); public Student(String n, int a) { name = n; age = a; }

if (student1.equals(student2))
System.out.println("They are equal"); else System.out.println("They are not equal"); System.out.println();

if (student2.equals(student3))
else

System.out.println("They are equal"); System.out.println("They are not equal"); System.out.println(); }

// Java2717.java // This redefines the <equals> method for the <Student> class. // For this implementation equality is based on GPA. class Student public class Java2717 { public static void main (String args[]) { System.out.println("\nJava2717.java\n"); Student student1 = new Student("Tom",2.165); Student student2 = new Student("Tom",3.675); Student student3 = new Student("Meg",3.675);
{

private String name; private double gpa;


public Student(String n, double g) { name = n; gpa = g; } public boolean equals(Student source) { return gpa == source.gpa; } }

if (student1.equals(student2))
System.out.println("They are equal"); else System.out.println("They are not equal"); System.out.println();

if (student2.equals(student3))
System.out.println("They are equal"); else System.out.println("They are not equal"); System.out.println(); } }

// Java2718.java This redefines the <equals> method for the <Student> class. For this implementation equality is based on equality in every field. public class Java2718 { public static void main (String args[]) { System.out.println("\nJava2718.java\n"); Student student1 = new Student("Meg",2.165); Student student2 = new Student("Tom",3.675); Student student3 = new Student("Tom",3.675);

class Student { private String name; private double gpa; public Student(String n, double g) { name = n; gpa = g; }

public boolean equals(Student source) { return (name.equals(source.name) && gpa == source.gpa); }


}

if (student1.equals(student2))
System.out.println("They are equal"); else System.out.println("They are not equal"); System.out.println();

if (student2.equals(student3))
else

System.out.println("They are equal"); System.out.println("They are not equal"); System.out.println(); } }

The equals Method


The equals method is originally defined in the Object class. The default equals class does little besides comparing actual values in objects, which becomes a comparison of references. Many classes redefine equals, such as the String class and the ArrayList class. Redefinition of the equals method normally involves making a comparison of the values at the referenced memory location.

// Java2719.java // This program demonstrates how the <compareTo> // method work with <String> objects. public class Java2719 { public static void main (String args[]) { System.out.println("\nJava2719.java\n"); String s1 = "Aardvark"; String s2 = "Zulu"; String s3 = "Aardvark"; System.out.println(s1 + " compares to " + s2 + " : " + s1.compareTo(s2)); System.out.println(s2 + " compares to " + s1 + " : " + s2.compareTo(s1)); System.out.println(s1 + " compares to " + s3 + " : " + s1.compareTo(s3)); System.out.println(); }

// Java2720.java // The <equals> method is a member of the <Object> class, but this is not true // for the <compareTo> method. The program below will not compile with the // comments removed. public class Java2720 { public static void main (String args[]) { System.out.println("\nJava2720.java\n"); Object obj1 = new Object(); Object obj2 = new Object(); obj2 = obj1; if (obj1.equals(obj2)) System.out.println("equals"); else System.out.println("no equals");

//
// }

System.out.println(obj1.compareTo(obj2));
remove comments after first execution System.out.println();

// Java2721.java // The <compareTo> method also does not work for the <ArrayList> class, // just like the <Object> class. import java.util.ArrayList; public class Java2721 { public static void main (String args[]) { System.out.println("\nJava2721.java\n"); ArrayList<String> list1 = new ArrayList<String>(); ArrayList<String> list2 = new ArrayList<String>(); list1.add("John"); list1.add("Greg"); list2.add("Maria"); list2.add("Heidi");

System.out.println(list1.compareTo(list2)); System.out.println(list2.compareTo(list1));
System.out.println();

Where Does compareTo Come From?


compareTo is not part of the ArrayList class, just like it is not part of the Object class.
The method compareTo comes from the Comparable interface. An interface is very similar to a class with strictly abstract methods. It is not possible to use the compareTo method in the Comparable interface. It is not even possible to create an object of Comparable. It is possible to give compareTo some meaning for your class. There is no default definition for compareTo. This is not an inheritance situation and it is also not a composition situation either. This is an implementation issue. Program Java2722.java uses a Student class and it states that it implements the Comparable class.

Inheritance vs. Implementation


Inheritance of Classes
A class is a blueprint for creating an object. An inherited class (subclass) is a modified blueprint for creating an specialized object.

Inheritance vs. Implementation


Implementation of Interfaces
A interface is something abstract. It is like a general idea you have before anyone can create the blueprints.

Interfaces will be explained in detail in Chapter 31.

// Java2722.java // This program implements the <Comparable> interface only method, <compareTo>. // Note how it also redefines the <toString> method so that the <Student> object's // name is displayed, rather than a memory address. public class Java2722 { public static void main (String args[]) { System.out.println("\nJava2722.java\n"); Student st1 = new Student("Tom",21); Student st2 = new Student("Meg",21); Student st3 = new Student("Tom",20); System.out.println(st1 + " compares to " + st2 + " : " + st1.compareTo(st2)); System.out.println(st2 + " compares to " + st1 + " : " + st2.compareTo(st1)); System.out.println(st1 + " compares to " + st3 + " : " + st1.compareTo(st3));

System.out.println(); }

class Student implements Comparable


{

private String name; private int age;


public Student(String n, int a) { name = n; age = a; }

public int compareTo (Object source) { Student temp = (Student) source; return name.compareTo(temp.name); }
public String toString() { return name; }

// This is still program Java2722.java // This an attempt to make the compareTo method simpler. // This does not work. Source must be of type Object.

class Student implements Comparable


{ private String name; private int age; public Student(String n, int a) { name = n; age = a; }

You might be wondering what point the is if it requires the method to be more complicated.

comparable interface

public int compareTo (Student source) { return name.compareTo(source.name); The purpose is that } when you see a class
public String toString() { return name; }

that implements a known interface, you know what methods it will have, and how they are expected to work.

Comparable and compareTo


Comparable is an interface with a single abstract method, called compareTo.
Access to the compareTo method is only possible from a class, which has implemented the compareTo method.
Some classes, like the String class have already implemented the compareTo method. Implementing is not redefining an inherited method.

You are defining the method for the first time.

Java Parameter Passing


ALL parameters, in Java, are passed by value.
This means that a copy of the actual parameter is assigned to the formal parameter.
This is true whether the actual parameter is a simple data type or an object.

// Java2723.java // This program demonstrates that the <swap> method does not alter // the parameter values passed in the <main> method. public class Java2723 { public static void main (String args[]) { System.out.println("\nJava2723.java\n"); int num1 = 100; int num2 = 200; System.out.println("num1: " + num1); System.out.println("num2: " + num2); public static void swap(int x, int y) { System.out.println(); System.out.println("x: " + x); System.out.println("y: " + y); int temp = x; x = y; y = temp; System.out.println(); System.out.println("x: " + x); System.out.println("y: " + y); System.out.println(); } }

swap(num1,num2);
System.out.println("num1: " + num1); System.out.println("num2: " + num2); System.out.println();

// Java2724.java // This program demonstrates that the <swap> method does not alter // the <String> values passed in the <main> method.
public class Java2724 { public static void main (String args[]) { System.out.println("\nJava2724.java\n"); String name1 = "Tom"; String name2 = "Sue"; System.out.println("name1: " + name1); System.out.println("name2: " + name2); public static void swap(String n1, String n2) { System.out.println(); System.out.println("n1: " + n1); System.out.println("n2: " + n2); String temp = n1; n1 = n2; n2 = temp; System.out.println(); System.out.println("n1: " + n1); System.out.println("n2: " + n2); System.out.println(); } } System.out.println();

swap(name1,name2);
System.out.println("name1: " + name1); System.out.println("name2: " + name2);

// Java2725.java // This program demonstrates that the <swap> method does not alter // the <Student> values passed in the <main> method.
public class Java2725 { public static void main (String args[]) { System.out.println("\nJava2725.java\n"); Student st1 = new Student("Sue",21,3.5); Student st2 = new Student("Tom",20,2.2); System.out.println("st1: " + st1); System.out.println("st2: " + st2); } public static void swap(Student s1, Student s2) { System.out.println(); System.out.println("s1: " + s1); System.out.println("s2: " + s2); Student temp = s1; s1 = s2; s2 = temp; System.out.println(); System.out.println("s1: " + s1); System.out.println("s2: " + s2); System.out.println(); } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } public String toString() { return name; } }

swap(st1,st2);
System.out.println("st1: " + st1); System.out.println("st2: " + st2); System.out.println(); }

// Java2726.java // This program is the same as Java2725 with the <toString> redefinition removed from // the <Student> class, so that memory references can be observed.
public class Java2726 { public static void main (String args[]) { System.out.println("\nJava2726.java\n"); Student st1 = new Student("Sue",21,3.5); Student st2 = new Student("Tom",20,2.2); System.out.println("st1: " + st1); System.out.println("st2: " + st2); public static void swap(Student s1, Student s2) { System.out.println(); System.out.println("s1: " + s1); System.out.println("s2: " + s2); Student temp = s1; s1 = s2; s2 = temp; System.out.println(); System.out.println("s1: " + s1); System.out.println("s2: " + s2); System.out.println(); } } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } }

swap(st1,st2);
System.out.println("st1: " + st1); System.out.println("st2: " + st2); System.out.println(); }

What is going on? (Part 1)


Student st1 = new Student("Sue",21,3.5); Student st2 = new Student("Tom",20,2.2);

st1 @82ba41

st2 @923e40

82ba41 Sue, 21, 3.5

923e40 Tom, 20, 2.2

What is going on? (Part 2)


swap(st1,st2); public static void swap(Student s1, Student s2)

st1 s1 s2 st2 @82ba41 @82ba41 @923e40 @923e40

82ba41 Sue, 21, 3.5

923e40 Tom, 20, 2.2

What is going on? (Part 3)


Student temp = s1; s1 = s2; s2 = temp;

st1 s1 s2 st2 @82ba41 @923e40 @82ba41 @923e40

82ba41 Sue, 21, 3.5

923e40 Tom, 20, 2.2

What is going on? (Part 4)


System.out.println("st1: " + st1); System.out.println("st2: " + st2);

st1 @82ba41

st2 @923e40

82ba41 Sue, 21, 3.5

923e40 Tom, 20, 2.2

// Java2727.java // This program now appears to work as expected. Note that this time the object values, which are // references, are not swapped, but the content values which are referenced by the objects.
public static void main (String args[]) { System.out.println( "\nJava2727.java\n"); Student st1 = new Student("Sue",21,3.5); Student st2 = new Student("Tom",20,2.2); System.out.println( "st1: " + st1); System.out.println( "st2: " + st2); public static void swap( Student s1, Student s2) { System.out.println(); System.out.println( "s1: " + s1); System.out.println( "s2: " + s2); String sTemp = s1.getName(); s1.setName(s2.getName()); s2.setName(sTemp); int iTemp = s1.getAge(); s1.setAge(s2.getAge()); s2.setAge(iTemp); double dTemp = s1.getGpa(); s1.setGpa(s2.getGpa()); s2.setGpa(dTemp); class Student { private String name; private int age; private double gpa; public Student( String n, int a, double g) { name = n; age = a; gpa = g; } public String getName () { return name; } public int getAge () { return age; } public double getGpa () { return gpa; } public void setName (String s) { name = s; } public void setAge (int a) { age = a; } public void setGpa (double g) { gpa = g; } public String toString() { return name; } }

swap(st1,st2);
System.out.println( "st1: " + st1); System.out.println( "st2: " + st2); System.out.println(); } }

System.out.println(); System.out.println( "s1: " + s1); System.out.println( "s2: " + s2); System.out.println();
}

// Java2728.java // This program uses a <createList> method to generate random integers for an // integer array. The program executes as desired. import java.util.Random; public class Java2728 { public static void main (String args[]) { System.out.println( "\nJava2728.java\n"); int list[] = new int[100]; displayList(list); createList(list); displayList(list); System.out.println(); } public static void createList(int list[]) { Random rnd = new Random(12345); for (int k = 0; k < list.length; k++) { int rndInt = rnd.nextInt(9000) + 1000; list[k] = rndInt; } } public static void displayList(int list[]) { System.out.println(); for (int k = 0; k < list.length; k++) System.out.print(list[k] + " "); System.out.println(); } }

Making Changes with Method Calls


It is possible to call some method and make changes to information that is stored by the calling parameter variable. Just keep in mind that you cannot change the direct reference value of the calling parameter with a void method. However, you can make changes to the values that being referenced.

// Java2729.java // This program is yet another example that parameters are only passed by value. // It is not possible to pass the reference from the temp array to the list parameter. import java.util.Random; public class Java2729 { public static void main (String args[]) { System.out.println( "\nJava2729.java\n"); int list[] = new int[100]; displayList(list); public static void createList(int list[]) { Random rnd = new Random(12345); int temp[] = new int[100]; for (int k = 0; k < list.length; k++) { int rndInt = rnd.nextInt(9000) + 1000; temp[k] = rndInt; }

list = temp;

} public static void displayList(int list[]) { System.out.println(); for (int k = 0; k < list.length; k++) System.out.print(list[k] + " "); System.out.println(); } }

createList(list);
displayList(list); System.out.println();

References and Parameters

Bottom Line

void methods cannot change the


reference of the calling parameter; only the values being referenced.

return methods can change both


the values being referenced and the reference of the calling parameter.

// Java2730.java // If in fact it is desirable to change the memory reference of an object, it can be // done with a return method, as is demonstrated in this program. import java.util.Random; public class Java2730 { public static void main (String args[]) { System.out.println( "\nJava2730.java\n"); int list[] = new int[100]; displayList(list); public static int[] createList(int list[]) { Random rnd = new Random(12345); int temp[] = new int[100]; for (int k = 0; k < list.length; k++) { int rndInt = rnd.nextInt(9000) + 1000; temp[k] = rndInt; } list = temp;

return list;

} public static void displayList(int list[]) { System.out.println(); for (int k = 0; k < list.length; k++) System.out.print(list[k] + " "); System.out.println(); } }

list = createList(list);
displayList(list); System.out.println();

You might also like