Java Advanced Placement Study Guide:  Introduction to the Lessons, Primitive Types

Sample question.  What do you get when you divide 1.0 by 3 in Java?

Published December 17, 2001
By Richard G. Baldwin

Questions

File JavaAP002.htm


Welcome

This is the first lesson 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.

Background

In October 2000, the AP Computer Science Development Committee made a formal request to The College Board that the AP Computer Science curriculum be revised to include object orientation and to use Java as the delivery language for the AP Computer Science Examinations. The request was approved by the College Board in November 2000.

As of December 2001,

You will have to complete a free registration to gain access to the subset material.  Once you register for that material, you will also have access to a lot more information as well.

Disclaimer

I have no inside knowledge of the questions that will appear on the AP exams, either in terms of format or content.  I have no relationship with the College Board, and did not participate in any way in the deliberations leading up to the use of Java for the AP exams.

I have constructed this study guide solely on the basis of the material in the subset document and my experience as a college professor teaching Java Programming to approximately 500 college students and industry programmers each year since 1997.

Approach

This series of tutorial lessons provides questions, answers, and explanations designed to help you understand the essential subset of features identified by The College Board.

The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the question to the answer and back.

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.

Insofar as possible, I will make use of Sun Java in these lessons.  It will not be possible for me to go back and do a full update each time Sun releases a new version, so over the course of time, I expect to use different versions of Sun Java.

Invoking a Java Program

The subset document mentioned above contains the following statement, "The AP CS exam does not prescribe any particular approach for program invocation."

There are several different kinds of Java programs, including applications, applets, and servlets.  Each different kind of program is invoked in a different way, and the AP exam doesn't require the student to know about all of the different ways that a program can be invoked.  Realistically, however, in order to write and execute a Java program, you must know how to invoke that kind of program.

The simplest kind of Java program to invoke is a Java application.  The questions in these lessons that show program code will almost always show code that is contained in an application.  The Java virtual machine always invokes the main method of the controlling class for an application in order to invoke the program.

In order to illustrate the object-oriented nature of Java, the main method in these questions will usually create an instance (object) of some other class and invoke one or more methods on that object.  Thus, the main method will usually have no purpose other than to cause the program to start running.  The details of data processing will rarely be included in the main method.  When all of the methods invoked by the main method return, the program will terminate and control will return to the system prompt.

File Management

The controlling class used in the program code in these lessons will normally be declared public.

Java requires that any class definition that is declared public be placed in a separate source code file.  The file management required to maintain large numbers of files can be burdensome for simple programs.  These are very simple programs and there is no need to place each class definition associated with a single program in its own separate source code file.

To avoid the logistical effort required to place the definitions for classes other than the controlling class in separate source code files, the other classes defined in a program will not normally be declared public.  Those classes will not have an access modifier.  (Note that this is often referred to as package or default access or visibility, and is not a requirement of the AP CS subset.  This approach is being used here strictly for the convenience of the author.)  This will make the class definitions accessible to the code in the main method, without requiring that they be placed in separate source code files.

What is Included?

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



1.  What output is produced by the following program?
public class Ap001{
  public static void main(
                        String args[]){
    new Worker().hello();
  }//end main()
}//end class definition

class Worker{
  public void hello(){
    System.out.println("Hello World");
  }//end hello()
}//end class definition

Answer and Explanation

2.  What is the largest (algebraic) value of type int?

Answer and Explanation

3.  What is the smallest (algebraic) value of type int?

Answer and Explanation

4.  What two values are displayed by the following program?

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

class Worker{
  public void printDouble(){
    System.out.println(
                     Double.MAX_VALUE);
    System.out.println(
                     Double.MIN_VALUE);
  }//end printDouble()
}//end class definition

Answer and Explanation

5.  What output is produced by the following program?

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

class Worker{
  private boolean myVar;
  public void printBoolean(){
    System.out.println(myVar);
  }//end printBoolean()
}//end class definition

Answer and Explanation

6.  What output is produced by the following program?

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

class Worker{
  public void printBoolean(){
    boolean myVar;
    System.out.println(myVar);
  }//end printBoolean()
}//end class definition

Answer and Explanation

7.  What output is produced by the following program?

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

class Worker{
  public void printBoolean(){
    boolean myVar = true;
    myVar = false;
    System.out.println(myVar);
  }//end printBoolean()
}//end class definition

Answer and Explanation

8.  The plus (+) character can be used to perform numeric addition in Java.  What output is produced by the following program?  Pay particular attention to the boldface expression.

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

class Worker{
  public void printBoolean(){
    boolean myVar = true;
    System.out.println(1 + myVar);
  }//end printBoolean()
}//end class definition

Answer and Explanation

9.  The plus (+) character can be used to perform numeric addition in Java.  What output is produced by the following program?

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

class Worker{
  public void printMixed(){
    double x = 3;
    int y = 3;
    System.out.println(x+y);
  }//end printMixed()
}//end class definition

Answer and Explanation

10.  The slash (/) character can be used to perform numeric division in Java. What output is produced by the following program?

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

class Worker{
  public void printMixed(){
    System.out.println(1.0/3);
  }//end printMixed()
}//end class definition

Answer and Explanation



Copyright 2001, 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, "Primitive types: int, double, boolean are part of the AP Java subset."


Answers and Explanations

Answer 10

D.  0.3333333333333333

Back to Question 10

Explanation 10

Divide floating type by integer type

This program divides the literal floating value of 1.0 by the literal integer value of 3 (no decimal point is specified in the integer literal value).

Automatic conversion from narrow to wider type

To begin with, whenever division is performed between a floating type and an integer type, the integer type is automatically converted (sometimes called promoted) to a floating type and floating arithmetic is performed.

What is the actual floating type, float or double?

The real question here is, what is the type of the literal shown by 1.0 (with a decimal point separating the 1 and the 0).  Is it a double or a float?

Type double is the default

By default, a literal floating value is treated as a double.

The result is type double

Consequently, this program divides a double type by an integer type, producing a result of type double.  This is somewhat evident in the output, which shows about 17 digits plus a decimal point in the result (recall that the maximum value for a float shown earlier had only about eight digits plus the decimal point and the exponent).

How can you create literals of type float?

What if you don't want your literal floating value to be treated as a double, but would prefer that it be treated as a float instead.

You can usually force this to be the case by adding a suffix of either F or f to the end of the literal value (as in 1.0F).  If you were to modify this program to cause it to divide 1.0F by 3, the output would be 0.33333334 with only nine digits in the result.

Answer 9

D.  6.0

Back to Question 9

Explanation 9

Declare and initialize two local variables

This program declares and initializes two local variables, one of type double and the other of type int.  Each variable is initialized with the integer value 3.

Automatic conversion to floating type double

However, before the value of 3 is stored in the double variable, it is automatically converted to type double.

Automatic conversion in mixed-type arithmetic

Numeric addition is performed on the two variables.  Whenever addition is performed between a floating type and an integer type, the integer type is automatically converted to a floating type and floating arithmetic is performed.

A floating result

This produces a floating result.  When this floating result is passed to the println() method for display, a decimal point and a zero are displayed to indicate a floating type, even though in this case, the fractional part of the result is zero.

Answer 8

A.  Compiler Error

Back to Question 8

Explanation 8

Initialize boolean variable to true

This program declares and initializes a boolean variable with the value true.  Then it attempts to add the literal value 1 to the value stored in the boolean variable named myVar.

Arithmetic with booleans is not allowed

As mentioned earlier, unlike C++, boolean types in Java cannot participate in arithmetic expressions.

Therefore, this program will not compile.  The compiler error produced by this program under JDK 1.3 reads partially as follows:

Ap007.java:13: operator + cannot be applied to int,boolean
    System.out.println(1 + myVar);

Answer 7

D.  false

Back to Question 7

Explanation 7

Format for variable initialization

This program declares a local boolean variable and initializes it to the value true.  All variables, local or otherwise, can be initialized in this manner provided that the expression on the right of the equal sign evaluates to a value that is assignment compatible with the type of the variable (I will have more to say about assignment compatibility in a subsequent lesson).

Value is changed before display

However, before invoking the println() method to display the initial value of the variable, the program uses the assignment operator (=) to assign the value false to the variable.  Thus, when it is displayed, the value is false.

Answer 6

A.  Compiler Error

Back to Question 6

Explanation 6

A local boolean variable

In this program, the primitive variable named myVar is a local variable belonging to the method named printBoolean().

Local variables are not automatically initialized

Unlike instance variables, if you fail to initialize a local variable, the variable is not automatically initialized.

Cannot access value from uninitialized local variable

If you attempt to access and use the value from an uninitialized local variable before you assign a value to it, you will get a compiler error.  The compiler error produced by this program under JDK 1.3 reads partially as follows:

Ap005.java:13: variable myVar might not have been initialized
    System.out.println(myVar);

Must initialize or assign value to all local variables

Thus, the programmer is responsible for either initializing all local variables, or assigning a value to them before attempting to access their value with code later in the program.

Answer 5

B.  false

Back to Question 5

Explanation 5

The boolean type

In this program, the primitive variable named myVar is an instance variable of the type boolean.

What is an instance variable?

 (An instance variable is a variable that is declared inside a class, outside of all methods of the class, and is not declared static.  Every object instantiated from the class has one.  That is why it is called an instance variable.)

Cannot use uninitialized variables in Java

One of the great things about Java is that it is not possible to make the mistake of using variables that have not been initialized.

Can initialize when declared

All Java variables can be initialized when they are declared.

Member variables are automatically initialized

If the programmer doesn't initialize the variables declared inside the class but outside of a method (often referred to as member variables as opposed to local variables), they are automatically initialized to a default value.  The default value for a boolean variable is false.

Did you know the boolean default value?

I wouldn't be overly concerned if you had selected the answer A.  true, because I wouldn't necessarily expect you to memorize the default initialization value.

Great cause for concern

However, I would be very concerned if you selected either C. 1 or D. 0.

Java has a true boolean type

Unlike C++, Java does not represent true and false by the numeric values of 1 and 0 (at least the numeric values that represent true and false are not readily accessible by the programmer).

Thus, you cannot include boolean types in arithmetic expressions, as is the case in C++.

Answer 4

B.  1.7976931348623157E308
D.  4.9E-324

Back to Question 4

Explanation 4

Floating type versus integer type

If you missed this one, shame on you!

I didn't expect you to memorize the maximum and minimum values represented by the floating type double, but I did expect you to be able to distinguish between the display of a floating value and the display of an integer value.

Both values are positive

Note that both of the values given above are positive values.

Unlike the integer types discussed earlier, the constants named MAX_VALUE and MIN_VALUE don't represent the ends of a signed number range for type double.  Rather, they represent the largest and smallest (non-zero) values that can be expressed by the type.

An indication of granularity

MIN_VALUE is an indication of the degree of granularity of values expressed as type double.  Any double value can be treated as either positive or negative.

Two floating types are available

Java provides two floating types:  float and double.  The double type provides the greater range, or to use another popular terminology, it is the wider of the two.

What is the value range for a float?

In case you are interested, using the same syntax as above, the value range for type float is from 1.4E-45 to 3.4028235E38

Double is often the default type

There is another thing that is significant about type double.  In many cases where a value is automatically converted to a floating type, it is converted to type double rather than to type float.  This will come up in future lessons.

Answer 3

A.  -2147483648

Back to Question 3

Explanation 3

Could easily have guessed

As a practical matter, you had one chance in two of guessing the answer to this question, already having been given the value of the largest algebraic value for type int.

And the winner is ...

Did you answer B.  -2147483647?

If so, you may be wondering why the most negative value isn't equal to the negative version of the most positive value?

A twos-complement characteristic

Without going into the details of why, it is a well-known characteristic of binary twos-complement notation that the value range extends one unit further in the negative direction than in the positive direction.

What about the other two values?

Do the values of  -32768 and 32767 in the set of multiple-choice answers to this question represent anything in particular?

Yes, they represent the extreme ends of the value range for a 16-bit binary number in twos-complement notation.

Does Java have a 16-bit integer type?

Just in case you are interested, the short type in Java is represented in 16-bit binary twos-complement signed notation, so this is the value range for type short.

What about type byte?

Similarly, a value of type byte is represented in 8-bit binary twos-complement signed notation, with a value range extending from -128 to 127.

Answer 2

B.  2147483647

Back to Question 2

Explanation 2

First question on types

This is the first question on Java types in this series of tutorial lessons.

What does the College Board have to say?

To set the stage for the discussion of types, the version of the Java subset document that is available on 10/30/01 contains the following statement:

"Primitive types: int, double, boolean are part of the AP CS subset. The other primitive types short, long, byte, char and float are not in the subset."
Concentrate on int, double, and boolean

Therefore, this series of lessons will concentrate on int, double, and boolean.

All eight primitive types are important

However, this should not be taken to mean that the other five types are unimportant.  If you expect to work as a Java programmer, you must be fully capable of using all of the eight primitive types, not just the three covered here.

32-bit signed twos-complement integers

Now back to the question at hand.  In Java, values of type int are stored as 32-bit signed integers in twos-complement notation.

Can you calculate the values?

There are no unsigned integer types in Java, as there are in C++.  If you are handy with binary notation, you could calculate the largest positive value that can be stored in 32 bits in twos-complement notation.

See documentation for the Integer class

Otherwise, you can visit the documentation for the Integer class, which provides a symbolic constant (public static final variable) named MAX_VALUE.  The description of MAX_VALUE reads as follows:

"The largest value of type int. The constant value of this field is 2147483647."

Answer 1

C.  Hello World

Back to Question 1

Explanation 1

Pretty easy huh?
The answer to this first question is intended to be easy.  The purpose of the first question is to introduce you to the syntax that will frequently be used for program code in this series of lessons.

The controlling class and the main method

In this example, the class named Ap001 is the controlling class.  It contains a method named main(), whose signature matches the required signature for the main() method.  When the user executes this program, the Java virtual machine automatically invokes the method named main() in the controlling class.

Create an instance of Worker

The main() method uses the new operator along with the default constructor for the class named Worker to create a new instance of the class named Worker (an object of the Worker class).  This is often referred to as instantiating an object.

A reference to an anonymous object

The combination of the new operator and the default constructor for the Worker class returns a reference to the new object.  In this case, the object is instantiated as an anonymous object, meaning that the reference to the object is not saved in a named reference variable.  (Instantiation of a non-anonymous object will be illustrated later.)

Invoke hello method on Worker object

The main() method contains a single executable statement that is highlighted in boldface.  (Note:  Although the statement is highlighted in boldface for presentation purposes, actual Java source code never contains boldface, Italics, underlines, or any other form of decoration.)

As soon as the reference to the new object is returned, the single statement in the main() method invokes the hello() method on that reference.

Output to standard output device

This causes the hello() method belonging to the new object (of the class named Worker) to execute.  The code in the hello() method invokes the println() method on the static variable of the System class named out.

Lots of OOP embodied in the hello method

I often tell my students that I can tell a lot about whether a student really understands object-oriented programming in Java by asking them to explain everything that they know about the following statement:

System.out.println("Hello World");

I would expect the answer to consume about ten to fifteen minutes if the student really understands Java OOP.

The one-minute version

When the virtual machine starts a Java application running, it automatically instantiates an I/O stream object linked to the standard output device (normally the screen) and stores a reference to that object in the static variable named out belonging to the class named System.

Invoke the println instance method on out

Invoking the println() method on that reference, and passing a literal string ("Hello World") to that method causes the contents of the literal String object to be displayed on the standard output device.

Display Hello World on the screen

In this case, this causes the words Hello World to be displayed on the standard output device.  This is the answer to the original question.

Time for main method to terminate

When the hello() method returns, the main() method has nothing further to do, so it terminates.  When the main() method terminates in a Java application, the application terminates and returns control to the operating system.  This causes the system prompt to reappear.

A less-cryptic form

A less cryptic form of this program is shown below.
 
public class Ap002{
  public static void main(
                        String args[]){
    Worker refVar = new Worker();
    refVar.hello();
  }//end main()
}//end class definition

class Worker{

  public void hello(){
    System.out.println("Hello World");
  }//end hello()
}//end class definition

Decompose single statement into two statements

In this version, the single statement in the earlier version of the main() method is replaced by two statements, which are highlighted in boldface.

A non-anonymous object

In the class named Ap002, the reference to the object of the class named Worker is not instantiated anonymously.  Rather, a new object of the Worker class is instantiated and a reference to the object is stored in (assigned to) the reference variable named refVar.

Invoke hello method on named reference

Then the hello() method is invoked on that reference in a separate statement.

Produces the same result as before

The final result is exactly the same as before.  The only difference is that a little more typing is required to create the source code for the second version.

Will often use anonymous objects

In order to minimize the amount of typing required, I will probably use the anonymous form of instantiation whenever appropriate in these tutorial lessons.

Now that you understand the framework ...

Now that you understand the framework for the program code, I can present more specific questions based on the material that is expected to be included in the AP exam.


Copyright 2001, 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-