Wednesday, June 27, 2007

Want to be SCJP 1.4 or 5.0 ?

Go to Home Page


Just study the materials below.....It is enough if you are done with this!!!!!!!!!!!!! Its really a complete site for doing your certification with great scores.

Material chaptered aside is written by author Jamie Jaworski.It covers exams 310-025,
310-027,310-050.

For scjp 1.4(310-035):

I have attached :
1.Syllabus
2.Study Materials
1.Sun Certified Programmer and Developer for Java 2 - author - Kathy Sierra and Bert Bates
2.Java Certification Success, Part 1: SCJP - author - Pradeep Chopra
3.Mock Exams - with answers
4.Links to online Mock Exams

For scjp 5.0(310-055):

I have attached :
1.Syllabus
2.Study Materials
1.Sun Certified Programmer for Java 5 written by Kathy Sierra and Bert Bates
3.Mock Exams - with answers
4.Links to online Mock Exams

For scjp 5.0 Upgrade Exam(310-056):

I have attached:
1.Fast Track to Sun Certified Java Programmer(SCJP)5.0 Upgrade Exam


Go through once.You will really find it very very helpful!

Go to Home Page

Java 2 Certification Training Guide.pdf - Jamie Jaworski Chapter 1. Introduction & Sample SCJP Exam Questions

Go to Home Page



Java 2 Certification Training Guide

Chapter 1. Introduction & Sample SCJP Exam Questions

Table of Contents

Introduction

Part I Becoming a Sun Certified Java 2 Programmer

Chapter 1 -Overview of the Java Programmer Exam -9
Chapter 2 -Language Fundamentals - 15
Chapter 3 -Operators and Assignments - 31
Chapter 4 -Declarations and Access Control - 60
Chapter 5 -Flow Control and Exception Handling - 74
Chapter 6 Overloading, Overriding, Runtime Type, and Object Orientation - 95
Chapter 7 -Garbage Collection - 114
Chapter 8 -Threads - 122
Chapter 9 -The java.lang Package - 145
Chapter 10 -The java.util Package - 158
Chapter 11 -The java.awt Package: Components and Facilities - 177
Chapter 12 -The java.awt Package: Layout - 204
Chapter 13 -The java.awt Package: Event Handling - 219
Chapter 14 -The java.awt Package: Painting - 238
Chapter 15 -The java.io Package - 257

Part II Becoming a Sun Certified Java 2 Architect

Chapter 16 -Overview of the Java Architect Exam - 285
Chapter 17 -Java Applications Architecture - 289
Chapter 18 -Object-Oriented Architecture Design - 300
Chapter 19 -Distributed Applications Technologies - 314
Chapter 20 -Securing Distributed Applications - 337
Chapter 21 -Working with Legacy Systems - 354


Part III Becoming a Sun Certified Java 2 Developer

Chapter 22 -Overview of the Java Developer Exam - 368
Chapter 23 -The Programming Assignment - 373
Chapter 24 -The Essay Exam - 379


Part IV Appendixes

Appendix A -Running the Simulated Exam Program - 385
Appendix B -Running the Simulated Preparation Program - 390
Index
List of Figures
List of Tables
List of Listings
List of Sidebars



Introduction

Java 2 Certification

In just a few years, Java has become one of the world's most popular programming languages. Java's
initial popularity stemmed from its association with the Web and its capability to deliver executable
content to Web pages. This popularity increased as programmers discovered Java's power, simplicity,
and rich APIs. Java's popularity increased further as both large and small companies invested in
building Java-based information infrastructures.

One of the results of Java's popularity is that there is a high demand for skilled Java programmers and
system architects. However, due to Java's brief existence, experienced Java programmers are hard to
find. Hardly anyone in the field has more than a few years experience in developing Java applications.
This is a problem for both employers and programmers. Employers cannot rely on the traditional
number of years of experience in selecting senior-level Java programmers and software engineers. Star
Java programmers have a hard time differentiating themselves from entry-level Java programmers.

The Java certification exams provide a solution for both employers and programmers. Employers can
identify skilled Java programmers by their certification level. Programmers and software engineers can
attest to their knowledge of Java by pointing to their certification credentials.

The Java certification program is not new—it has been around since version 1.02 of the Java
Developer's Kit. However, a new certification exam—the Java Architect exam—was introduced with
Java 2. The differences between the three exams are as follows:

.
Programmer exam—The Programmer exam tests the candidate's knowledge of the Java
language and basic API packages. Programmer certification is a prerequisite to Developer
certification.
.
Developer exam—The Developer exam tests the candidate's ability to complete an extended
programming assignment and answer questions concerning the issues and tradeoffs involved in
the assignment's completion.
.
Architect exam—The Architect exam tests a candidate's familiarity with the technologies used
to build Java-based enterprise applications and the candidate's ability to resolve issues in Java
application design. This exam focuses on much higher-level software and system engineering
skills than the Programmer and Developer exams.
Being a Java evangelist since its initial alpha release in 1995 and having written several books on Java,
I was intrigued about how Sun would go about testing programmers. When I finally took the JDK 1.1
Programmer's exam back in 1998, I was amazed at the great job that Sun's testers had done at
selecting a challenging and highly appropriate set of questions for the test. When I was invited in
December of 1998 to visit Sun's Broomfield, Colorado campus to select the questions for the Java 2
Programmer's exam, I jumped at the chance. Since then, I've been actively involved in all aspects of
Java certification, taking and passing each of the three exams and developing an online training course
for DigitalThink. I am confident that this book will help you in your quest to attain Java certification, no
matter which certification exam you take.

Attaining Java certification is not easy. The most basic certification exam the Programmer exam is very
difficult, even for an experienced Java programmer. This exam covers every aspect of the Java
language and many of the core classes and interfaces of the basic API packages. In order to pass this
exam you must acquire both a breadth and depth of experience with the Java language and selected


API packages. This book is organized to help you to prepare for the Programmer, Architect, and
Developer exams as follows:

Part I of this book is dedicated to the Programmer exam and is organized according to Sun's
published exam topics and objectives. It contains a detailed and focused description of the topics
that are covered by the exam, numerous questions that review your understanding of these
topics, and even more questions that you can use to measure your progress and determine when
you're ready to take the exam.

Part II prepares you for the Java Architect exam. It introduces the technologies that are covered
by the exam and describes the issues and tradeoffs involved in building Java-based distributed
applications. It also provides review and sample exam questions that you can use to assess your
mastery of the exam topics.

Part III covers the Java Developer exam. It provides you with background information on what
to expect and provides a number of tips that will help you to successfully complete your
assignment. The essay part of the Developer exam is also covered. Approaches to preparing for
and answering the essay questions are described. Sample exam questions are examined and
answers to these questions are provided.
Who Should Read This Book

This book is for anyone who wants to take and pass any of the three Java 2 Platform certification
exams. If you are an experienced Java programmer and you want to pass the Programmer exam, this
book will show you how. It will fill any gaps that you might have in your knowledge of the Java language
or fundamental API packages. It will cover all that you need to know to do well on the exam and help
you to assess your test readiness through hundreds of review and sample exam questions. If you study
the material presented in each chapter, use the review questions to identify areas that you need to
improve in, and continue your study until you get high grades in the sample exam questions. Then you'll
be on a direct path to passing the exam.
If you are not an experienced Java programmer, you'll need to learn how to program in Java before
taking the Programmer exam. I suggest that you start with Sun's online Java tutorial at
http://www.javasoft.com/docs/books/tutorial/index.html and work your way through
an intermediate to advanced Java book, such as Java 1.2 Unleashed.

If you are an experienced software or system engineer and you want to take and pass the Java
Architect exam, this book will point you to the information that you need to know in order to pass the
exam. While you won't be an experienced architect after reading six chapters, you will have covered the
Architect exam topics and learned about the salient issues faced by the architects of Java-based
applications. Moreover, the review and exam questions of these chapters will help you to determine
whether you need more study or are ready to take the exam. You don't need to take the Java
Programmer exam to take the Java Architect exam. However, as you can probably guess, knowledge of
Java programming is extremely helpful for anyone who wants to design Java-based applications.

If you successfully pass the Java Programmer exam, you may want to achieve a higher level of
certification by taking and passing the Java Developer exam. The Java Developer exam is a two-part
exam that consists of a programming assignment and an essay exam. The programming assignment
requires you to complete a partially developed Java application according to a list of very specific
instructions. The essay exam consists of a small number (5–10) of short-answer essay questions. In
order to take the Java Developer exam you must take and pass the Programmer exam. If you haven't
taken the Programmer exam, then you should definitely start with that. Don't worry about the Developer
exam until you have the Programmer exam under your belt. Once you've taken the Programmer exam, I
recommend that you take (or at least study for) the Architect exam. The object-oriented design
principles that you cover in preparing for the Architect exam will help you to do better on the
programming assignment part of the Developer exam and also help you to answer the essay questions
with a better understanding of the design tradeoffs they address.

Getting Started

To use this book, you'll need a computer and operating system that support the Java 2 Platform. There
are a wide variety of operating systems that support the Java 2 Platform, including Windows 2000, NT,
98, and 95, Linux, and Solaris. Ports of the Java 2 Platform to many other operating systems are in the
works. The examples used in this book were developed under Windows 98. However, they are pure
Java and will run under all Java 2 Platform implementations.


The CD-ROM that accompanies this book contains all the source and compiled code for all examples
presented in this book. The CD-ROM is a hybrid that works on Windows, Linux, UNIX, and Macintosh
platforms. In addition, it contains an Exam Preparation program that helps you to review the material
presented in each chapter and a Simulated Exam program that tests your knowledge of this material.
Appendixes A and B show you how to install and run these programs.

How to Use This Book

No matter which exam you are studying for, I recommend that you start with Chapter 1 and proceed
through each chapter of the book in order, working through all review and exam questions. Passing the
Programmer exam is a prerequisite to taking the Developer exam. However, I believe that the refined
understanding of the Java language and basic API that you need to pass the Programmer exam is also
an important asset to a Java Architect. I also believe that the object-oriented software engineering skills
that you need to pass the Java Architect exam will help you to do better on the Java Developer exam.

Conventions Used in This Book

This book follows certain conventions that make it easier for you to use.

.
List of Objectives—Each chapter begins with a list of objectives that identify areas you
should focus on in studying the material presented in the chapter.
.
Chapter Outline—The chapter's outline is presented after the list of objectives, enabling you
to get a quick overview of the chapter's organization.
.
Study Strategies—Study strategies that identify ways to prepare for the certification exam
are provided, following the chapter outline.
.
Chapter Introduction/Summary—In order for you to understand where you are going and
where you have been, each chapter begins with a short description of the information that
will be presented and ends with a summary of the material that was covered.
.
Key Terms—A list of key terms are provided at the end of each chapter. You should review
each term and make sure that you are familiar with how the term applies to the material that
you studied in the chapter.
.
Review Questions—Review questions are short-answer questions that test your
comprehension of the material that was presented in the chapter. I recommend that you
write down your answers to these questions to increase your retention of the information
you've studied.
.
Exam Questions—Exam questions are multiple-choice questions that are modeled after
questions that appear in the certification exams. These questions are used to test your
knowledge of the material covered in the chapter and determine whether you need further
study before going on to the next chapter or taking the certification exam.
.
Answers and Explanations—The answers to each of the review and exam questions are
provided along with short explanations as to why each answer is correct.
.
Suggested Readings and Resources—Each chapter ends with a reference to additional
information that you can use to learn more about the information that you just studied.
A monospaced font is used to identify program code. An italic monospaced font is used to
identify any placeholders used in Java syntax descriptions.

In addition, the following visual cues will help draw your attention to important information.
Note Notes like this are used to call your attention to information that is important to
understanding and using Java or doing well on the certification exams.
Tip Tips like this are used to identify ways that you can use Java more efficiently or
prepare yourself for the certification exams.
Warning Warnings like this are used to help you to avoid common problems
encountered when using Java and when answering exam questions.


The Book's Web Site

To help you with your certification studies, I've put together a Java certification Web site that
supplements the information presented in this book. It provides a forum for feedback on the certification
exams and contains any corrections for errors that are discovered after the book's printing. The URL for
this Web site is http://www.jaworski.com/java/certification/. If you have any questions,
comments, or suggestions concerning the book, its Web site, or the certification exams, please direct
them to support@jaworski.com

Part I: Becoming a Sun Certified Java 2 Programmer

Chapter List

Chapter 1: Overview of the Java Programmer Exam

Chapter 2: Language Fundamentals

Chapter 3: Operators and Assignments

Chapter 4: Declarations and Access Control

Chapter 5: Flow Control and Exception Handling

Chapter 6: Overloading, Overriding, Runtime Type, and Object Orientation

Chapter 7: Garbage Collection

Chapter 8: Threads

Chapter 9: The java.lang Package

Chapter 10: The java.util Package

Chapter 11: The java.awt Package: Components and Facilities

Chapter 12: The java.awt Package: Layout

Chapter 13: The java.awt Package: Event Handling

Chapter 14: The java.awt Package: Painting

Chapter 15: The java.io Package

Exam Questions (from Sun)
1. What would be the result of attempting to compile and run the following piece of code?

public class Test {
static int x;
public static void main (String args—]) {
System.out.println("Value is " + x);
} }
A. The output "Value is 0" is printed.
B. An object of type NullPointerException is thrown.
C. An "illegal array declaration syntax" compiler error occurs.
D. A "possible reference before assignment" compiler error occurs.
E. An object of type ArrayIndexOutOfBoundsException is thrown.

7. What should you use to position a Button within an application Frame so that the size of the Button is NOT affected by the Frame size?
A. A FlowLayout
B. A GridLayout
C. The center area of a BorderLayout
D. The East or West area of a BorderLayout
E. The North or South area of a BorderLayout

8. Which is the advantage of encapsulation?
A. Only public methods are needed.
B. No exceptions need to be thrown from any method.
C. Making the class final causes no consequential changes to other code.
D. It changes the implementation without changing the interface and causes no consequential changes to other code.
E. It changes the interface without changing the implementation and causes no consequential changes to other code.


9. What can contain objects that have a unique key field of String type, if it is required to retrieve the objects using that key field as an index?
A. Map B. Set C. List D. Collection E. Enumeration


10. Which statement is true about a non-static inner class?
A. It must implement an interface.
B. It is accessible from any other class.
C. It can only be instantiated in the enclosing class.
D. It must be final, if it is declared in a method scope.
E. It can access private instance variables in the enclosing object.

11. Which are keywords in Java?
A. NULL B. sizeof C. friend D. extends E. synchronized


12. Which declares an abstract method in an abstract Java class?
A. public abstract method();
B. public abstract void method();
C. public void abstract Method();
D. public void method() {abstract;}
E. public abstract void method() {}

Answers to Exam Questions
1. A. The program compiles without error. The default value of an uninitialized int variable is 0. 2. A. The size of a component that is laid out via a BorderLayout or GridLayout is affected by the Frame size. This is not the case with a FlowLayout.
3. D. When a class is properly encapsulated, it is possible to change the class's implementation without changing its interface. Implementation changes do not affect other classes which abide by this interface.
4. A. The Map interface provides the capability to retrieve objects by their keys. The others do not.
5. E. An object of a non-static inner class is able to access private variables of objects of the outer class in which it is defined.
6. D. and E The words, extends and synchronized, are Java keywords. The others are not.
7. B. The abstract keyword must precede the method's return type.

Go to Home Page

Chapter 2 - Language Fundamentals

Go to Home Page



Chapter 2:

Language Fundamentals

As you read through this chapter, you should concentrate on the following key items:
. How to identify a Java package . How to import classes and interfaces from other packages . How to create a program's main() method . How to access command-line arguments . How to create valid identifiers . How field variables and arrays are initialized . What the range of each primitive type is . How to create literal values of each primitive type . How to create String literal values

Chapter Introduction

This chapter covers the fundamentals of the Java programming language. If you've written Java programs, you should be familiar with most of the material in this chapter. However, odds are there are a few things that you might not be sure of. The questions on the certification exam will exploit this uncertainty—so pay careful attention to the material that's presented. Make sure that you read through each section, even if you think that you know it cold. The review questions and exam questions will let you know how well you know this material and will give you an idea of how well you will do in exam-related questions.

The Structure of Java Programs

Java programs are composed of declarations of classes and interfaces. Classes define variables, which provide named access to data, methods, which perform actions consisting of operations on the data, and constructors, which create instances of classes, referred to as objects. Data items consist of primitive data values—such as byte, char, and int values—and objects—such as arrays, I/O streams, and GUI elements. Interfaces define collections of methods that are implemented by classes. They are also used to define constants, which are data values that cannot be changed. Java programs are written using one or more compilation units, which are Java source code files. Every source code file consists of the name of a class or interface followed by the .java extension. Since Java identifiers are case-sensitive, source code filenames are also case-sensitive. Each source code file may contain at most one public class or interface. If a class or interface is declared as public, the source code filename must be the name of the class or interface (followed by the .java extension). If a source code file does not contain a public class or interface, it may take on a name that is different from its classes and interfaces.

Identifying Packages

Java classes and interfaces are organized into packages. Packages provide a naming context for classes and interfaces. In other words, packages enable different programmers (or even the same programmer) to create classes and interfaces with the same name. For example, if you and I both create a class named Cool and then use the two different versions of Cool in the same program, the compiler and runtime system won't know which version to use. But, if I put my Cool class in the Mypackage, and you put your
Cool class in the You package, the compiler and runtime system will have no problem, as long as we refer to Cool using its package name. Packages are identified by the package statement. It must appear as the first statement in a source code file
package packageName;
Note Use of Packages In addition to being used as a naming context, packages are
used to organize related classes and interfaces into a single API unit to which
access may be controlled. If a package statement is omitted, the classes and interfaces declared within the package are put into the default no name package. In the Java 2 Platform Software Development Kit (SDK), the package name and the CLASSPATH environment variable are used to find a class or interface that is located in another package.

Importing Classes and Interfaces from Other Packages

The import statement is used to reference classes and interfaces that are declared in other packages (without having to specify their names each time they are referenced). There are three forms of the import statement:
import packageName.className;
import packageName.interfaceName;
import packageName.*;
The first and second forms enable the identified classes and interfaces to be referenced without specifying the name of their package. The third form allows all classes and interfaces in the specified package to be referenced without specifying the name of their package.
The main() Method
The main() method is used as the entry point for a Java application program. All programs must have a main() method or they cannot be run. The main() method is a method of the class that is executed to run the program.

Note Importing java.lang The java.lang package is always imported by default
and does not need to be imported by an import statement. For example, if your program's name is MyProgram, then the MyProgram class must be defined in a file named MyProgram.java. The MyProgram class must have a correctly defined main() method. A correctly defined main() method has the following form:
public static void main(String[] args) {
// Statements go here
} The main() method must be declared as public, static, and void. The void keyword must appear immediately before main(). The public and static keywords may be interchanged. The main() method has one argument—an array of String arguments. This argument may be defined as String[] args or String []args or String args[]. The args argument may use any valid identifier. For example, you can use arg, myArgs, or parms. However, args is standard, and you should probably stick with it. As a convention, when I refer to args, I'm referring to the argument to a program's main() method. The args array is used to access a program's command-line arguments. These arguments are passed to a program when it is invoked. They are passed as part of the command that is used to invoke the program.
Note Applets Applets are not required to have a main() method.
For example, to run the MyProgram program, you would enter
java MyProgram Suppose that you wanted to pass the arguments 2 and 3 to MyProgram.

You would invoke it as follows:
java MyProgram 2 3 The String object "2" would be accessed as args[0], and the String object "3" would be accessed as args[1]. If you are a C or C++ programmer—pay attention. Java accesses command-line arguments using different indices than do C and C++ programs. The ArgsTest program of Listing 2.1 shows how command-line arguments are accessed using the args array. When you run the program using the following command line

java ArgsTest this is a test
it displays the following results args[0] = this args[1] = is args[2] = a
args[3] = test Listing 2.1: The Argstest Program class ArgsTest {
public static void main(String[] args) {
for(int i=0;i System.out.println("args["+i+"] = "+args[i]);
}
}
}

Comments

Java provides three styles of comments: /* This is a multiline comment. */
// This is a single-line comment.
/** This is a multiline javadoc comment */ The first comment style supports traditional C-language comments. All text appearing between /* and */ is treated as a comment. Comments of this style can span multiple lines. The second comment style supports single line C++ comments. All text following the // until the end of the line is treated as a comment. The third comment style is used by the javadoc documentation generation tool. All text between the /** and */ is treated as a javadoc comment. javadoc comments may span multiple lines. You don't need to know about javadoc on the certification exam. However, if you are interested, it is described in the tools section of the Java 2 platform documentation.
Comments cannot be nested. If comments appear within a String or character literal, they are treated as part of the String or literal.

Identifiers and Keywords

Identifiers are used to name Java language entities. They begin with a Unicode letter, underscore character (_), or dollar sign ($). Subsequent characters consist of these characters and the digits 0–9. Identifiers are case sensitive and cannot be the same as a reserved word or the boolean values True or False or the null value. Avoid using the dollar sign character; it is intended for use by compiler-generated identifiers.

The following are examples of valid Java identifiers:
. myIdentifier. $my_identifier. $123 The following are invalid Java identifiers:
. 1badIdentifier . bad-too . %badID The following words are reserved by the Java language and cannot be used as identifiers:

abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements importinstanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient try void volatile while
Although you don't necessarily need to memorize the above list, it's a good idea to familiarize yourself with it because you are very likely to see at least one exam-related question that requires knowledge of the preceding keywords.

Primitive Types and Literal Values

Java defines eight primitive types. Variables that are declared as a primitive type are not references to objects. They are only place-holders to store primitive values. The eight primitive types are byte, short, int, long, float, double, char, and boolean. The byte, short, int, and long types represent 8-, 16-, 32-, and 64-bit signed integer values. The char type represents an unsigned 16-bit value. The float and double types represent 32- and 64-bit floating point values. The ranges of the primitive types are shown in Table 2.1.

Table 2.1: Ranges of Numeric Types
Type boolean byte char short int long float Range true and false -(27) to 27 - 1 0 to 216 - 1 -(215) to 215 - 1 -(231) to 231 - 1 -(263) to 263 - 1 Float.MIN_VALUE to Float.MAX_VALUE, Float.NaN,
- 19
Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITYdoubleDouble.MIN_VALUE to Double.MAX_VALUE, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY
The literal values of these integer types are written using positive or negative decimal, hexadecimal, or octal integers. Hexadecimal values are preceded by 0x or 0X and use the letters a through f (uppercase or lowercase) to represent the digits 10 through 15. Octal numbers are preceded by 0. Long decimal values have an l or L appended to the end of the number. Examples of conversions between decimal, hexadecimal, and octal values are shown in Table 2.2.
Table 2.2: Decimal, Hexadecimal, and Octal Values
Decimal Value 14 123 4567 Hexadecimal Value 0x0E 0x7B 0x11D7 Octal Value 020 0173 010727

The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers. Floatnumbers have the f or F suffix. Double numbers have d or D. If no suffix is provided, the default double type is assumed. Floating-point numbers may be written using any of the following forms:
digits . optionalDigits optionalExponentPart suffix
. digits optionalExponentPart suffix
digits optionalExponentPart suffix

The suffix is optional. It consists of f, F, d, or D, as described previously. The exponent part is optional. It consists of an e or E followed by a signed integer. It is used to identify the exponent of 10 of the number written in scientific notation. For example, 1000000.0 could be represented as 1.0E6. If a floating-point literal does not contain a decimal point, then it needs to have either the exponent part or the suffix to be recognized as a floating-point literal (as opposed to an integer literal). The Float and Double classes define three special float and double constants. The special value NaN is used to represent the value for "not a number" that occurs as the result of undefined mathematical operations. The values, POSITIVE_INFINITY and NEGATIVE_INFINITY, represent infinite values in the positive and negative directions. The char type represents 16-bit Unicode characters. Unicode is a 16-bit superset of the ASCII character set that provides many foreign-language characters. A single character is specified by putting the character within single quotes ('). There are three exceptions: single quote ('), double quote ("), and backslash (\). The backslash character (\) is used as an escape code to represent special character values. For example, a single quote would be represented by '\''. The character escape codes are shown in Table 2.3.

Table 2.3: Character Escape Codes

Escape Code \b \t \n \f \r \" \' \\ Character backspace tab linefeed form feed carriage return double quote single quote backslash

The backslash can also be followed by an 8-bit octal value (\000 through \377) or by a u or U followed by a four-digit, hexadecimal value (\u0000 through \uffff). The four-digit value can be used to specify the full range of Unicode characters. The boolean type represents the logical values true and false. String literals are also supported by Java. String literals are not primitive values. They are a shorthand notation for representing String objects. Strings consist of characters enclosed by double quotes ("). The character escape codes may be used within String literals to represent special characters within the string. The literal value null is used to identify the fact that an object is not assigned to a variable. It may be used with any variable that is not of a primitive data type. Class literals were introduced with Java 1.1. A class literal is formed by appending .class to the name of a primitive or reference type. It evaluates to the class descriptor of the reference type or class descriptor of the primitive type's wrapper class. The expression void.class evaluates to the class descriptor of the Void class. For example, suppose Test is a class that you've declared.
The following statement displays the output class Test:

System.out.println(Test.class);
Automatic Initialization
Field variables and the elements of arrays are automatically initialized to default values. Local variables are not automatically initialized. Failure to initialize a local variable results in a compilation error. Table
2.4 identifies the default values of each primitive type.

Table 2.4: Default Values for Primitive Types
boolean
false
Type
Default Value
byte
0
char
\u0000
short
0
int
0
long
0l
float
0.0f
double
0.0d

Note Field Variables and Local Variables Field variables are variables that are declared as members of classes. Local variables, also referred to as automatic variables, are declared relative to (or local to) a method or constructor.
Field variables of object types and the elements of arrays of object types are automatically initialized to the null value. The Initialization program (Listing 2.2) illustrates the use of the automatic initialization of field variables and arrays. It displays the following output:
boolean: false byte: 0 char: short: 0 int: 0 long: 0 float: 0.0 double: 0.0 Object: null int[2]: 0 0

Object[2]: null null Note Declaring Arrays and Objects The declaration and use of arrays and objects are covered in Chapter 4, "Declarations and Access Control."

Listing 2.2: The Initialization Program

class Initialization { boolean bo; byte by; char c; short s; int i; long l; float f; double d; Object o; public static void main(String[] args) {
Initialization app = new Initialization();
app.run(); } void run() {
int[] intArray = new int[2]; Object[] objectArray = new Object[2]; System.out.println("boolean: "+bo); System.out.println("byte: "+by); System.out.println("char: "+c); System.out.println("short: "+s); System.out.println("int: "+i); System.out.println("long: "+l); System.out.println("float: "+f); System.out.println("double: "+d); System.out.println("Object: "+o); System.out.println("int[2]: "+intArray[0]+" "+intArray[1]); System.out.println("Object[2]: "+objectArray[0]+" "+objectArray[1]);

} }

Chapter Summary

This chapter reviewed the basics of Java programming. You learned how to create packages, import classes and interfaces from other packages, and create a program's main() method. You also learned how command-line variables are accessed, identifiers are formed, and which keywords are reserved by the Java language. You were introduced to each primitive type, learned its range of values, and learned how to create literal values of each type (and also the String type). You should now be prepared to test your knowledge of these subjects. The following review questions and exam questions will let you know how well you understand this material and will give you an idea of how you'll do in related exam questions. They'll also indicate which material you need to study further.

Key Terms

. Interface . Class . Field Variable . Local Variable . Automatic Variable . Constant . Object . Method . Constructor . Compilation Unit . Source Code File . Package . Naming Context . Import . Command-Line Argument . Comment . Keyword . Primitive Type

Review Questions

1. What is a Java package and how is it used?
2. What is a compilation unit?
3. How are Java source code files named?
4. What restrictions are placed on the location of a package statement within a source code file? 5. Which package is always imported by default?
6. What is the return type of a program's main() method?
7. What is the argument type of a program's main() method?
8. Which non-Unicode letter characters may be used as the first character of an identifier? - 23
9. Which characters may be used as the second character of an identifier, but not as the first character of an identifier?

10. Are true and false keywords?
11. Is null a keyword?
12. Is sizeof a keyword?
13. Name the eight primitive Java types.
14. What is the range of the short type?
15. What is the range of the char type?
16. Is "abc" a primitive value?
17. To what value is a variable of the boolean type automatically initialized?
18. To what value is a variable of the String type automatically initialized?

Exam Questions
1. In order for the public class MyClass to successfully compile, which of the following are true? A. MyClass must have a correctly formed main() method.

B. MyClass must be defined in the file MyClass.java.
C. MyClass must be defined in the MyClass package.
D. MyClass must be imported.

2. In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
A. It must import java.lang.
B. It must declare a public class named Test.
C. It must be named Test.java.
D. It must have a package statement.

3. In order for the MyProgram program to be compiled and run, which of the following must be true?
A. The MyProgram class must be defined in MyProgram.java.
B. MyProgram must be declared public.
C. MyProgram must have a correctly formed main() method.
D. MyProgram must import java.lang.

4. Which of the following are true?
A. If a package statement is included in a source code file, it must appear as the first non-blank line.
B. If an import statement is included in a source code file, it must appear as the first non-blank line.
C. If a main() method is included in a source code file, it must appear as the first non-blank line. D. If a public interface is declared in a source code file, it must have the same name as the source code file.

5. Which of the following are valid main() methods?
A. public static void main() { }
B. public static void main(String[] argc) { }
C. void main(String[] args) { }
D. public static void main(String []args) { }

6. What is the output of the following program when it is invoked using the command line java Test this is a test?
7. class Test {
8. public static void main(String[] args) {
9. System.out.println(args[1]);
10. } }
A. this B. is C. a D. test - 24


11. Which of the following are valid Java comments?
A. \\ This is a comment.
B. /* This is a comment. */
C. /** This is a comment. */
D. \* This is a comment *\

12. Which of the following are valid Java identifiers?
A. %id
B. $id
C. _id
D. #id

13. Which of the following are valid Java identifiers?
A. my-id
B. my_id
C. 101ids
D. id101

14. Which of the following are Java keywords?
A. interface B. sizeof C. superD. volatile

15. Which of the following are Java keywords?
A. NULL B. null C. extends D. main

16. Which of the following are primitive types?
A. byteB. StringC. integerD. Float

17. What is the range of the short type?
A. 0 to 216 B. -(216) to 216 C. -(215) to 215 D. -(215) to 215- 1

18. What is the range of the char type?
A. 0 to 216 B. 0 to 216 - 1 C. 0 to 215 D. 0 to 215- 1

19. What is the octal equivalent of the decimal value 123?
A. 0173 B. 123 C. 0x123 D. 0x173

20. What is the hexadecimal equivalent of decimal 123?
A. 0x173 B. 0x123 C. 0x7B D. 173

21. What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment."); ?
A. // Looks like a comment.
B. / Looks like a comment.
C. No output is displayed.
D. The statement results in a compilation error.

22. Which of the following are valid double literals?
A. 1D B. 1E-5D C. e2d D. 1ed

23. What is the output of the following program?
24. public class Question {
25. public static void main(String args[]){
26. boolean[] b = new boolean[2];
27. double[] d = new double[2];
28. System.out.print(b[0]);
29. System.out.println(d[1]);
30. } }
A. true0.0 B. true0 C. false0.0 D. false0

31. What is the output of the following program?
32. public class Question {
33. public static void main(String args[]){
34. Object[] o = new Object[2];
35. byte[] b = new byte[2];
36. System.out.print(o[0]);
37. System.out.println(b[1]);
38. } }
A. 0 B. o0 C. A NullPointerException is thrown D. null0


Answers to Review Questions
1. A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes a
nd interfaces.

2. A compilation unit is a Java source code file.

3. A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

4. A package statement must appear as the first line in a source code file (excluding blank lines and comments).

5. The java.lang package is always imported by default.

6. A program's main() method has a void return type.

7. A program's main() method takes an argument of the String[] type.

8. The non-Unicode letter characters $ and _ may appear as the first character of an identifier.

9. The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

10. The values true and false are not keywords.

11. The null value is not a keyword.

12. The sizeof operator is not a keyword.

12. The eight primitive types are byte, char, short, int, long, float, double, and boolean.

13. The range of the short type is -(215) to 215 - 1.

14. The range of the char type is 0 to 216 - 1.

15. The String literal "abc" is not a primitive value.

16. The default value of the boolean type is false.

17. The default value of an String type is null.

Answers to Exam Questions

1. B. A class does not need a main() method to compile. Nor does it need to be defined in a package or imported. However, a public class needs to be defined in a source code file of the same name.
2. C. A source code file must take the same name as any public class or interface that it declares. 3. C. For a class to be compiled and run, it must have a correctly formed main() method. It does not need to be declared public.
4. A and D. Package statements must appear as the first non-blank line of a source code file (if they appear at all). If a public class or interface is declared in a source code file, then the source code file must take the name of the public class or interface.
5. B and D. The main() method of answer A is missing an argument. The main()method of answer C is missing the public and static modifiers.
6. B. The String "is" is assigned to args[1].
7. B and C. Comments use slashes and not backslashes.
8. B and C. The only special characters that may appear in an identifier are _ and $.
9. B and D. The only special characters that may appear in an identifier are _ and $. Digits may not be used as the first character of an identifier.
10. A, C, and D. The sizeof operator is not a Java keyword.
11. C. NULL, null, and main are not Java keywords.
12. A. Neither String, integer, nor Float are primitive types.
13. D. The range of the short type is -(215) to 215- 1.
14. B. The range of the char type is 0 to 216 - 1.
15. A. The octal value 0173 is equivalent to the decimal value 123.
16. C. The hexadecimal value 0x7B is equivalent to the decimal value 123.
17. A. Comments may not appear in a String literal.
18. A and B. Since the value e2d begins with a letter, it is treated as an identifier. Since there is no signed integer value after the e in 1ed, it is an invalid double literal.
19. C. The default value of a boolean is false and the default value of a double is 0.0.
20. D. The default value of an Object is null and the default value of a byte is 0.

Go to Home Page

Chapter 3 - Operators and Assignments

Go to Home Page




Chapter 3: Operators and Assignments


Chapter Introduction

This chapter is an easy chapter to master. It is also an important one to know. Operators are a basic
building block from which Java expressions and statements are built. You should already be pretty
familiar with the use of many of the operators covered in this chapter. On the other hand, there may be
a handful of operators that you've seen before, but you are not quite familiar with. It's up to you to
identify which ones they are and firm up your knowledge of how they work. This is essential to doing
well on the exam. There are a number of operator-specific and operator-related questions. These are
some of the easier questions on the test. You should answer all of them correctly. If you don't learn
operators well, not only will you miss some of the operator-specific questions, you may also miss some
of the more complex questions that assume knowledge of basic operators.

This chapter reviews all of the Java operators and provides examples of their use. It covers operator
precedence and shows how it is used in expression evaluation. It also covers casting and conversion
and those situations where automatic type conversion comes into play. Read through this chapter and
fill in any gaps that you may have. The review questions and exam questions will let you know how well
you know this material and will give you an idea of how well you will do in operator-specific exam
questions.

Java Operators

Java's operators originate in C and C++. If you are a C or C++ programmer, I have good news and bad
news. The good news is that many of Java's operators have the same behavior as they do in C and
C++. The bad news is that some do not, and the ones that don't can trip you up on the exam. I don't
assume that you have a background in C or C++, but I hope that you are far enough in your Java
programming that most of the operators in Table 3.1 are familiar to you. Take the time now to go
through the table and check off the ones you are familiar with. Then highlight the ones that you need to
study. Pay careful attention to these operators when you work your way through this chapter.

Table 3.1: Operator Summary

Category Operator Example Result
Arithmetic + (Unary) +3 The int
value 3.
+ (Binary) 2 + 4 The value of
x is 6.
- (Unary) -x The sign of x
is changed.
-(Binary) 4 - 2 The value of
x is 2.
++
(Prefix)
x = 3
y = ++x
The value of
x is 4
and
the value of
y is 4.
++
(Postfix)
x = 3
y =
x++;
The value of
x is 4
and
the value of
y is 3.
--
(Prefix)
x = 3
y = --x
The value of
x is 2
and
the value of
y is 2.
--
(Postfix)
x = 3
y = x--
The value of
x is 2
and
the value of
- 33



y is 3.
* 4 * 3 12
/ 11 / 4 2
% 11 % 4 3
String + "ab" +
"cd"
"abcd"
Bitwise ~ ~3 -4
& 3 & 4 0
| 3 | 4 7
^ 5 | 4 4
Shift << 3 << 2 12
>> -6 >> 2 -2
>>> -6 >>>
2
1073741822
Comparison < 5 < 7 true
<= 5 <= 7 true
> 5 > 7 false
>= 5 >= 7 false
== 5 == 7 false
!= 5 != 7 true
instanceof "abc"
instanc
eof
String
true
Logical & true & false
false
| true | true
false
^ true ^ true
false
! !true false
&& true && false
false
|| true || true
false
Category Operator Example Result
Assignment = x = 5; The value of
x is 5.
+= x = 1;
x += 5;
The value of
x is 6.
-= x = 1;
x - =
5;
The value of
x is -4.
*= x = 1;
x *= 5;
The value of
x is 5.
/= int x =
1;
x /= 5;
The value of
x is 0.
%= x = 1;
x %= 5;
The value of
x is 1.
- 34



&= x = 1;
x &= 5;
The value of
x is 1.
|= x = 1;
x |= 5;
The value of
x is 5.
^= x = 1;
x ^= 5;
The value of
x is 4.
<<= x = 1;
x <<=
5;
The value of
x is 32.
>>= x = 1;
x >>=
5;
The value of
x is 0.
>>>= x = 1;
x >>>=
5;
The value of
x is 0.
Cast (type) double
d =
4.2;=
byte b=
(byte)
d;
The value of
b is 4.
Ternary ? : x = 1;
x = (x> 0)
? 5 :
10
The value of
x is 5.
Unary Arithmetic Operators

The arithmetic operators consist of both unary and binary operators. Unary operators perform
operations on a single operand. Binary operations perform operations on two operands. For example, in
the expression, -x, the - operator is used as a unary operator. In the expression, x-y, the - operator is
used as a binary operator.
The unary operators are used to increment, decrement, or change the sign of a value. The + unary
operator has no effect on the sign of a value. The - unary operator changes the sign of a value. Both
the + and - operators have subtle effects on byte, char, and short values. When the + or
operators are applied to a value of these types the value is first converted to an int value. The result of
the operation is an int value. This process, referred to as numeric promotion, is discussed further for
binary arithmetic operations, in the later section, "Numeric Promotion."
The ++ and -- operators are used to increment and decrement a value. For example, if x is 1 then ++x
results in the value of 2 being assigned to x. If x is 6 then --x results in the value 5of 5 being assigned
to x. The ++ operators may appear before the value (prefix) or after the value (postfix). Examples are:
++x (prefix)
x++ (postfix)
--x (prefix)
x-- (postfix)
If xis 4 in the above expressions, then the first two expressions result in 5 being assigned to x, and the
last two expressions result in 4 being assigned to x. Because the prefix and postfix forms of the
increment and decrement operators both result in the same value being assigned to x, you may wonder
what the difference is between the prefix and postfix forms. There is one significant difference between
the prefix and postfix forms, and there's a fair chance that you'll encounter it on the test. The difference
involves the use of prefix and postfix expressions in assignments. When a prefix expression is used in
an expression, the value that is returned is the value that is calculated after the prefix operator is
applied. When a postfix expression is used in an expression, the value that is returned is the value of
the expression before the postfix operator is applied. The following examples illustrate these rules:

x = 10;

y = ++x; // The value assigned to y is 11

- 35



x = 10;

y = x++; // The value assigned to y is 10

x = 10;

y = --x; // The value assigned to y is 9

x = 10;

y = x--; // The value assigned to y is 10

You can see the difference in the results returned by the prefix and postfix operators in the preceding
examples. If you want to make sure that the calculation is performed before returning a value, always
use the prefix operator.

Binary Arithmetic Operators

Now that you've looked at the unary arithmetic operators, we'll cover the binary arithmetic operators +
(addition), - (subtraction), * (multiplication), / (division), and % (modulo).

The binary arithmetic operators are fairly straightforward—they perform simple calculations on a pair of
numeric values. However, there are a few special cases that need to be considered:

.
When an operation is performed on operands of different types
.
When the result of an integer division must be rounded
.
Division by zero
.
Modulo operations
.
Operations that result in the throwing of runtime exceptions
.
Operations that result in overflow or underflow
We'll cover each of the above special cases in the following sections, showing how they apply to each
operator.

Numeric Promotion

When binary operations are applied to numeric arguments (integer and floating-point), numeric
promotion is performed before the operation takes place. The numeric promotion consists of converting
the values of the operands to a common type. The rules for this conversion are straightforward.

.
If one of the operands is a double, then the other is converted to a double.
.
Otherwise, if one of the operands is a float, then the other is converted to a float.
.
Otherwise, if one of the operands is a long, then the other is converted to a long.
.
Otherwise, both operands are converted to int values.
Make sure that you remember these rules. You won't be tested on the rules themselves, but you'll need
to know them to work through related questions. One thing that you probably will see on the test is +
operations involving a numeric value and a String value. These questions test your knowledge of the
difference between the arithmetic + operator and the String+ operator. The String+operator
results in the concatenation of two String objects. For example, "abc" + "def" results in
"abcdef". But what about, 10 + "0" or "2.4" + 2.5?
The rule that you should remember is that when one of the operands in a + operation is a String, then
the other operand is converted to a String. Therefore, 10 + "0" results in the String"100" and
"2.4" + 2.5 results in the String object "2.42.5". The other operand is converted to a Stringobject in one of two ways, depending on whether the operand is an object or a value of a primitive type.
If the other operand is an object, then its toString() method is invoked to convert it to a Stringobject. If the other operand is a value of a primitive type, then an object of the type's wrapper class is
created (see Chapter 9, "The java.lang Package") and the object's toString() method is invoked
to convert it to a String object.
- 36



Integer Division and Division by Zero

Java, like many other languages, supports division (/) operations on integer (long, int, short, char,
and byte) values. In order to return the result of operations like 4/3 as an integer value, it rounds
toward zero. This is the same as truncating the fractional part of the result. The following list provides
some examples of integer division.

.
10 / 3 results in
3
.
-10 / 3 results in -
3
.
10 / -3 results in -3
.
11 / 3 results in
3
.
-11 / 3 results in -
3
.
11 / -3 results in -3
In mathematics, division by zero is undefined. In Java, division by zero results in different values,
depending on whether the operation is performed on an integer value, a positive floating-point value, or
a negative floating-point value.
Division of an integer by zero results in the throwing of an ArithmeticException. Division of a
positive floating-point value by zero results in POSITIVE_INFINITY. Division of a negative floating
point value by zero results in NEGATIVE_INFINITY. Note that when the sign of zero is negative, such
as -0, the sign of the result is reversed. This only applies to floating point operations.

Modulo Operations

For many, the modulo operator %, also referred to as the remainder operator, is not as familiar as the
other binary mathematical operators. First of all, it has nothing to do with percentages. It is the
remainder that results when the first operand is divided by the second. That is, x % y is x - ((int)
(x/y)*y). Java, unlike C and C++, allows floating-point operands to be used with the %operator. The
results of using the % operator with floating-point operands are calculated in a similar manner. The
following list provides some examples of the % operator in action.

.
11 % 3 results in 2.
.
11 % -3 results in 2.
.
-11 % 3 results in -2.
.
-11 % -3 results in -2.
.
11.5 % 3.2 results in 1.8999999999999995. (that is, approximately 1.9)
.
11.5 % -3.2 results in 1.8999999999999995.
.
-11.5 % 3.2 results in -1.8999999999999995.
.
-11.5 % -3.2 results in -1.8999999999999995.
Note that if x is positive and y is not zero, x % y is positive. If x is negative and y is not zero, then x %
y is negative. If x is an integer value and yis zero, then x % y results in the throwing of an
ArithmeticException. If x is a floating-point value and yis zero, then x % y results in NaN (but no
exception is thrown).

Runtime Exceptions

The only runtime exception that occurs during arithmetic operations is the ArithmeticException.
This exception is never thrown in floating-point operations and only occurs in integer operations when
dividing by 0 or taking the remainder of a number by 0. Although you won't be tested on this fact
directly, remember it to help you to weed out bad answers in related questions.

Overflow and Underflow

A numeric overflow occurs when the result of a calculation is larger than the largest value that can be
represented by a type. A numeric underflow occurs when the result of a calculation is smaller than the
smallest value that can be represented by a type. Because arithmetic operations are performed using
numeric values of limited size, some operations result in overflow and underflow. You can determine if
an operation results in an overflow or underflow by calculating its result and determining whether the
result is too large or small to be represented using the number of bytes available to the type. In cases of
integer (but not floating point) overflow and underflow, the lower order bytes of the result that are
capable of fitting into the type are returned as the result of the operation. Figure 3.1 shows how this
occurs:
For example, consider the following program (see Listing 3.1):

- 37



Figure 3.1: How Java handles overflows and underflows.

Listing 3.1: Overflow.java—An Example of the Result of an Overflow Operation


class Overflow {
public static void main(String args[]) {
int n = 2000000000;
System.out.println(n * n);
}

}
The result displayed by this program is -1651507200, which is hardly the square of 2 billion. To
determine how this result is calculated, look at the arithmetic that takes place.

.
2,000,000,000 is represented as 01110111 00110101 10010100 00000000 in
binary form.
.
2,000,000,000 * 2,000,000,000 results in 4,000,000,000,000,000,000, which is
00110111 10000010 11011010 11001110 10011101 10010000 00000000
00000000 in binary form.
.
This overflows the 32-bit int type. Therefore, we only save the last 4 bytes (10011101
10010000 00000000 00000000) as the result.
.
The value of the last 4 bytes is the binary representation of the int value -1651507200.
The good news is that you won't see any questions that will ask you to calculate whether an operation
results in an overflow or underflow. However, there may be some answers to multiple choice questions
that say that an operation results in an overflow or underflow. By being familiar with how overflows and
underflows occur, you will be able to tell which answers are obviously true and which are used as
distractors.

Bitwise Operators

The bitwise operators, ~ (inversion), & (and), | (or), and ^ (exclusive-or) perform operations on integer
values. The ~ operator is a unary operator, and the others are binary operators. Figure 3.2 summarizes
how each operator performs its calculation.

- 38



Figure 3.2: How the bitwise operators work.
The ~ operator inverts the bits which make up the integer value. That is, 0 bits become 1 bits and 1 bits
become 0 bits. For example, ~3 yields the value -4. It is calculated as follows:

.
3 is represented as the binary int value 00000000 0000000000000000 00000011.
.
Inverting each of the bits yields 11111111 1111111111111111 11111100, which is the
bit pattern for -4 as an int value.
The &, |, and ^ operators calculate their results in a bit-by-bit fashion. That is, the nth bit of the result is
calculated using only the nth bit of each operand. These bit-level operations are performed as follows:

.
The & operator returns a 1 bit if the corresponding bits of its operands are both 1. It returns a
0 otherwise.
.
The | operator returns a 0 bit if the corresponding bits of its operands are both 0. It returns a
1 otherwise.
.
The ^ operator returns a 0 bit if the corresponding bits of its operand are both 0or both 1. It
returns a 1 otherwise.
Note
Numeric Promotion Numeric promotion is used with both unary and binary
bitwise operators. This means that byte, char, and short values are converted
to int values before a bitwise operator is applied. If a binary bitwise operator has
one long operand, the other operand is converted to a long value. The type of
the result of a bitwise operation is the type to which the operands have been
promoted.

Table 3.2 summarizes the operation of these operators.

Table 3.2: Binary Bitwise Operators

Operand 1 Operator Operand
2
Result
0 & 0 0
0 & 1 0
1 & 0 0
1 & 1 1
0 | 0 0
0 | 1 1
1 | 0 1
1 | 1 1
0 ^ 0 0
0 ^ 1 1
1 ^ 0 1
1 ^ 1 0
Let's consider the expressions 63 & 252, 63 | 252, and 63 ^ 252. To calculate the value of these
expressions, we first represent the int values 63 and 252 as bit patterns:
00000000 00000000 00000000 00111111 = 63
00000000 00000000 00000000 11111100 = 252

- 39



Because & returns a 1 bit if, and only if, the corresponding bit from each operand is 1, we calculate 63
& 252 to be 60 as follows:

00000000 00000000 00000000 00111111 = 63

00000000 00000000 00000000 11111100 = 252

00000000 00000000 00000000 00111100 = 60
Because | returns a 0 bit if and only if the corresponding bit from each operand is 0, we calculate 63 |
252 to be 255 as follows:

00000000 00000000 00000000 00111111 = 63

00000000 00000000 00000000 11111100 = 252

00000000 00000000 00000000 11111111 = 255
Because ^ returns a 0 bit if, and only if, the corresponding bit from each operand match, we calculate
63 | 252 to be 195 as follows:

00000000 00000000 00000000 00111111 = 63

00000000 00000000 00000000 11111100 = 252

00000000 00000000 00000000 11000011 = 195

The results of bitwise operations are easy to calculate after you've tried a few examples. The questions
at the end of this chapter will help you study them. You may see an exam question that requires you to
know how the bitwise operators work.

Note Java's Platform Independence Because Java is implemented using a platform-

independent virtual machine, bitwise operations always yield the same result,

even when run on machines that use radically different CPUs.

Shift Operators

The shift operators << (left shift), >> (right shift), and >>> (unsigned right shift) also work on the bit
level. All of these operators are binary operators. If you took the JDK 1.1 Programmer Certification
exam, you probably remember a few shift-related questions. Shift-related questions are not emphasized
as much on the JDK 1.2 exam. However, you may still encounter a question that involves shifting. With
a little bit of practice, you'll find that these operators are easy to use.
Numeric promotion is used with the shift operators. The left operand is promoted to an int if it is a
byte, char, or short value. Then the right operand is promoted in the same manner. Note that when
the left operand is an int, only the last 5 bits of the right operand are used to perform the shift. That's
because an int is a 32-bit value and can only be shifted 0 through 31 times. When the left operand is a
long value, only the last 6 bits of the right operand are used to perform the shift. Because long values
are 64-bit values, they only can be shifted 0 through 63 times.
The << operator causes the bits of the left operand to be shifted to the left, based on the value of the
right operand. The new bits that are used to fill in the shifted right bits have the value 0. Figure 3.3
illustrates the process of shifting left. Note that the leftmost bits shifted out of the operand are discarded.
The >> operator causes the bits of the left operand to be shifted to the right, based on the value of the
right operand. The bits that fill in the shifted left bits have the value of the leftmost bit (before the shift
operation). The >> operator is said to be a signed shift because it preserves the sign (positive or
negative) of the operand. Figure 3.4 illustrates how the signed right shift is performed. The right-most
bits that are shifted out of the operand are discarded.
The >>> operator is identical to the >> operator, except that the bits that fill in the shifted left bits have
the value of 0. The >>> operator is said to be an unsigned shift because it does not preserve the sign of
the operand. Figure 3.5 illustrates how the unsigned right shift is performed. The rightmost bits that are
shifted out of the operand are discarded.

- 40



Figure 3.3: The << (left shift) operator.

Figure 3.4: The >> (right shift) operator.
Figure 3.5: The >>> (unsigned right shift) operator.

Comparison Operators

The comparison operators are used to compare primitive values or object references. They are
organized into three subgroups: the relational operators, the equality operators, and the instanceof
operator. The relational operators are only defined for numeric values and the instanceof operator is
only defined for object references.

The Relational Operators

The four relational operators are < (less than), <= (less than or equals), > (greater than), and >=
(greater than or equals). These operators follow their mathematical definitions and produce a boolean
value as their result. However, you should note that any relational expression with the NaN value
evaluates to false.

The Equality Operators

The equality operators consist of == (is equal) and != (is not equal). These operators may be used with
the eight primitive types, as well as object references. They return a boolean value in each case. When
they are used with primitive values, the following rules apply:

.
Numeric values cannot be compared to boolean values. Such a comparison results in a
compilation error.
- 41



.
Numeric promotion takes place before numeric values are compared. This enables any
numeric value to be compared with any other numeric value.
Let's examine what happens in the following program (see Listing 3.2) as the result of the above rules.

Listing 3.2: EqualNumbers.java—Using the Equality Operators


class EqualValues {
public static void main(String args[]) {
byte b = 3;
int i = 5;
float f = 5.0f;
double d = 3.0;
System.out.println((b == d) == (i == f));
}

}
The computation of interest takes place as an argument to the println() method. The expression
(b==d) is evaluated. This results in the promotion of the byte value 3 to a double value. The ==
expression returns a value of true. The expression (i == f) is then evaluated. The int value of 5is
promoted to a float value and the == expression returns a value of true. This results in an
expression true == true as the argument to the println() method. A value of true is printed as
the result. (Note that the true value is converted to a String object by the println() method.)
When object references are compared, the == and != operators check to see if the objects being
compared are the same object instance, and not whether the objects have the same values. For
example, suppose objects A and B are both object of the same class and have exactly the same field
values. If these objects are distinct (that is they are located in different areas of memory), then A == B
evaluates to false, and A != B evaluates to true. Figure 3.6 summarizes the process used in
evaluating expressions that use the equality operators.
Because String objects of identical values may be created during a program's execution, you must be
careful not to compare the values of these objects using the == operator. For example, the following
program (see Listing 3.3) displays a value of false when comparing two String objects with the
same values.

Listing 3.3: EqualStrings1.java—An Example That Uses the == Operator to Compare String Objects
class EqualStrings1 {

public static void main(String args[]) {
String s = "ab";
String s1 = s + "cd";
String s2 = "abcd";
System.out.println(s1);
System.out.println(s2);

- 42



System.out.println(s1 == s2);
}

}
Figure 3.6: Comparing object references.
The equals() method is defined by the Object class as a means to tell whether two objects have the
same value. It is overridden by subclasses of Object, such as String, to provide class-specific value
comparisons. Let's use the equals() method to compare the values of the two String objects from
Listing 3.3. The following program (Listing 3.4) displays a value of true when comparing the two
String objects, referenced by s1 and s2.

Listing 3.4: EqualStrings2.java—An Example That Uses the Equals() Method to Compare StringObjects


class EqualStrings2 {

public static void main(String args[]) {
String s = "ab";
String s1 = s + "cd";
String s2 = "abcd";
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.equals(s2));

}

}
The instanceofOperator

The instanceof operator is a binary operator that determines whether an object reference (the left
operand) is an instance of the class, interface, or array type specified by the right operand. The
instanceof operator cannot be used with primitive types (this results in a compilation error).

- 43



The instanceof operator returns a boolean value of true if the left operand references a non-null

object of class C (or array of type T), so that at least one of the following conditions holds.

.
The right operand is a class name C' and C is a subclass of C'.
.
The right operand is an interface name I, and C implements I.
.
The right operand is an array of type T', the left operand is an array of type T, and T is a
subclass or subinterface of T' or equal to T'.
The instanceof operator returns false if none of the above conditions are met or if the left operand
is null.
The following program (see Listing 3.5) illustrates the use of the instanceof operator.

Listing 3.5: Instance.java—Using the Instanceof Operator to Determine an Object's Runtime Type


import java.util.*;

class Instance {

public static void main(String args[]) {
String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String);
System.out.println(s instanceof Object);
System.out.println(o instanceof String);
System.out.println(o instanceof Object);
System.out.println(o instanceof Vector);

}

}
When you run the program, it produces the following results:
true
true
true
true
false

The first two output lines reflect the fact that s is a String and therefore an Object (because Stringis a subclass of Object). The third output line displays a value of true even though o is declared to be
of type Object. How is this so? That's because the object assigned to o is the String object that was
added to Vectorv. The fourth and fifth output lines result from the fact that a String object is an
Object object but not a Vector object.

- 44



Logical Operators

Java supports two groups of logical operators, the boolean operators ! (not), & (and), | (or), and
^
(exclusive-or), and the logical short-circuit operators && (short-circuit and) and || (short-circuit or). All of
these operators are restricted to boolean operands.
The ! operator performs logical negation. Its operation is simply described:


.
!x results in false if x is true.
.
!x results in true if x is false.
The &, |, and ^ operators operate in the same manner that the bitwise operators do when applied to
each bit. This operation is described in Table 3.3.
Table 3.3: The Boolean Operators &, |, and ^

Operand 1 Operator Operand
2
Result
false & false false
false & true false
true & false false
true & true true
false | false false
false | true true
true | false true
true | true true
false ^ false false
false ^ true true
true ^ false true
true ^ true false
The logical short-circuit operators, && and ||, produce the same logical result as & and |, but differ in
the way they are evaluated. Given an expression x & y, evaluation proceeds in the following order:

1. Evaluate x.
2. Evaluate y.
3. Apply Table 3.3 to determine the result of x & y.
However, the expression x && y is evaluated in the following manner:
1. Evaluate x.
2. If x is false, return false.
3. Otherwise, if x is true evaluate y.
4. Return the value of y.
The && operator is called a short-circuit operator because it skips the evaluation of the second operand,
if the first operand is evaluated as false.
The || operator also operates in a short-circuit fashion. The expression x || y is evaluated as
follows:
1. Evaluate x.
2. If x is true return true.
3. Otherwise, if x is false evaluate y.
4. Return the value of y.
If the first operand of || is true then the evaluation of the second operand is skipped.
The following program (see Listing 3.6) illustrates the results of using the &, |, &&, and || operators.
LogicalListing 3.6: Logical.java—Using the Boolean and Short-Circuit Operators

class Logical {
static boolean sideEffect(boolean b) {
System.out.print("Side effect! ");
return b;

- 45



}

public static void main(String args[]) {
boolean t = true;
boolean f = false;
System.out.println(false & sideEffect(true));
System.out.println(false && sideEffect(true));
System.out.println(true | sideEffect(true));
System.out.println(true || sideEffect(true));

}

}
When you run the program, it produces the following results:

Side effect! false

false

Side effect! true

true

Logical Operators

Java supports two groups of logical operators, the boolean operators ! (not), & (and), | (or), and
^
(exclusive-or), and the logical short-circuit operators && (short-circuit and) and || (short-circuit or). All of
these operators are restricted to boolean operands.
The ! operator performs logical negation. Its operation is simply described:


.
!x results in false if x is true.
.
!x results in true if x is false.
The &, |, and ^ operators operate in the same manner that the bitwise operators do when applied to
each bit. This operation is described in Table 3.3.
Table 3.3: The Boolean Operators &, |, and ^

Operand 1 Operator Operand
2
Result
false & false false
false & true false
true & false false
true & true true
false | false false
false | true true
true | false true
true | true true
false ^ false false
false ^ true true
true ^ false true
true ^ true false
- 46



The logical short-circuit operators, && and ||, produce the same logical result as & and |, but differ in
the way they are evaluated. Given an expression x & y, evaluation proceeds in the following order:

1. Evaluate x.
2. Evaluate y.
3. Apply Table 3.3 to determine the result of x & y.
However, the expression x && y is evaluated in the following manner:
1. Evaluate x.
2. If x is false, return false.
3. Otherwise, if x is true evaluate y.
4. Return the value of y.
The && operator is called a short-circuit operator because it skips the evaluation of the second operand,
if the first operand is evaluated as false.
The || operator also operates in a short-circuit fashion. The expression x || y is evaluated as
follows:
1. Evaluate x.
2. If x is true return true.
3. Otherwise, if x is false evaluate y.
4. Return the value of y.
If the first operand of || is true then the evaluation of the second operand is skipped.
The following program (see Listing 3.6) illustrates the results of using the &, |, &&, and || operators.
LogicalListing 3.6: Logical.java—Using the Boolean and Short-Circuit Operators

class Logical {

static boolean sideEffect(boolean b) {
System.out.print("Side effect! ");
return b;

}

public static void main(String args[]) {
boolean t = true;
boolean f = false;
System.out.println(false & sideEffect(true));
System.out.println(false && sideEffect(true));
System.out.println(true | sideEffect(true));
System.out.println(true || sideEffect(true));

}

}
When you run the program, it produces the following results:
Side effect! false
false

- 47



Side effect! true
true

Assignment Operators

Java provides a full suite of assignment operators, including the basic = assignment operator and the C
op= style operators where op is a binary arithmetic operator. These operators are as follows:

.
x = y The variable x is assigned the value of y.
.
x += y The variable x is assigned the value of x + y.
.
x -= y The variable x is assigned the value of x - y.
.
x *= y The variable x is assigned the value of x * y.
.
x /= y The variable x is assigned the value of x / y.
.
x %= y The variable x is assigned the value of x % y.
.
x &= y The variable x is assigned the value of x & y.
.
x |= y The variable x is assigned the value of x | y.
.
x ^= y The variable x is assigned the value of x ^ y.
.
x <<= y The variable x is assigned the value of x <<= y.
.
x >>= y The variable x is assigned the value of x >>= y.
.
x >>>= y The variable x is assigned the value of x >>>= y.
With the exception of the = simple assignment operator and the += operator, all of the other above
operators are used with primitive types. Note that the &, |, and ^ operators can be used with both
Boolean and numeric arguments. The += operator may also be used with String objects.
The assignment operators of the form op= cast their result to the type of the left operand. For example,
if b is of type byte, b += 3, assigns (byte) (b + 3) to b. This is important because the value of b
is promoted to an int value before the addition takes place. The following program (Listing 3.7)
compiles without a compilation error:
Listing 3.7: Cast1.java—Casting and the += Operator
class Cast1 {

public static void main(String args[]) {
byte b = 0;
b += 3;
System.out.println(b);

}

}
Unlike the op= operators, the = operator does not perform an implicit cast. The following program
(Listing 3.8) results in a compilation error because casting is required to assign an int value to a bytevalue.

Listing 3.8: Cast2.java—Casting and the = Operator
class Cast2
{
public static void main(String args[])
{
byte b = 0;


- 48



b = b + 3;

System.out.println(b);
}

}
When the simple assignment operator is used with object references, a few rules apply:

.
If the type of the left operand is a class C, then the type of the right operand must be a
subclass of C or the null value.
.
If the type of the left operand is an interface I, the type of the right operand must be a
subinterface of I, or a class that implements I, or the null value.
The following section shows how casting can be used to change the type associated with the right
operand before an assignment is made.


There are two more points to cover about the assignment operator:

.
The value (and type) returned by an assignment is the value (and type) assigned to the left
operand.
.
The simple assignment operator is right associative. This means that a = b = c is
evaluated as a = (b = c). All other operators are left associative. For example, a + b +
c is evaluated as (a + b) + c.
The following program (see Listing 3.9) illustrates the above two rules. The statement i = j = k = lis evaluated as follows:

1.
The value of l (4) is assigned to k.
2.
The value of k = l (4) is assgined to j.
3.
The value of j = k = l (4) is assigned to i.
Listing 3.9: Assign.java—Associativity and the = Operator


class Assign {

public static void main(String args[]) {
int i = 1;
int j = 2;
int k = 3;
int l = 4;
i = j = k = l;
System.out.println(i);
System.out.println(j);
System.out.println(k);
System.out.println(l);

}
}

- 49



The Cast Operator

The cast operator (type) is used to convert numeric values from one numeric type to another or to
change an object reference to a compatible type.


Widening and Narrowing Conversions

A widening conversion is a conversion from a smaller numeric type to a larger numeric type. An
example of a widening conversion is when a byte value is promoted to an int value. A narrowing
conversion is a conversion from a larger numeric type to a smaller numeric type. A conversion from a
long value to a short value would be an example of a narrowing conversion. Narrowing conversions
require the use of the cast operator.


Casting can be used to enable numeric conversions that would normally be disallowed by the compiler.
For example, the following program (see Listing 3.10) assigns the value 123 to the b variable. Without
the (byte) cast operator, the compiler would generate an error message.

Listing 3.10: Cast3.java—Casting Numeric Values
class Cast3 {

public static void main(String args[]) {
double d = 123.456;
byte b;
b = (byte) d;
System.out.println(b);

}

}
When casting is used with object references, the following rules apply:

1.
A reference to any object can be cast into a reference to an object of class Object.
2.
A reference to an object can be cast into a reference to an object of class C', if the actual
class of the object is a subclass of C'.
3.
A reference to an object can be cast into a reference to an object of interface I, if the actual
class of the object implements I, if the object is of interface type I' and I' is a
subinterface of I, or if the object is an array type and I is the Cloneable interface.
4.
A reference to an object can be cast a reference to an object of an array type (with element
reference type T), if the object is of an array type (with element reference type T') such
that T' can be cast into T.
Let's examine each of the above rules.
The first rule is pretty simple. Any object reference can be cast to an Object object using the
(Object) cast operator.


- 50



Figure 3.7 summarizes the second rule. When an object is created, it is an object of some specific class
(referred to as the actual class in the rule). The object may be subsequently referenced by a superclass
reference or an interface reference. For example, a String object may be created and then referenced
as an Object object. Casting can be used to change the object's reference back to its original class
(for example, String).


Figure 3.7: Casting between classes.
The third rule covers casting to interfaces. If the actual class of an object implements the interface, the
object can be cast to that interface. For example, a Vector object can be cast to a List object, and a
List object can be cast to a Collection object. Because the array type implements the Cloneable
interface, any array can be cast into a Cloneable object.
Casting to array types is more complicated. In order to cast to an object reference to an array type
reference, the object must be an array of a component type that is compatible with the component type
of the array type reference. Figure 3.8 summarizes casting to array types.
As an example of object type casting, consider the following program (Listing 3.11). Without the
(String) cast operator, the result returned by v.elementAt(0) is an object of the Object class.
The compiler recognizes this inconsistency and generates an error message. When the (String) cast
operator is used, the compiler recognizes that you are casting the reference to an Object object into a
String object and proceeds with the compilation.

Listing 3.11: Cast4.java—Casting Object References


import java.util.*;

class Cast4 {

public static void main(String args[]) {
String s1 = "abc";
String s2 = "def";
Vector v = new Vector();
v.add(s1);
s2 = (String) v.elementAt(0);
System.out.println(s2);

- 51



}
}

The Ternary Operator

The ternary operator ? :, also referred to as the conditional operator, has three operands and takes the
following form:

operand1 ? operand2 : operand3
Figure 3.8: Casting to array types.

The first operand must be of boolean type. The first operand is evaluated and if true, the value of the
second operand is returned. In this case, evaluation of the third operand does not take place. If the
value of the first operand is false, evaluation of the second operand is skipped, and the value of the third
operand is returned. The Java compiler requires that the second and third operands be promotable
(numeric values) or castable (object references) to a common type.
For example, the program shown in Listing 3.12 produces the output 0xx3xx6xx9.

Listing 3.12: Ternary.java—Using the Ternary Operator
class Ternary {
public static void main(String args[]) {
for(int i=0;i<10;++i)
System.out.print((i%3==0)? ("" + i) : "x");
}

}
Operator Precedence and Order of Evaluation

The order in which expressions are evaluated determines the values they produce. In Java, the
operands of an expression are evaluated in a left-to-right fashion before any operations are performed.
The only exceptions to this are operations involving the logical short-circuit operators && and || and the
ternary operator. After evaluating the operands of an expression, the operators are applied according to
operator precedence and associativity. All binary operators are left associative except the = assignment
operator. Parentheses are used to alter the effects of precedence and associativity.
Figure 3.9 shows Java's operator precedence hierarchy. Operators at the top of the hierarchy take
precedence over lower level operators in the evaluation of an expression. Operators at the same level
are evaluated in the order they appear in an expression, according to their associativity.

- 52



Figure 3.9: Java's operator precedence hierarchy.
Use Figure 3.9 to evaluate a complex expression. Consider the program shown in Listing 3.13. It
displays the value abc9.

Listing 3.13: Precedence.java—Using the Operator Precedence to Evaluate Complex Expressions
class Precedence {

public static void main(String args[]) {
String s = "abc";
int x = 10;
boolean b = false;
s = s += x = x++ + 1 - 2 * 3 +

((Object) s instanceof String ? 4 << 5 / 6 & ++x:
7 ^ 8 % --x) | 9;
System.out.println(s);
}

}
The highest precedence operator is the postfix ++ operator. This increments the value of x to 11 but
returns the value of 10. Our expression reduces to

s = s += x = 10 + 1 - 2 * 3 + ((Object) s instanceof String ? 4 << 5 / 6 & ++x:

- 53



7 ^ 8 % --x) | 9;
Now the highest precedence operators is *. Applying this operator, reduce the expression to
s = s += x = 10 + 1 - 6 +
((Object) s instanceof String ? 4 << 5 / 6

& ++x: 7 ^ 8 % --x) | 9;
The highest precedence operators becomes the + and - operators. Applying these operators enables
us to reduce the expression to

s = s += x = 5 + ((Object) s instanceof String ? 4 << 5 / 6 & ++x:
7 ^ 8 % --x) | 9;

We must now evaluate the expression
(Object) s instanceof String ? 4 << 5 / 6 & ++x: 7 ^ 8 % --
x
and then plug it back in to the overall expression. Within this expression the (Object) cast operator has
the highest precedence. This causes s to be cast to an object of the Object class. (However,
s
remains fundamentally a String object.) We'll simplify the expression to


s instanceof String ? 4 << 5 / 6 & ++x: 7 ^ 8 % --
x
The ternary operator evaluates the operand to the left of the ? before selecting which operand 4 <<
5
/ 6 & ++x or 7 ^ 8 % --x to evaluate next. The expression s instanceof String evaluates to
true, and the overall expression simplifies to


4 << 5 / 6 & ++
x
The ++ operator is evaluated next. Because the value of xis now 11, it is incremented to 12 and the
expression simplifies to


4 << 5 / 6 & 12
The / is then evaluated, followed by << and then &. The expression is evaluated as follows:


4 << 0 & 12
4 & 12


Plugging this result back into the expression, you now have


s = s += x = 5 + 4 | 9;
Because + has a higher precedence than | the expression evaluates to
s = s += x = 9 | 9;


and then to


s = s += x = 9;
The value 9 is then assigned to x leaving
s = s += 9;


The value of s becomes "abc9", and the expression simplifies to
s = "abc9"
;


The above example is much more complex than any you'll see in the exam. If you can work your way
through this example, you should be able to tackle any exam question.


Chapter Summary

This chapter reviewed all of the Java operators and provided examples of their use. It covered operator
precedence and showed how it is used in expression evaluation. It also covered important points related
to casting and numeric promotion. You should now be prepared to test your knowledge of these
subjects. The following review questions and exam questions will let you know how well you understand
this material and will give you an idea of how you'll do on operator-specific exam questions. They'll also
indicate which material you need to study further.

Key Terms

.. Operator
.. Operand
- 54



.
Expression
.
Unary operator
.
Binary operator
.
Prefix operator
.
Postfix operator
.
Ternary operator
.
Numeric promotion
.
Casting
.
Overflow
.
Underflow
.
Precedence
.
Associativity
.
Order of evaluation
Review Questions

1.
What is the % operator?
2.
What is the difference between the prefix and postfix forms of the ++ operator?
3.
What are the legal operands of the instanceof operator?
4.
What is the difference between the Boolean & operator and the && operator?
5.
What is the difference between the >> and >>> operators?
6.
How is it possible for two String objects with identical values not to be equal under the
== operator?
7.
Is &&= a valid Java operator?
8.
Is the ternary operator written x : y ? z or x ? y : z ?
9.
Can a double value be cast to a byte?
10. Can a Byte object be cast to a double value?
11. Which arithmetic operations can result in the throwing of an ArithmeticException?
12. How is rounding performed under integer division?
13. What happens when you add a double value to a String?
14. How does Java handle integer overflows and underflows?
15. What factors determine the order of evaluation of an expression?
16. What is numeric promotion?
17. What is casting?
18. When can an object reference be cast to an interface reference?
19. What are order of precedence and associativity, and how are they used?
20. Which Java operator is right associative?
Exam Questions

1.
What is the value of 111 % 13?
A.
3
B.
5
C.
7
D.
9
2.
What is the value of 9 + 8 % 7 + 6?
A.
17
- 55



B. 16
C. 13
D. 4
3. What is the value of y after execution of the following statements?
4. int x = 5;
5. int y = 4;
y = x++
;
A. 4
B. 5
C. 6
D. 7
6. What is the value returned by "abcd" instanceof Object?
A. "abcd"
B. true
C. false
D. String
7. What is the value of 8 | 9 & 10 ^ 11?
A. 8
B. 9
C. 10
D. 11
8. What is the output displayed by the following program?
9. class Question {
10. public static void main(String[] args) {
11. int n = 7;
12. n <<= 3;
13. n = n & n + 1 | n + 2 ^ n + 3;
14. n >>= 2;
15. System.out.println(n);
16.
}
}
A. 0
B. -1
C. 14
D. 64
17. What is the value of -31 >>> 5 >> 5 >>> 5 >> 5 >>> 5 >> 5?
A. NaN
B. -1
C. 3
D. 1024
18. What is the value displayed by the following program?
19. class Question {
20. public static void main(String[] args) {
21. int x = 0;
22. boolean b1, b2, b3, b4;
23. b1 = b2 = b3 = b4 = true;
24. x = (b1 | b2 & b3 ^ b4) ? x++ : --x;
25. System.out.println(x);
26.
}
}
A. -1
- 56



B. 0
C. 1
D. 2
27. What line of output is displayed by the following program?
28. class Question {
29. static boolean sideEffect(boolean b) {
30. System.out.print(" side effect ");
31. return b;
32. }
33. public static void main(String[] args) {
34. boolean b1 = true;
35. boolean b2 = false;
36. if(b2 & sideEffect(b1)) System.out.println(1);
37. else if(b1 | sideEffect(b2)) System.out.println(2);
38.
}
}
A. 1
B. 2
C. side effect 1
D. side effect 2
E. side effect side effect 1
F. side effect side effect 2
39. What is the output displayed by the following program?
40. class Question {
41. public static void main(String[] args) {
42. String s1 = "ab";
43. String s2 = "abcd";
44. String s3 = "cd";
45. String s4 = s1 + s3;
46. s1 = s4;
47. System.out.print("s1 "+((s1 == s2)? "==" : "!=")+" s2");
48.
}
}
A. s1 == s2
B. s1 != s2
C. s1
D. s1 == "abcd"
49. Which statement (exactly one) is true about the following program?
50. class Question {
51. public static void main(String[] args) {
52. double d1 = 1.0;
53. double d2 = 0.0;
54. byte b = 1;
55. d1 = d1 / d2;
56. b = (byte) d1;
57. System.out.print(b);
- 57



58. }
}

A.
It results in the throwing of an ArithmeticException.
B.
It results in the throwing of a DivideByZeroException.
C.
It displays the value 1.5.
D.
It displays the value -1.
59. What is the result of the expression 5.4 + "3.2"?
A. The double value 8.6.
B. The String "8.6".
C. The long value 8.
D. The String "5.43.2".
60. What is the result of the following program?
61. class Question {
62. public static void main(String[] args) {
63. int i = 7;
64. int j = 8;
65. int n = (i | j) % (i & j);
66. System.out.print(n);
67. }
}

A.
0
B.
15
C. An ArithmeticException is thrown.
D.
-15
68. Suppose that classes X and Y are subclasses of Z and Z implements the W interface.
Which of the following are true?
A.
A reference to an object of class X can be cast to a reference to an object
of class Y.
B.
A reference to an object of class Y can be cast to a reference to an object
of class X.
C.
A reference to an object of class X can be cast to a reference to an object
of class Z.
D.
A reference to an object of class Y can be cast to a reference to an object
of class Z.
E.
A reference to an object of class X can be cast to a reference to an object
of interface W.
F.
A reference to an object of class Y can be cast to a reference to an object
of interface W.
G.
A reference to an object of class Z can be cast to a reference to an object
of interface W.
69. Which of the following are true?
A.
A reference to an array can be cast to a reference to an Object.
B.
A reference to an array can be cast to a reference to a Cloneable.
C.
A reference to an array can be cast to a reference to a String.
D.
None of the above.
Answers to Review Questions

1.
It is referred to as the modulo or remainder operator. It returns the remainder of dividing
the first operand by the second operand.
2.
The prefix form performs the increment operation and returns the value of the increment
operation. The postfix form returns the current value all of the expression and then
performs the increment operation on that value.
3.
The left operand is an object reference or null value and the right operand is a class,
interface, or array type.
- 58



4.
If an expression involving the Boolean & operator is evaluated, both operands are
evaluated. Then the & operator is applied to the operand. When an expression involving
the && operator is evaluated, the first operand is evaluated. If the first operand returns a
value of true then the second operand is evaluated. The && operator is then applied to
the first and second operands. If the first operand evaluates to false, the evaluation of
the second operand is skipped.
5.
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have
been shifted out.
6.
The == operator compares two objects to determine if they are the same object in
memory. It is possible for two String objects to have the same value, but be located in
different areas of memory.
7.
No, it is not.
8.
It is written x ? y : z.
9.
Yes, a double value can be cast to a byte.
10. No, an object cannot be cast to a primitive value.
11. Integer / and % can result in the throwing of an ArithmeticException.
12. The fractional part of the result is truncated. This is known as rounding toward zero.
13. The result is a String object.
14. It uses those low order bytes of the result that can fit into the size of the type allowed by
the operation.
15. The order of the evaluation of an expression is determined by the use of parentheses,
the operator precedence, and the operator associativity.
16. Numeric promotion is the conversion of a smaller numeric type to a larger numeric type,
so that integer and floating-point operations may take place. In numerical promotion,
byte, char, and short values are converted to int values. The int values are also
converted to long values, if necessary. The long and float values are converted to
double values, as required.
17. There are two types of casting, casting between primitive numeric types and casting
between object references. Casting between numeric types is used to convert larger
values, such as double values, to smaller values, such as byte values. Casting
between object references is used to refer to an object by a compatible class, interface,
or array type reference.
18. An object reference can be cast to an interface reference when the object implements
the referenced interface.
19. Order of precedence determines the order in which operators are evaluated in
expressions. Associativity determines whether an expression is evaluated left-to-right or
right-to-left.
20. The = operator is right associative.
Answers to Exam Questions

1.
C. 111 = 8 * 13 + 7.
2.
B. Order of precedence requires that the expression be evaluated as (9 + (8 % 7) +
6).
3.
B. The postfix operator returns the value of x before incrementing x.
4.
B. The String"abcd" is an instance of Object so the value of true is returned.
5.
D. Order of precedence requires the expression to be evaluated as (8 | ((9 & 10)
^ 11)).
6.
C. The variable n takes on the values 7, 56, 57, and then 14.
7.
C. Use the process of elimination to answer this question. The expression returns a valid
integer result, so answer A is eliminated. Because the first operation is an unsigned right
shift, the final value of the expression must be non-negative. This rules out answer B.
Because the original 32-bit value is shifted right 30 times, it would be impossible to
produce a number as large as 1024. This rules out answer D. The only answer left is
answer C.
8.
B. From the ternary expression, the value of xmust either be 0or -1. Because (b1 |
b2 & b3 ^ b4) evaluates as (b1 | (b2 & (b3 ^ b4)), the answer is 0.
- 59



9.
F. Because we are not using the logical short-circuit operators, the sideEffect()
method is invoked in both cases, resulting in " side effect side effect 2"
being displayed.
10. B. Because s1 and s2 refer to different objects, s1 != s2 is true.
11. D. Floating-point operations do not throw exceptions. This eliminates answers A and B.
It would be impossible for a byte value to be displayed as 1.5. The only answer left is
D.
12. D. The floating point value is converted to a String and is then appended to "3.2".
13. C. An ArithmeticException is thrown as the result of taking the remainder of a
number by 0.
14. C through G. References to X and Y objects can be cast to Z and W objects. References
to Z objects can be cast to W objects. However, references to X and Y objects may not
be cast to each other.
15. A and B. A and B hold for all array types. An array may never be cast to a String.

Go to Home Page