Java Advanced Placement Study Guide:  Relational Operators, Increment Operator, and Control Structures

Sample question:  What is the scope of a variable that is declared in the first clause of a for loop?

Published January 21, 2002
By Richard G. Baldwin

Questions

File JavaAP006


Welcome

This is one in a miniseries of tutorial lessons designed to help you learn the essential features of Java object-oriented programming as identified by The College Board.

Purpose

The purpose of this miniseries is to help you study for, and successfully complete, the Advanced Placement Examinations designed by the College Board.

Once you understand everything in this miniseries, plus the material in the lessons that I published earlier on Java Data Structures, you should understand the Java programming features that the College Board considers essential for the first two semesters of object-oriented programming education at the university level.

Hopefully, that will help you to take and successfully complete the Advanced Placement Examinations.

Approach

These lessons provide questions, answers, and explanations designed to help you to understand the subset of Java features covered by the Java Advanced Placement Examinations (as of October, 2001).

Please see the first lesson in the miniseries entitled Java Advanced Placement Study Guide: Introduction to the Lessons, Primitive Types, for additional background information.  The lesson immediately prior to this one was entitled Java Advanced Placement Study Guide: Assignment and Arithmetic Operators.

Supplementary material

In addition to the material in these lessons, I recommend that you also study the other lessons in my extensive collection of online Java tutorials, which are designed from a more conventional textbook approach.  You will find those lessons published at Gamelan.com.  However, as of the date of this writing, Gamelan doesn't maintain a consolidated index of my Java tutorial lessons, and sometimes they are difficult to locate there.  You will find a consolidated index at Baldwin's Java Programming Tutorials.

What is Included?

Click here for a preview of the Java programming features covered by this lesson.

String Concatenation

Problem 15 in the lesson entitled Java Advanced Placement Study Guide:  Assignment and Arithmetic Operators introduced the use of String concatenation for the purpose of displaying two or more items, separated by spaces, on the same output line.  Very little was provided in the way of an explanation of String concatenation at that time. String concatenation will also be used in this and the following lessons.  However, a detailed explanation of String concatenation will be deferred until a subsequent lesson.



1.  Given:  The use of String concatenation in the argument list of the call to the println() method in the following program will cause seven items to be displayed on the screen, separated by spaces.

True or False?  The following program produces the output shown below:

false true false false true true false
 
public class Ap025{
  public static void main(
                        String args[]){
    new Worker().doRelat();
  }//end main()
}//end class definition

class Worker{
  public void doRelat(){
    int a = 1, b = 2, c = 3, d = 2;
    
    System.out.println(
                      (a == b) + " " + 
                      (b == d) + " " + 
                      (b != d) + " " + 
                      (c < a) + " " + 
                      (b <= d) + " " + 
                      (c > d) + " " + 
                      (a >= c));
  }//end doRelat()
}//end class definition

Answer and Explanation

2.  What output is produced by the following program?

public class Ap026{
  public static void main(
                        String args[]){
    new Worker().doRelat();
  }//end main()
}//end class definition

class Worker{
  public void doRelat(){
    Dummy x = new Dummy();
    Dummy y = new Dummy();    
    System.out.println(x == y);
  }//end doRelat()
}//end class definition

class Dummy{
  int x = 5;
  double y = 5.5;
  String z = "A String Object";
}//end class Dummy

Answer and Explanation

3.  What output is produced by the following program?

public class Ap027{
  public static void main(
                        String args[]){
    new Worker().doRelat();
  }//end main()
}//end class definition

class Worker{
  public void doRelat(){
    Dummy x = new Dummy();
    Dummy y = new Dummy();    
    System.out.println(x.equals(y));
  }//end doRelat()
}//end class definition

class Dummy{
  int x = 5;
  double y = 5.5;
  String z = "A String Object";
}//end class Dummy

Answer and Explanation

4.  What output is produced by the following program?

public class Ap028{
  public static void main(
                        String args[]){
    new Worker().doRelat();
  }//end main()
}//end class definition

class Worker{
  public void doRelat(){
    Dummy x = new Dummy();
    Dummy y = x;    
    System.out.println(
         (x == y) + " " + x.equals(y));
  }//end doRelat()
}//end class definition

class Dummy{
  int x = 5;
  double y = 5.5;
  String z = "A String Object";
}//end class Dummy

Answer and Explanation

5.  What output is produced by the following program?

public class Ap029{
  public static void main(
                        String args[]){
    new Worker().doRelat();
  }//end main()
}//end class definition

class Worker{
  public void doRelat(){
    Dummy x = new Dummy();
    Dummy y = new Dummy();    
    System.out.println(x > y);
  }//end doRelat()
}//end class definition

class Dummy{
  int x = 5;
  double y = 5.5;
  String z = "A String Object";
}//end class Dummy

Answer and Explanation

6.  What output is produced by the following program?

public class Ap030{
  public static void main(
                        String args[]){
    new Worker().doIncr();
  }//end main()
}//end class definition

class Worker{
  public void doIncr(){
    int w = 5, x = 5;
    double y = 8.3, z = 8.3;
    
    w++;
    x--;
    y++;
    z--;
    
    System.out.println(w + "  " +
                       x + "  " +
                       y + "  " +
                       z);
  }//end doIncr()
}//end class definition

Answer and Explanation

7.  What output is produced by the following program?

public class Ap031{
  public static void main(
                        String args[]){
    new Worker().doIf();
  }//end main()
}//end class definition

class Worker{
  public void doIf(){
    int x = 5, y = 6;
    if(x - y){
      System.out.println("Hello");
    }//end if
  }//end doIf()
}//end class definition

Answer and Explanation

8.  What output is produced by the following program?

public class Ap032{
  public static void main(
                        String args[]){
    new Worker().doIf();
  }//end main()
}//end class definition

class Worker{
  public void doIf(){
    int x = 5, y = 6;
    if(x < y){
      System.out.print("Hello ");
    }//end if
    System.out.println("World");
  }//end doIf()
}//end class definition

Answer and Explanation

9.  What output is produced by the following program?

public class Ap033{
  public static void main(
                        String args[]){
    new Worker().doIf();
  }//end main()
}//end class definition

class Worker{
  public void doIf(){
    int x = 5, y = 6;
    if(x == y){
      System.out.println(
                        "Hello World");
    }else{
      System.out.println(
                      "Goodbye World");
    }//end else
  }//end doIf()
}//end class definition

Answer and Explanation

10.  What output is produced by the following program?

public class Ap034{
  public static void main(
                        String args[]){
    new Worker().doIf();
  }//end main()
}//end class definition

class Worker{
  public void doIf(){
    int x = 2;
    if(x == 4){
      System.out.println("x = 4");
    }else if (x == 5){
      System.out.println("x = 5");
    }else if (x == 6){
      System.out.println("x = 6");
    }else{
      System.out.println("x != 4,5,6");
    }//end else
  }//end doIf()
}//end class definition

Answer and Explanation

11.  What output is produced by the following program?

public class Ap035{
  public static void main(
                        String args[]){
    new Worker().doLoop();
  }//end main()
}//end class definition

class Worker{
  public void doLoop(){
    int cnt = 0;
    while(cnt<5){
      cnt++;
      System.out.print(cnt + " ");
      cnt++;
    }//end while loop
    System.out.println("");
  }//end doLoop()
}//end class definition

Answer and Explanation

12.  What output is produced by the following program?

public class Ap036{
  public static void main(
                        String args[]){
    new Worker().doLoop();
  }//end main()
}//end class definition

class Worker{
  public void doLoop(){
    int cnt;
    for(cnt = 0; cnt < 5; cnt++){
      System.out.print(cnt + " ");
    }//end for loop
    System.out.println(cnt + " ");
  }//end doLoop()
}//end class definition

Answer and Explanation

13.  What output is produced by the following program?

public class Ap037{
  public static void main(
                        String args[]){
    new Worker().doLoop();
  }//end main()
}//end class definition

class Worker{
  public void doLoop(){
    for(int cnt = 0; cnt < 5; cnt++){
      System.out.print(cnt + " ");
    }//end for loop
    System.out.println(cnt + " ");
  }//end doLoop()
}//end class definition

Answer and Explanation

14.  What output is produced by the following program?

public class Ap037{
  public static void main(
                        String args[]){
    new Worker().doLoop();
  }//end main()
}//end class definition

class Worker{
  public double doLoop(){
    for(int cnt = 0; cnt < 5; cnt++){
      System.out.print(cnt + " ");
      if(cnt == 3){
        System.out.println(cnt);
        return cnt;
      }//end if
    }//end for loop
    //return 3.5;
  }//end doLoop()
}//end class definition

Answer and Explanation

15.  What output is produced by the following program?

public class Ap038{
  public static void main(
                        String args[]){
    new Worker().doLoop();
  }//end main()
}//end class definition

class Worker{
  public void doLoop(){
    for(int cnt = 0; cnt < 5; cnt++){
      System.out.print(cnt + " ");
      if(cnt == 3){
        System.out.println(cnt);
        return;
      }//end if
    }//end for loop
  }//end doLoop()
}//end class definition

Answer and Explanation



Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com


What is Included?

According to the subset document,

Answers and Explanations

Answer 15

C.  0 1 2 3 3

Back to Question 15

Explanation 15

No return statement required

A method with a signature that specifies a void return type does not require a return statement.

However, such a method may contain a return statement, provided that it is terminated immediately with a semicolon (no expression between the word return and the semicolon).

(Every method whose return type is not void must contain at least one return statement.)

Multiple return statements are allowed

Any method may contain any number of return statements provided that they make sense from a syntax viewpoint, and provided the expression (or lack thereof) between the word return and the semicolon evaluate to the type specified in the method signature (or a type that can be converted to the type specified in the method signature).

A return statement terminates a method immediately

Whenever the execution stream encounters any return statement, the method is terminated immediately, and control is returned to the method that called that method.

Answer 14

A.  Compiler Error

Back to Question 14

Explanation 14

Missing return statement

This program produces the following compiler error under JDK 1.3:

Ap037.java:11: missing return statement
  public int doLoop(){

Even though this program contains a return statement inside the for loop, it is still necessary to place a return statement at the end of the method to satisfy the compiler. (The one shown in the code is a comment.)

The method named doLoop() must return a value of type double.  Apparently the compiler assumes that the return inside the for loop may never be executed (although that isn't true in this case).

Both of the return statements must return a value that satisfies the double type requirement given in the method signature.

Returning a value of type int in the for loop will satisfy the type requirement because type int will be automatically converted to type double as it is returned (that is a widening conversion).

Answer 13

A.  Compiler Error

Back to Question 13

Explanation 13

The scope of a local variable

In general, the scope of a local variable extends from the point at which it is declared to the curly brace that signals the end of the block in which it is declared.

This applies to for loop in an interesting way

While it is allowable to declare a variable within the first clause of a for loop, the scope of that variable is limited to the block of code contained in the loop structure.

The variable cannot be accessed outside the loop.

Attempts to access variable out of scope

This program attempts to access the value of the variable named cnt after the loop terminates.

The program displays the following compiler error under JDK 1.3.  This error results from the attempt to display the value of the counter after the loop terminates.

Ap037.java:15: cannot resolve symbol
symbol  : variable cnt
location: class Worker
    System.out.println(cnt + " ");

Answer 12

C.  0 1 2 3 4 5

Back to Question 12

Explanation 12

A simple for loop structure

This program illustrates a simple for loop that displays the value of its counter using a call to the print() method inside the loop.

After the loop terminates, the program displays the value of the counter one last time using a call to println().

Three clauses separated by semicolons

The first line of a for loop structure always contains three clauses separated by semicolons.

The first and third clauses may be empty, but the semicolons are required in any case.

The first clause ...

The first clause is executed once and only once at the beginning of the loop.

It can contain just about any valid Java expression.

It can even contain more than one expression with the individual expression separated by commas.

When the first clause contains more than one expression separated by commas, the expressions are evaluated in left-to-right order.

The second clause

The second clause is a conditional clause.  It must contain an expression that returns a boolean value.

(Actually, this clause can also be empty, in which case it is apparently assumed to be true.  This leads to an infinite loop unless there is some code inside the loop to terminate it, perhaps by executing a return or a break statement.)

Another entry-condition loop

The for loop is an entry condition loop, meaning that the conditional expression is evaluated once immediately after the first clause is executed, and once per iteration thereafter.

Behavior of the for loop

If the conditional expression returns true, the block of code following the closing parenthesis is executed.

If it returns false, the block of code is skipped, and control passes to the first executable statement following the block of code.

(For the case where the block contains only one statement, the matching curly braces can be omitted.)

The third clause

The third clause can contain none, one, or more valid expressions separated by commas.

If there are more than one, they are evaluated in left-to-right order.

When are they evaluated?

The expressions in the third clause are evaluated once during each iteration.

However, it is very important to remember that despite the physical placement of the clause in the first line, the expressions in the third clause are not evaluated until after the code in the block has been evaluated.

Typically an update clause

The third clause is typically used to update a counter, but this is not a technical requirement.

This clause can be used for just about any purpose.

However, the counter must be updated somewhere within the block of code or the loop will never terminate.

(Stated differently, something must occur within the block of code to eventually cause the conditional expression to evaluate to false.  Otherwise, the loop will never terminate on its own.  However, it is possible to execute a return or break within the block to terminate the loop.)

Note the first output value for this program

Because the update in the third clause is not executed until after the code in the block has been executed, the first value displayed by this program is the value zero.

Answer 11

E.  None of the above

Back to Question 11

Explanation 11

And the answer is ...

The output produced by this program is:
1 3 5

A simple while loop

This program uses a simple while loop to display the value of a counter, once during each iteration.

Behavior of a while loop

As long as the relational expression in the conditional clause returns true, the block of code immediately following the conditional clause is executed.

When the relational expression returns false, the block of code following the conditional clause is skipped and control passes to the next executable statement following that block of code.

An entry-condition loop

The while  loop is an entry condition loop, meaning that the test is performed once during each iteration before the block of code is executed.

If the first test returns false, the block of code is skipped entirely.

An exit-condition loop

There is another loop, known as a do/while loop, which performs the test after the block of code has been executed once.  This guarantees that the block of code will always be executed at least once.

Not on AP exam

However, the subset document indicates that the do/while loop is not tested on the AP exam.  Therefore, this set of tutorial lessons will not discuss the do/while loop.

Just to make things interesting ...

Two statements using the increment operator were placed inside the loop in this program.

Therefore, insofar as the conditional test is concerned, the counter is being incremented by twos.  This causes the output to display the sequence 1 3 5.

Nested while loops

The while loop control structure can contain loops nested inside of loops, which leads to some interesting behavior.

Answer 10

F.  x != 4,5,6

Back to Question 10

Explanation 10

A multiple-choice structure

This is a form of control structure that is often used to make logical decisions in a multiple-choice sense.

This is a completely general control structure.  It can be used with just about any type of data.

A switch structure

There is a somewhat more specialized, control structure named switch that can also be used to make decisions in a multiple choice sense under certain fairly restrictive conditions.

However, the structure shown in this program can always be used to replace a switch.

The subset document indicates that the switch statement is not tested by the AP exam.

Answer 9

D.  Goodbye World

Back to Question 9

Explanation 9

An if/else control structure

This program contains a simple if/else control structure.

Behavior of if/else structure

If the expression in the conditional clause returns true, the block of code following the conditional clause is executed, and the block of code following the word else is skipped.

If the expression in the conditional clause returns false, the block of code following the conditional clause is skipped, and the block of code following the word else is executed.

This program executes the else

In this program, the expression in the conditional clause returns false.

Therefore, the block of code following the word else is executed, producing the words Goodbye World on the computer screen.

Can result in very complex structures

While the structure used in this program is relatively simple, it is possible to create very complex control structures by nesting additional if/else structures inside the blocks of code.

Answer 8

D.  Hello World

Back to Question 8

Explanation 8

A simple if-statement

This program contains a simple if statement that

Tests for x less than y

The relational expression tests to determine if the value of the variable named x is less than the value of the variable named y.

Since the value of x is 5 and the value of y is 6, this relational expression returns true.

Behavior of an if-statement

If the expression in the conditional clause returns true, the block of code following the conditional clause is executed

What is a block of code?

A block of code is one or more statements surrounded by matching curly braces.

For cases like this one where the block includes only one statement, the curly braces can be omitted.

Display the word Hello

In this program, execution of the code in the block causes the print() method to be invoked and the word Hello to be displayed followed by a space, but without a newline following the space.

What if the conditional clause returns false?

If the expression in the conditional clause returns false, the block of code following the conditional clause is bypassed.

(That is not the case in this program.)

After the if-statement ...

After the if-statement is executed in this program, the println() method is invoked to cause the word World to be displayed on the same line as the word Hello.

Answer 7

A.  Compiler Error

Back to Question 7

Explanation 7

Not the same as C and C++

Unlike C and C++, which can use an integer numeric expression in the conditional clause of an if statement, Java requires the conditional clause of an if statement to contain an expression that will return a boolean result.

Bad conditional expression

That is not the case in this program, and the following compiler error occurs under JDK 1.3:

Ap031.java:13: incompatible types
found   : int
required: boolean
    if(x - y){
 

Answer 6

D.  6  4  9.3  7.300000000000001

Back to Question 6

Explanation 6

Postfix increment and decrement operators

This program illustrates the use of the increment (++) and decrement (--) operators in their postfix form.

Behavior of increment operator

Given a variable x, the following two statements are equivalent:

x++;
x = x + 1;

Behavior of decrement operator

Also, the following two statements are equivalent:

x--;
x = x - 1;

Prefix and postfix forms available

These operators have both a prefix form and a postfix form.

Can be fairly complex

It is possible to construct some fairly complex scenarios when using these operators and combining them into expressions.

However, the subset document makes it clear that this is not the intent of the AP CS exam.

Only the postfix form used on the AP exam

According to that document, the postfix form is always used on the exam.

Also, the operators are not included in other expressions on the AP exam.

In these lessons ...

In this series of lessons, the increment and decrement operators will primarily be used to update control variables in loops.

Inaccurate results

Regarding the program output, you will note that there is a little arithmetic inaccuracy when this program is executed using JDK 1.3.

Ideally, the output value 7.300000000000001 should simply be 7.3 without the very small additional fractional part, but that sort of thing often happens when using floating types.

Answer 5

A.  Compiler Error

Back to Question 5

Explanation 5

Cannot use > with reference variables

The only relational operator that can be applied to reference variables is the == operator.

As discussed in the previous questions, even it can only be used to determine if two reference variables refer to the same object.

This program produces the following compiler error under JDK 1.3:

Ap029.java:14: operator > cannot be applied to Dummy,Dummy
    System.out.println(x > y);
 

Answer 4

E.  true true

Back to Question 4

Explanation 4

Two references to the same object

In this case, the reference variables named x and y both refer to the same object.  Therefore, when tested for equality, using either the == operator or the default equals() method, the result is true.

Answer 3

D.  false

Back to Question 3

Explanation 3

Read question 2

In case you skipped it, you need to read the explanation for the answer to question 2 before reading this explanation.

Objects appear to be equal

These two objects are of the same type and contain the same values.  Why are they reported as not being equal?

Did not override the equals() method

When I defined the class named Dummy used in the programs for questions 2 and 3, I did not override the method named equals().

Therefore, my class named Dummy simply inherited the default version of the method named equals() that is defined in the class named Object.

Default behavior of equals() method

After a very long discussion of the behavior of the default equals() method, the Sun documentation summarizes by saying that this method behaves essentially the same as the == operator.

That is to say, the inherited default version of the equals() method will return true if the two objects being compared are actually the same object, and will return false otherwise.

As a result, this program displays false.

Overridden equals() is required for valid testing

If you want to be able to determine if two objects instantiated from a class that you define are "equal", you must override the inherited equals() method for your new class.  You cannot depend on the inherited version of the equals() method to do that job for you.

Overriding may not be easy

That is not to say that overriding the equals() method is easy.  In fact, it may be quite difficult in those cases where the class declares instance variables that refer to other objects.  In this case, it may be necessary to test an entire tree of objects for equality.

Answer 2

D.  false

Back to Question 2

Explanation 2

Use of == with references to objects

This program illustrates an extremely important point about the use of the == operator with objects and reference variables containing references to objects.

You cannot determine...

You cannot determine if two objects are "equal" by applying the == operator to the reference variables containing references to those objects.

Rather, that test simply determines if two reference variables refer to the same object.

Two references to the same object

Obviously, if there is only one object, referred to by two different reference variables, then it is "equal" to itself.

Objects of same type containing same instance values

On the other hand, two objects of the same type could contain exactly the same data values, but this test would not indicate that they are "equal." (In fact, that is the case in this program.)

So, how do you test two objects for equal?

In order to determine if two objects are "equal", you must devise a way to compare the types of the two objects and actually compare the contents of one object to the contents of the other object.  Fortunately, there is a standard framework for doing this.

The equals method

In particular, the class named Object defines a default version of a method named equals() that is inherited by all other classes.

Class author can override the equals method

The intent is that the author of a new class can override the equals() method so that it can be invoked to determine if two objects instantiated from that class are "equal."

What does "equal" mean for objects?

Actually, that is up to the author of the class to decide.

After having made that decision, the author of the class writes that behavior into her overridden version of the method named equals().
 

Answer 1

The answer is True.

Back to Question 1

Explanation 1

Not much to explain here

There isn't much in the way of an explanation to provide for this program.

Evaluate seven relational expressions

Each of the seven relational expressions in the argument list for the println() method is evaluated and returns either true or false as a boolean value.

Concatenate the individual results, separated by a space

The seven boolean results are concatenated, separated by space characters, and displayed on the computer screen.

Brief description of the relational operators

Just in case your aren't familiar with the relational operators, here is a brief description.

Each of these operators returns the boolean value true if the specified condition is met.  Otherwise, it returns false.



Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-