public class Test10
{
public static void main( String[] args )
{
Thing2 first = new Thing2( 1 );
Thing2 second = new Thing2( 2 );
Thing2 temp = second;
second = first;
first = temp;
System.out.println( first.toString() );
System.out.println( second.toString() );
Thing2 third = new Thing2( 3 );
Thing2 fourth = new Thing2( 4 );
third.swap1( fourth );
System.out.println( third.toString() );
System.out.println( fourth.toString() );
second.setCount( fourth.getCount() );
third = first;
System.out.println( third == first );
System.out.println( fourth == second );
System.out.println( first.toString().equals( third.toString() ) );
System.out.println( second.toString().equals( fourth.toString() ) );
System.out.println( first.toString() );
System.out.println( second.toString() );
System.out.println( third.toString() );
System.out.println( fourth.toString() );
first = new Thing2( 1 );
second = new Thing2( 2 );
first.swap2( second );
System.out.println( first.toString() );
System.out.println( second.toString() );
}
}
class Thing2
{
private int count;
public Thing2( int count )
{
this.count = count;
}
public int getCount()
{
return this.count;
}
public void setCount( int count )
{
this.count = count;
}
public String toString()
{
String s = " ";
switch( this.count )
{
case 1:
s = s + "first ";
case 2:
s = s + "mid ";
break;
case 3:
s = s + "last ";
break;
default:
s = s + "rest ";
break;
}
return s;
}
public void swap1( Thing2 t2 )
{
int temp;
temp = this.getCount();
this.setCount( t2.getCount() );
t2.setCount( temp );
}
public void swap2( Thing2 t2 )
{
Thing2 temp;
Thing2 t1 = this;
temp = t1;
t1 = t2;
t2 = temp;
}
}
Given the following definition of class Thing2, what is the output of
the Java application Test10?
Hey guys, this is for one of my classes. There are two classes (listed above), Thing2 and Test10. This is the output, but I don’t understand how to get to the output (i.e. what points to what and what’s the order everything gets resolved in?). Thanks!
mid
first mid
rest
last
true
false
true
true
mid
last
mid
last
first mid
mid
One trick is that
case 1in your switch statement does not have a break statement, so the code continue to thecase 2instruction and creates the string “first mid” instead of “first” for Thing(1)it might help to add comments to your print statements like this
One you do that, add more print statements.
Think of each variable as a big arrow.
The statement
a = new Thing(2)makes a Thing with the word “mid” and points theaarrow at it.The statement
a = btake whatever thebarrow was looking at and points theaarrow at the same thing.