Manual



PURPOSE

THIS LAB HAS THREE PRE-WRITTEN PROGRAMS THAT YOU WILL RUN TO REINFORCE THE CONCEPTS OF

6.1 Access modifiers, static and the scope of variables in ScopeTest.java

6.2 Equality of primitives and equality of objects in Equals.java

6.3 Passing variable arguments to methods in PassingValues.java

In addition, you will practice drawing state of memory diagrams.

To prepare

▪ READ WU: CHAPTER 4

▪ Read through this laboratory session

▪ Using your memory device, create a directory called lab6 and copy the three files ScopeTest.java, Equals.java, PassingValues.java from .

To Complete

▪ THIS IS AN INDIVIDUAL LAB. YOU MAY ASK THE LAB TUTOR FOR HELP AND YOU MAY CONSULT WITH YOUR NEIGHBOR IF YOU ARE HAVING DIFFICULTIES.

▪ When you have completed the lab, your grade for the lab will be determined by your presence in the lab.

6.1 Scope of variables

Data Members or Data Fields

1. Data members are declared inside the class and outside of any method.

2. Data members are constants if they are modified by final, and variables, otherwise.

3. If a data member is modified by static, it belongs to the class. There is only one version of a class data member and it is shared by all objects of this type.

4. If a data member is not modified by static, it is an instance data member. Each object of this type has its own version of an instance data member.

5. Data members are modified by access modifiers. So far we have used the public and private access modifiers. Additional access modifiers are protected and to use no modifier. These modifiers determine which outside classes have access to the data members. A complete explanation of this topic will be given at the end of this course or the beginning of the next course.

6. Instance methods have access to all to both class or instance data fields. Class methods, those that are modified by static, may only access class data members. This makes sense, since class methods can be invoked on the class, whereas instance methods may only be invoked on an object.

Local Variables

1. Local variables are declared inside methods and include a method's formal parameters.

2. A formal parameter is known throughout the body of the method.

3. A local variable declared inside the body of a method is known from the point at which it is declared to the end of the block in which it is declared.

4. Local variables are never modified by the access modifiers since they may only be accessed in the method. They also are never modified by static.

Program: Open the program ScopeTest.java.

A class defines a data type. In Lab 05, once the Rectangle class was defined, variables of type Rectangle could be declared. The code below defines a data type called Scope. This is used for illustration purposes only, the actual purpose of this class is immaterial. Read the code for understanding and then answer the questions that follow.

class Scope

{

private static int one = 1;

private int two;

public int three;

public static final int FOUR = 4;

public Scope(int w, int x)

{

//++ is the auto-increment operator and adds one onto the value

one++;

two = w;

three = x;

}

public void change(int x)

{

int y = one + x;

two = one * y;

three = three * FOUR;

}

public String toString()

{

return (" one = " + one + " two = " + two + " three = " + three);

}

}

There are six variables or constants defined in the class Scope and each of these may either be instance, class or local data. Classify each, there are six possibilities.

one ____________________________________________________________________________________________

two ____________________________________________________________________________________________

three ____________________________________________________________________________________________

FOUR ____________________________________________________________________________________________

w ________________________________________________________________________________________________

x ________________________________________________________________________________________________

y ________________________________________________________________________________________________

To use the class Scope, there is a driver class defined in the file ScopeTest.java, which is called ScopeTest. You may put more than one class definition in a file. Compiling the file will result in more than one .class file being created. Since Scope is only a demonstration class, this is what I have chosen to do. Some of the statements in the main method have been commented out and should remain so when you compile the program. Later, we will uncomment some of these statements. For now we have

class ScopeTest

{

public static void main(String[] args)

{

Scope a = new Scope(3, 5);

System.out.println("1. a: " + a);

a.change(2);

System.out.println("2. a: " + a);

}

}

Step 1: Predict the output of the code.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Compile the file ScopeTest.java and run the application ScopeTest. Compare the results to your prediction, making corrections where needed. Be sure that you understand the concepts.

Step 2: After each statement below, state whether the code will compile or will not compile. If it will not compile, explain why. For each statement that compiles, comment on whether or not it violates the concept of encapsulation. If you add any of these statements to the application to check your answers, be sure to remove them before proceeding. Check your answers with someone else in class.

System.out.println(a.two); _______________________________________________________

__________________________________________________________________________________

System.out.println(Scope.three);__________________________________________________

__________________________________________________________________________________

System.out.println(a.FOUR); ______________________________________________________

__________________________________________________________________________________

Scope.FOUR = 5; __________________________________________________________________

__________________________________________________________________________________

a.three = 3; _____________________________________________________________________

__________________________________________________________________________________

Step 3: In the class Scope and at the beginning of the method public void change(int x) add the statements

int x = 10;

w = 5;

Compile the code and record the essence of the compiler error messages. Explain

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Essentially, two local variables in a method can not have the same name. Can two local variables in different methods have the same name? Substantiate your answer using the code in the class Scope.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Step 4: Now, eliminate the two statements added in Step 3. In the constructor in the class Scope, modify the statement

two = w;

to

int two = w;

Compile the file and run the application. Record what is printed?

_____________________________________________________________________________________________

_____________________________________________________________________________________________

The above is a common error made by new programmers. Java allows a local variable to have the same name as a data member. Thus, the statement int two = w; declares a local variable, two, with the same name as a data member. Therefore, statement assigns the value w to the local variable two, not to the data member two. Any data member that is not assigned a value in the constructor is assigned the equivalent of zero. The equivalent of zero is 0 or 0.0 if the data type is a primitive integer, floating-point number or character, is false if the data type is boolean and is null if the data type is a class type.

Inside of a method, is it possible to distinguish between a data member and a local variable with the same name. The answer is YES. The Java reserved this refers to the current object on which a method is invoked. Inside of a method, the word this may be dotted with the name of a data member or method member to refer to the current object's data member or invoke the method on the current method. Rewrite the constructor in Scope as shown below.

public Scope(int two, int three)

{

one++;

this.two = two;

this.three = three;

}

Step 5: Currently, a state of memory diagram for the application is:

Uncomment the next three statements in the application class ScopeTest.java and modify the state of memory diagram to show the effect of this added code.

Scope b = new Scope(7, 8);

System.out.println("\n3. a: " + a);

System.out.println("4. b: " + b);

Predict the output of the two print statements.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Compile the file ScopeTest.java and run the application ScopeTest. Compare the results to your prediction, making corrections where needed. Be sure that you understand the concepts.

Step 6: Uncomment the last four lines in the application ScopeTest.java. Redraw the state of memory diagram showing the result of these four lines.

a = b;

a.change(2);

System.out.println("\n5. a: " + a);

System.out.println("6. b: " + b);

Predict the output of the two new print statements.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Compile the file ScopeTest.java and run the application ScopeTest. Compare the results to your prediction, making corrections where needed. Be sure that you understand the concepts. Discuss these results with your neighbor. THIS IS IMPORTANT.

6.2 Checking for equality

TO CHECK FOR THE EQUALITY OF TWO VALUES, THE RELATIONAL OPERATOR == IS USED. THEREFORE, IF

int x = 5;

then the expression x == 5 has a value of true

and the expression x == 6 has a value of false.

Program: Open the file Equals.java

class Equals

{

public static void main(String[] args)

{

int x = 5, y = 5, z = 6;

System.out.println("x is " + x + " y is " + y + " z is " + z);

System.out.println("x == y is " + (x == y));

System.out.println("x == z is " + (x == z));

String r = new String("Help");

String s = new String("Help");

String t = new String("HELP");

System.out.println("\nr is " + r + " s is " + s + " t is " + t);

System.out.println("r == s is " + (r == s));

System.out.println("r == t is " + (r == t));

}

}

Step 1: Compile and run the program. Record the results.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

All of the primitive types are stored by value. That is, the value assigned to the variable is stored in the bytes that are reserved when the variable is declared.

All objects are stored by reference. That is , the address of the object assigned to the variable is stored in the bytes that are reserved when the variable is declared.

A memory diagram for the code above is

Use this diagram to explain why r == s, which compares the values stored in r and s, is false.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Step 2: To compare two objects for equality, the object must have a method called equals. Add these statements to the main method.

System.out.println(" r.equals(s) is " + r.equals(s));

System.out.println(" r.equals(t) is " + r.equals(t));

Compile and run the program. Record what is printed by this new line of code.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Where is the equals method defined? The method

public boolean equals(Object obj)

is defined in the String class. Notice that any object may be passed to the method. Obviously, if obj is not a String, false is returned. If obj is a String that is identical to this String, true is returned. Otherwise, false is returned.

Step 3: The String class has another method that compares this String to obj ignoring the case of the letters.

public boolean equalsIgnoreCase(Object obj)

To the main method, add two statements that print the values returned when r is compared to s and t using the equals method and the equalsIgnoreCase method. Record the lines you added.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Compile and run the program. Record what is printed by the two new statements.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

6.3 Passing variables to methods

IN JAVA, WE SAY VARIABLES ARE PASSED TO METHODS BY VALUE. THAT IS, ALL VARIABLES ARE PASSED TO METHODS BY COPYING THE VALUE STORED IN THE ARGUMENT TO THE PARAMETER.

If the variable's type is a primitive, the value passed is the primitive value. If the variable's type is a class type, the value stored in the variable is a reference. Therefore, to make this important distinction, we rephrase "Variables are passed by value." as "Primitives are passed by value and objects are passed by reference."

Program: Open the file PassingValues.java

This file contains two classes: Number, a utility class and PassingValues, the driver class.

Step 1: Read the class Number for understanding. Draw a picture of a Number object

class Number

{

private int value;

public Number(int v)

{

value = v;

}

public void setValue(int v)

{

value = v;

}

public String toString()

{

return "" + value;

}

}

Now follow this partial code that uses a Number object. Draw a state of memory diagram for this partial code.

Number num = new Number(6);

System.out.println(num);

num.setValue(15);

System.out.println(num);

What is printed by this partial code?

_____________________________________________________________________________________________

Step 2: Now read the actual program, which is stored in the PassingValues class. The program defines two methods

public static void main(String[] args

and

public static void makeChanges(int n, Number num )

When the program is run, it starts with the main method. Inside the class method main the second class method makeChanges is called in the statement

makeChanges(n, num);

class PassingValues

{

public static void main(String[] args)

{

int n = 5;

Number num = new Number(10);

System.out.println(

"In main before change: n is " + n + " num is " + num);

makeChanges(n, num);

System.out.println(

"\nIn main after change : n is " + n + " num is " + num);

}

public static void makeChanges(int n, Number num )

{

System.out.println(

"\nIn makeChanges before: n is " + n + " num is " + num);

n = n + 2;

num.setValue(12);

System.out.println(

"In makeChanges after : n is " + n + " num is " + num);

}

}

Predict the output by completing the state of memory diagram. Note that the method main has two local variables n and num. makeChanges has two parameters, which are local variables, also named n and num. When the main method calls makeChanges, the execution of main is interrupted and makeChanges is executed. When the execution of makeChanges is completed, the execution of main continues.

main makeChanges

n n

num num

In main before change: n is ________ num is _________

In makeChanges before: n is ________ num is _________

In makeChanges after : n is ________ num is _________

In main after change : n is ________ num is _________

Now, compile and run the program. Check your predicted answers. If you were not correct, discuss this program with your neighbor. Be sure that you understand what is occurring. Also, be sure that you can correctly draw the state of memory diagram.

Step 3: Will the results change if the parameters in the makeChanges method are changed? Change the names of the parameters in the method makeChanges to int a and Number b.

public static void makeChanges(int a, Number b )

{

System.out.println(

"\nIn makeChanges before: a is " + a + " b is " + b);

a = a + 2;

b.setValue(12);

System.out.println(

"In makeChanges after : a is " + a + " b is " + b);

}

Compile and run the program. Record the results

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

What relationship do the parameter names have to the argument names?

_____________________________________________________________________________________________

_____________________________________________________________________________________________

When a Java program is executed, or run, the Java Virtual Machine invokes the main method on the name of the driver class. This is why main must be modified by static. A static method only has access to the class's static data and static methods, i.e. a static method does not have access to instance data or instance methods. This is why the makeChanges method must also be static.

Step 4: Change the header of the makeChanges method by removing the static modifier.

public void makeChanges(int a, Number b )

Compile the modified code. Record the compiler error message.

_____________________________________________________________________________________________

_____________________________________________________________________________________________

Step 5: Remove the previous error by replacing the static modifier in the header of makeChanges.

Since makeChanges is a class method it should be invoked on the name of the class in which it is defined.

In the main method, replace the statement

makeChanges(n, num);

with the statement

PassingValues.makeChanges(n, num);

Compile and run the program. Are there any differences in the way the program is run?

_____________________________________________________________________________________________

_____________________________________________________________________________________________

All methods must be invoked on the name of a class or on the name of an object. There are no exceptions. When a static method is called from a static method without naming the class, it is implied that the method being called is invoked on the same class as the calling method. Therefore, since the JVM executes

PassingValues.main(null);

in main the statement

changeValues(n, num);

implicitly calls a static method in the PassingValues class. Whereas, the statement

PassingValues.changeValues(n, Num)

explicitly calls the method on the name of its class. Both statements are correct.

Post Lab Exercise

1. WHAT IS PRINTED BY THE PROGRAM LAB6A

| class Number { |class Lab6A |

|int value; |{ |

|public static int count = 0; |public static void main(String[] args) |

| |{ |

|public Number(int v) { |Number a = new Number(5); |

|count++; |Number b = new Number(7); |

|value = v; |System.out.println(a + " " + b); |

|} |System.out.println(a == b); |

| |System.out.println(a.equals(b)); |

|public boolean equals(Number other){ | |

| |a = b; |

|return value == other.value; |b.setValue(9); |

|} |System.out.println(a + " " + b); |

| |System.out.println(a == b); |

|public String toString() { |System.out.println(a.equals(b)); |

| | |

|return "" + value; |a = new Number(4); |

|} |b = new Number(4); |

| |System.out.println(a + " " + b); |

|public void add(Number other){ |System.out.println(a == b); |

| |System.out.println(a.equals(b)); |

|value = value + other.value; | |

|} |a.add(b); |

|} |System.out.println(a + " " + b); |

| |System.out.println(Number.count); |

| |} |

| |} |

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

"HELP"

"Help"

"Help"

6

5

5

5 20

3 12

a

4

1 2

Scope.one

Scope.FOUR

Scope object

Scope

two

three

x y z r s t

L A B

6

Check your answers with someone else in class, or with the lab tutor. If you do not agree, correct your answer and be sure that you

understand the concept.

Fill in this drawing to agree with you answers to the above.

Draw a diagram of the Scope class and a Scope object.

The Scope class should store the shared class data members.

The Scope object should store the instance data members that

are unique to each Scope object

The local variables in any method do not belong to the class or the object.

Scope class

Object Oriented Programming in Java

Reinforcing the Concepts of

Modifiers, Scope, Equality and References

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download