You are on page 1of 23

The following chapters are currently available:

• Table of Contents, etc.


• Chapter 1 The Context of Software Development
• Chapter 2 Values, Variables, and Types
• Chapter 3 Arithmetic Expressions
• Chapter 4 Objects: Packaging Computation
• Chapter 5 Boolean Expressions and Conditional Execution
• Chapter 6 More Complex Conditionals
• Chapter 7 Modeling Real Objects
• Chapter 8 Living with Java
• Chapter 9 Class Members
• Chapter 10 Composing Objects
• Chapter 11 Inheritance and Polymorphism
• Chapter 12 Simple Graphics Programming
• Chapter 13 Some Standard Java Classes
• Chapter 14 The Object Class
• Chapter 15 Software Testing
• Chapter 16 Using Inheritance and Polymorphism
• Chapter 17 Iteration
• Chapter 18 Examples using Iteration
• Chapter 19 Other Conditional and Iterative Statements
• Chapter 20 Arrays
• Chapter 21 Arrays as Objects
• Chapter 22 Working with Arrays
• Chapter 23 A Simple Database
• Chapter 24 Graphical Objects
• Chapter 25 Exceptions
• Bibliography, index

Operators
In Java, an expression carries out some operation or operations that are directed by a list of allowed operators. An
operator acts upon one, two or three operands. Here are some general properties of operators:
General Properties of Operators
They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or
ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its
arguments.
Operands
An operand can be:

• A numeric variable - integer, floating point or character


• Any primitive type variable - numeric and boolean
• Reference variable to an object
• A literal - numeric value, boolean value, or string.
• An array element, "a[2]"
• char primitive, which in numeric operations is treated as an unsigned two byte integer

The operator is unary if it acts on a single operand; binary if it requres two operands. The conditional operator is
the only ternary operator in Java.
Each operator places specific requirements on the operand types allowed. For example, the subtractive operator "- "
in x=a-b; requires that a and b variables be numeric types. The assignment operator "=" then requires that x also
be a numeric type. (If a and b were wider types than x, a casting operation would also be required.)
Returned Value
A value is "returned" at the completion of an operation. The following statements use the assignment operator "="
and the addition operator "+"
int x = 3;
int y = x+5;
and result in x holding the value 3 and y holding the value 8. The entire expression y= x+5 could be used in another
expression:
int x=3;
int y;
int z = (y=x+5) * 4;
which results in y holding 8 and z holding 32. The assignment operator "=" in the expression "y=x+5" produces a
new value for y and also returns the value of y to be used in the expression for z.
Effects on Operands
In most of the operations, the operands themselves are not changed. However, for some operators, the operand(s)
do undergo a change:
Assignment operators: "x=y" replaces the value of the first operand with that of the second. The other assignment
operators, "*=, +=, etc" will also replace the value of the first operand but only after using its initial value in the
particular operation indicated by the symbol before the = sign.
Increment & decrement operators: The operand is incremented or decremented, before or after the operand's
value is returned, depending on whether it is a pre- or post- increment of decrement.
If an operand is changed by the operation, note that if the statement holding that expression is processed again, e.g.
in a loop, the resulting value can be different for each pass.
Expression Evaluation
The operands of an operator are always evaluated left to right. For example, in
x = a + b;
the first "+" operator will determine the value of a and then b.
Do not get this rule confused with the precedence and associativity rules.
Precedence determines the order in which operators act in an expression of more than one operator. The table
below gives the rating for each operator, the higher number indicating higher precedence.
Associativity rules determine the grouping of operands and operators in an expression with more than one operator
of the same precedence.
For example, in the expression
x = a + b * c;
the first "+" operator still first determines its left operand ("a" in this case) and then its right operand. But in this
case the right operand consists of the expression "b*c". The multiplication operator "*" has a higher precedence
than the additive "+".
Precedence can be overridden with parentheses, e.g.
x = (a + b) * c;
will force the addition of b to a, and then this sum is multiplied by c.
Although the precedence ratings, which are similar to those in C/C++, were chosen for the most "natural" ordering
of the operator evaluations, it never hurts to use the parentheses if you are unsure of the precedence and don't have
the table handy.
When the operations in an expression all have the same precedence rating, the associativity rules determine the
order of the operations. For most operators, the evaluation is done left to right, e.g.
x = a + b - c;
Here, addition and subtraction have the same precedence rating and so a and b are added and then from this sum c
is subtracted. Again, parentheses can be used to overrule the default associativity, e.g.
x = a + (b - c);
However, the assignment and unary operators, are associated right to left, e.g.
x += y -= -~4;
is equivalent to
x += (y -= (-(~4)));
or in long hand,
int a = ~4;
a = -a;
y = y - a;
x = x + y;
Other Operator Tricks
Finally, here are some other miscellaneous notes about operators. As indicated in the last example above,
assignment operations can be chained:
x = y = z = 4;
with the evaluations proceeding right to left.
Assignments can be combined into other operations, to compact the code, e.g.
if( (x = 5) == b) y = 10;
which first sets x to 5, then returns that value for the test of b. You should not overuse this technique else it makes
the code unreadable. Occasionally, though, it can be a neat approach.
Tables of Java Operators
Assignment Operators
x operation= y
is equivalent to
x = x operation y
x and y must be numeric or char types except for "=", which allows x and y also to be object references. In this
case, x must be of the same type of class or interface as y. If mixed floating-point and integer types, the rules for
mixed types in expressions apply.

Assignment operator.
x = y;
=
y is evaluated and x set to this value.
The value of x is then returned.
Arithmetic operation and then assignment, e.g.
x += y;
+=, -=, *=, /=, %=
is equivalent to
x = x + y;
Bitwise operation and then assignment, e.g.
x &= y;
&=, |=, ^=
is equivalent to
x = x & y;
Shift operations and then assignment, e.g.
x <<= n;
<<=, >>=, >>>=
is equivalent to
x = x << n;

Arithmetic Operators
x and y are numeric or char types. If mixed floating-point and integer types, then floating-point arithmetic used
and a floating-point value returned. If mixed integer types, the wider type is returned. If double and float mixed,
double is returned.
x+y Addition
x-y Subtraction
x*y Multiplication
Division
x/y If FP arithmetic and y = 0.0, then infinity returned if x is not zero, NaN if x is zero.
ArthmeticException thrown if x & y are integer types and y is zero.
Modulo - remainder of x/y returned.
If FP arithmetic and y = 0.0 or infinity,
x%y
then NaN returned
ArthmeticException thrown if x & y are integer types and y is zero.
Unary minus
-x
Negation of x value
Increment & Decrement Operators
x and y are numeric (FP & integer) or char types.
Post-increment : add 1 to the value.
The value is returned before the increment is made, e.g.
x++ x = 1;
y = x++;
Then y will hold 1 and x will hold 2
Post-decrement : subtract 1 from the value.
The value is returned before the decrement is made, e.g. :
x-- x = 1;
y = x--;
Then y will hold 1 and x will hold 0.
Pre-increment : add 1 to the value.
The value is returned after the increment is made, e.g.
++x x = 1;
y = ++x;
Then y will hold 2 and x will hold 2.
Pre-decrement : subtract 1 from the value.
The value is returned after the decrement is made, e.g.
--x x = 1;
y = --x;
Then y will hold 0 and x will hold 0.

Boolean Operators
x and y are boolean types. x and y can be expressions that result in a boolean value.
Result is a boolean true or false value.
If both x and y are true, result is true.
x && y Conditional
If either x or y are false, the result is false
AND
If x is false, y is not evaluated.
If both x and y are true,the result is true.
x & y Boolean
If either x or y are false, the result is false
AND
Both x and y are evaluated before the test.

x || y Conditional If either x or y are true, the result is true.


OR If x is true, y is not evaluated.

x | y Boolean If either x or y are true, the result is true.


OR Both x & y are evaluated before the test.

!x Boolean If x is true, the result is false.


NOT If x is false, the result is true.
If x is true and y is false, the result is true.
x ^ y Boolean If x is false and y is true, the result is true.
XOR Otherwise, the result is false.
Both x and y are evaluated before the test.
Comparison Operators
x and y are numeric or char types only except for "==" and "!=" operators, which can also compare references.
If mixed types, then the narrower type converted to wider type. Returned value is boolean true or false.
x < y Is x less than y ?
x <= y Is x less than or equal to y ?
x > y Is x greater than y ?
x >= y Is x greater than or equal to y ?
x == y Is x equal to y ?
x != y Is x not equal to y ?

Bitwise Operators
x and y are integers. If mixed integer types, such as int and long, the result will be of the wider type.

Note: Operations on byte and short types may give unexpected results since operands are promoted to integers
during intermediate operations. For example,
byte x = (byte)0xFF;
x >>>= 1;
will result in 0xFF in x rather than 0x7F. That is because the operation is carried out on a signed integer rather
than simply on 8 bits. Here the signed byte is promoted to the signed integer 0xFFFFFFFF.

Use of an integer would go as follows:


int i = 0xFF;
i >>>= 1;
This results in 0x7F in the variable i.
~x Compliment Flip each bit, ones to zeros, zeros to ones
x&y AND AND each bit a with corresponding bit in b
x|y OR OR each bit in a with corresponding bit in b
x^y XOR XOR each bit in x with corresponding bit in y
Shift x to the left by y bits. High order bits lost.
x << y Shift left
Zero bits fill in right bits.
Shift x to the right by y bits. Low order bits lost.
Shift Right -
x >> y Same bit value as sign (0 for positive numbers, 1 for negative) fills in
Signed
the left bits.
Shift Right - Shift x to the right by y bits. Low order bits lost.
x >>> y
Unsigned Zeros fill in left bits regardless of sign.

Class and Object Operators


The first operand must be an object reference.
c is the name of a class or interface.
Class Test If x is an instance of type c or a subclass of c, then true returned.
x instanceof c
Operator If x is an instance of interface type c or a sub-interface, then true is
returned.
Otherwise, false is returned.
Class
new c(args) Create an instance of class c using constructor c(args)
Instantiation
Access a method or field of a class or object :
Class Member
"." o.f - field access for object o
Access
o.m() - method access for object o
Parentheses after a method name invokes
Method (i.e. calls) the code for the method, e.g.
()
Invocation o.m()
o.m(x,y)
Treat an object as the type of class or interface c:
Object
(c) c x=(c)y;
Cast
Treat y as an instance of class or interface c
This binary operator will concatenate one string to another. E.g.
String str1 = "abc";
String str2 = "def";
String str3 = str1 + str2
results in str3 holding "abcdef".
String
+ For mixed operands, if either a or b in (a + b) is a string, concatenation
Concatenation
to a string will occur. Primitives will be converted to strings and the
toString() methods of objects will be called.
(This is the only case of operator overloading in Java.)
Note that the equivalence operator "+=" will also perform string
concatenation.
In Java, arrays are classes. However, the bracket operators work
essentially the same as in the C/C++.
To access a given element of an array, place the number of the element
as an int value (long values cannot be used in Java arrays) into the
Array Element
[] brackets, e.g.
Access
float a = b[3];
int n = 5;
char c=c[n];
where b is a float array and c is a char array.

Other Operators

The first operand - boolean - is a boolean variable or expression.


Conditional First this boolean operand is evaluated. If it is true then the second operator
x=boolean?y:x evaluated and x is set to that value.
Operator If the boolean operator is false, then the third operand is evaluated and x is
set to that value.
To assign a value of one primitive numeric type a more narrow type, e.g.
long to int, an explicit cast operation is required, e.g.
(primitive type) Type Cast
long a = 5;
int b = (int)a;

Operator Precedence
The larger the number, the higher the precedence.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
= ?: || && | ^ & == < << + * new ++x .
*= != <= >> - / (type) --x []
/= > >>> % +x (args)
%= >= -x x++
+= ~ x--
-= !
<<=
>>=
>>>=
&=
^=
|=

Notes:
 (type) refers to the casting operator
 "." is the object member access operator
 [] is the array access operator
 (args) indicates the invocation of a method.
 In column 11, the + and - refer to binary addition and subtraction. Also, the + refers tothe string append
operator. Whereas in column 14, the + & - refer to the unary operations +x and -x specify the sign of
the value.
 |, ^, and & refer to both the bitwise and boolean operators.

Operator Associative
The following operators have Right to Left associativity. All other operators (see precedence table above) are
evaluated left to right.
= ?:
*= new
/= (type cast)
%= ++x
+= --x
-= +x
<<= -x
>>= ~
>>>= !
&=
^=
|=

The Remainder or Modulus Operator in Java


Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or
remainder operator. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10
divided by 3 leaves a remainder of 1. You can use % just as you might use any other more common operator like +
or -.
class Remainder {

public static void main (String args[]) {

int i = 10;
int j = 3;
System.out.println("i is " + i);
System.out.println("j is " + j);

int k = i % j;
System.out.println("i%j is " + k);
}
}
Here's the output:
% javac Remainder.java
% java Remainder
i is 10
j is 3
i%j is 1
Perhaps surprisingly the remainder operator can be used with floating point values as well. It's surprising because
you don't normally think of real number division as producing remainders. However there are rare times when it's
useful to ask exactly how many times does 1.5 go into 5.5 and what's left over? The answer is that 1.5 goes into 5.5
three times with one left over, and it's that one which is the result of 5.5 % 1.5 in Java.

Keywords
There are certain words with a specific meaning in java, which tell (help) the compiler what the program is
supposed to do. These Keywords cannot be used as variable names, class names, or method names.
Keywords in java are case sensitive, all characters being lower case.
Keywords are reserved words that are predefined in the language; see the table below. All the keywords are
in lowercase.

Keyword Purpose
boolean declares a boolean variable or return type
byte declares a byte variable or return type
char declares a character variable or return type
double declares a double variable or return type
float declares a floating point variable or return type
short declares a short integer variable or return type
void declare that a method does not return a value
int declares an integer variable or return type
long declares a long integer variable or return type
while begins a while loop
for begins a for loop
do begins a do while loop
switch tests for the truth of various possible cases
break prematurely exits a loop
continue prematurely return to the beginning of a loop
case one case in a switch statement
default default action for a switch statement
if execute statements if the condition is true
else signals the code to be executed if an if statement is not true
try attempt an operation that may throw an exception
catch handle an exception
finally declares a block of code guaranteed to be executed
class signals the beginning of a class definition
abstract declares that a class or method is abstract
extends specifies the class which this class is a subclass of
final declares that a class may not be subclassed or that a field or method may not be overridden
implements declares that this class implements the given interface
import permit access to a class or group of classes in a package
instanceof tests whether an object is an instanceof a class
interface signals the beginning of an interface definition
native declares that a method is implemented in native code
new allocates a new object
package defines the package in which this source code file belongs
private declares a method or member variable to be private
protected declares a class, method or member variable to be protected
public declares a class, method or member variable to be public
return returns a value from a method
static declares that a field or a method belongs to a class rather than an object
super a reference to the parent of the current object
synchronize
d Indicates that a section of code is not thread-safe
this a reference to the current object
throw throw an exception
throws declares the exceptions thrown by a method
transient This field should not be serialized
volatile Warns the compiler that a variable changes asynchron

Comments
Comments are descriptions that are added to a program to make code easier to understand. The compiler
ignores comments and hence its only for documentation of the program.
Java supports three comment styles.
1. Block style comments begin with /* and terminate with */ that spans multiple lines.
2. Line style comments begin with // and terminate at the end of the line. (Shown in the above program)
3. Documentation style comments begin with /** and terminate with */ that spans multiple lines. They
are generally created using the automatic documentation generation tool

Variable, Identifiers and Data Types


Variables are used for data that change during program execution. All variables have a name, a type, and a
scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique
within a scope of the Java program. Variables have a data type, that indicates the kind of value they can
store. Variables declared inside of a block or method are called local variables; They are not automatically
initialized. The compiler will generate an error as a result of the attempt to access the local variables before a
value has been assigned.
public class localVariableEx {
public static int a;
public static void main(String[] args) {
int b;
System.out.println(”a : “+a);
System.out.println(”b : “+b); //Compilation error
}}
Note in the above example, a compilation error results in where the variable is tried to be accessed and not
at the place where its declared without any value.

Primitive Data Types in Java


The data type indicates the attributes of the variable, such as the range of values that can be stored and the
operators that can be used to manipulate the variable. Java has four main primitive data types built into the
language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data types.
 Integer: byte, short, int, and long.
 Floating Point: float and double
 Character: char
 Boolean: variable with a value of true or false.
The following chart summarizes the default values for the java built in data types. Java's primitive data types
are very similar to those of C. They include boolean, byte, short, int, long, float, double, and char. The Boolean type
has been added. However the implementation of the data types has been substantially cleaned up in several ways.

1. Where C and C++ leave a number of issues to be machine and compiler dependent (for instance the size of
an int) Java specifies everything.
2. Java prevents casting between arbitrary variables. Only casts between numeric variables and between sub
and superclasses of the same object are allowed.
3. All numeric variables in Java are signed.

sizeof isn't necessary in Java because all sizes are precisely defined. For instance, an int is always 4 bytes. This may
not seem to be adequate when dealing with objects that aren't base data types. However even if you did know the
size of a particular object, you couldn't do anything with it anyway. You cannot convert an arbitrary object into
bytes and back again.
boolean
1-bit. May take on the values true and false only.
true and false are defined constants of the language and are not the same as True and
False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans
may not be cast into any other type of variable nor may any other variable be cast
into a boolean.
byte
1 signed byte (two's complement). Covers values from -128 to 127.
short
2 bytes, signed (two's complement), -32,768 to 32,767
int
4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all
numeric types ints may be cast into other numeric types (byte, short, long, float,
double). When lossy casts are done (e.g. int to byte) the conversion is done modulo
the length of the smaller type.
long
8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807.
float
4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to
3.40282346638528860e+38 (positive or negative).
Like all numeric types floats may be cast into other numeric types (byte, short, long, int,
double). When lossy casts to integer types are done (e.g. float to short) the fractional
part is truncated and the conversion is done modulo the length of the smaller type.
double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d
(positive or negative).
char
2 bytes, unsigned, Unicode, 0 to 65,535
Chars are not the same as bytes, ints, shorts or Strings.
Classes
A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An
object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to
describe the behavior of an object. Methods are nothing but members of a class that provide a service for an
object or perform some business logic.

Objects
An object is an instance of a class created using a new operator. The new operator returns a reference to a
new instance of a class. This reference can be assigned to a reference variable of the class. The process of
creating objects from a class is called instantiation. An object reference provides a handle to an object that is
created and stored in memory. In Java, objects can only be manipulated via references, which can be stored
in variables.

Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class
implements an interface, it promises to implement all of the methods declared in that interface.

Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables which
represent an object’s state. The methods of an object define its behaviour called instance methods. Instance
variables and instance methods, which belong to objects, are collectively called instance members. The dot ‘.’
notation with a object reference is used to access Instance Members.

Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static
variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and
static methods are collectively known as static members, and are declared with a keyword static. Static
members in the class can be accessed either by using the class name or by using the object reference, but
instance members can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed above.
/** Comment
* Displays “Hello World!” to the standard output.
*/
public class HelloWorld {
String output = “”;
static HelloWorld helloObj; //Line 1

public HelloWorld(){
output = “Hello World”;
}

public String printMessage(){


return output;
}

public static void main (String args[]) {


helloObj = new HelloWorld(); //Line 2
System.out.println(helloObj.printMessage());
}
}
White Space
White space consists mostly of the space character that you produce by hitting the space bar on your keyboard and
that is commonly used to separate words in sentences. There are four other white space characters in Java, the
horizontal tab, the form feed, the carriage return, and the linefeed. Depending on your platform, when you hit the
return or enter key, you get either a carriage return (the Mac), a linefeed (Unix) or both (DOS, Windows, VMS).
This produces a hard line break in the source code text.
Outside of String literals Java treats all white space and runs of white space (more than one white space character in
immediate succession) the same. It's used to separate tokens, and one space is as good as seven spaces, a tab and
two carriage returns. Exactly which white space characters you use is primarily a result of what's convenient for
human beings reading the code. The compiler doesn't care.
Inside String and character literals the only white space permitted is the space character. Carriage returns, tabs, line
feeds and form feeds must be inserted with special escape sequences like \r, \t, \f, and \n. You cannot break a String
across a line like this:
String poem = "Mary had a little lamb whose fleece was white as snow and everywhere that Mary went the lamb
was sure to go.";
Instead you must use \n and the string concatenation operator, +, like this:
String poem = "Mary had a little lamb\n" + "whose fleece was white as snow\n" + "and everywhere that Mary
went\n" + "the lamb was sure to go.";
Note that you can break a statement across multiple lines, you just can't break a String literal.
Also note that \n only works on Unix. You should probably use System.getProperty("line.separator") instead to
return the proper line separator string for the platform your program is running on.
Java does not have all the escape sequences C has. Besides those already mentioned it has only \b for backspace, \\
for the backslash character itself.
There are also \u escapes that let you include any Unicode character.

Separators in Java
Separators help define the structure of a program. The separators used in HelloWorld are parentheses, ( ), braces,{},
the period, ., and the semicolon, ;. The table lists the six Java separators.
Separator Purpose
Encloses arguments in method definitions and calling; adjusts precedence in arithmetic expressions;
()
surrounds cast types and delimits test expressions in flow control statements
{} defines blocks of code and automatically initializes arrays
[] declares array types and dereferences array values
; terminates statements
separates successive identifiers in variable declarations; chains statements in the test, expression of a for
,
loop
. Selects a field or method from an object; separates package names from sub-package and class names
: Used after loop labels
Java Flow Control
 if
 else
 else if
 while
 for
 do while
 switch case
 break
 continue
The if-then and if-then-else Statements
The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a
certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow
the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible
implementation of the applyBrakes method could be as follows:

void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must be moving
currentSpeed--; // the "then" clause: decrease current speed
}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-
then statement.

In addition, the opening and closing braces are optional, provided that the "then"
clause contains only one statement:
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more
brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to
add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong
results.

The if-then-else Statement


The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.
You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are
applied when the bicycle is not in motion. In this case, the action is to simply print an error message
stating that the bicycle has already stopped.

void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test
score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {

int testscore = 76;


char grade;

if (testscore >= 90) {


grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is:

Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are
executed (grade = 'C';) and the remaining conditions are not evaluated

The switch Statement


Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch
works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in
Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and
Integer (discussed in Simple Data Objects ).
The following program, SwitchDemo, declares an int named month whose value represents a month out of the year.
The program displays the name of the month, based on the value of month, using the switch statement.

class SwitchDemo {
public static void main(String[] args) {

int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
In this case, "August" is printed to standard output.
The body of a switch statement is known as a switch block. Any statement immediately contained by the switch
block may be labeled with one or more case or default labels. The switch statement evaluates its expression and
executes the appropriate case.
Of course, you could also implement the same thing with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call. You can decide
which one to use based on readability and other factors. An if-then-else statement can be used to make decisions
based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single
integer or enumerated value.
Another point of interest is the break statement after each case. Each break statement terminates the enclosing
switch statement. Control flow continues with the first statement following the switch block. The break statements
are necessary because without them, case statements fall through; that is, without an explicit break, control will
flow sequentially through subsequent case statements. The following program, SwitchDemo2, illustrates why it
might be useful to have case statements fall through:

class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
This is the output from the program.
Number of Days = 29
Technically, the final break is not required because flow would fall out of the switch statement anyway. However,
we recommend using a break so that modifying the code is easier and less error-prone. The default section handles
all values that aren't explicitly handled by one of the case sections. The char data type in Java
The while and do-while Statements
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be
expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true,
the while statement executes the statement(s) in the while block. The while statement continues testing the
expression and executing its block until the expression evaluates to false. Using the while statement to print the
values from 1 through 10 can be accomplished as in the following While program:

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the
following Do-While program:

class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for
loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of
the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
• The initialization expression initializes the loop; it's executed once, as the loop begins.
• When the termination expression evaluates to false, the loop terminates.

The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this
expression to increment or decrement a value.
The following program ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to
standard output:

class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from
its declaration to the end of the block governed by the for statement, so it can be used in the termination and
increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best
to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops;
declaring them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
for ( ; ; ) { // infinite loop
// Your code goes here
}
The for statement also has another form designed for iteration through Collections and arrays This form is
sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to
read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:

class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array. The output from this program is
the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Multiple Initializes and Incriminators
Sometimes it's necessary to initialize several variables before beginning a for loop. Similarly you may want to
increment more than one variable. Java lets you do this by placing a comma between the different initializers and
incrementers like this:
for (int i = 1, j = 100; i < 100; i = i+1, j = j-1) {
System.out.println(i + j);
}
You can't, however, include multiple test conditions, at least not with commas. The following line is illegal and will
generate a compiler error.
for (int i = 1, j = 100; i <= 100, j > 0; i = i-1, j = j-1) {
To include multiple tests you need to use the boolean logic operators && and || which will be discussed later.
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion
of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as
shown in the following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {

int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,


2000, 8, 622, 127 };
int searchfor = 12;

int i;
boolean foundIt = false;

for (i = 0; i < arrayOfInts.length; i++) {


if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}

if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for
loop when that value is found. Control flow then transfers to the print statement at the end of the program. This
program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a
labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to the
previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is
found, a labeled break terminates the outer for loop (labeled "search"):

class BreakWithLabelDemo {
public static void main(String[] args) {

int[][] arrayOfInts = { { 32, 87, 3, 589 },


{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;

int i;
int j = 0;
boolean foundIt = false;

search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}

if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control
flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips
to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following
program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current
character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a
"p", the program increments the letter count.

class ContinueDemo {
public static void main(String[] args) {

String searchMe = "peter piper picked a peck of pickled peppers";


int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {


//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;

//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When you run the program
again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The
following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within
another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string
being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip
an iteration in the outer loop.

class ContinueWithLabelDemo {
public static void main(String[] args) {

String searchMe = "Look for a substring in me";


String substring = "sub";
boolean foundIt = false;

int max = searchMe.length() - substring.length();

test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}
Here is the output from this program.
Found it
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current method,
and control flow returns to where the method was invoked. The return statement has two forms: one that returns a
value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after
the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value. When a method is
declared void, use the form of return that doesn't return a value.
return;

Escape sequences
A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. A char
literal is a single one character enclosed in single quote marks like this
char myCharacter = 'g';
Some characters are hard to type. For these Java provides escape sequences. This is a backslash followed by an
alphanumeric code. For instance '\n' is the newline character. '\t' is the tab character. '\\' is the backslash itself. The
following escape sequences are defined:
\b Backspace
\t Tab
\n Linefeed
\f form feed
\r Carriage return
\" Double quote, "
\' Single quote, '
\\ Backslash, \
The double quote escape sequence is used mainly inside strings where it would otherwise terminate the string. For
instance
System.out.println("And then Jim said, \"Who's at the door?\"");
It isn't necessary to escape the double quote inside single quotes. The following line is legal in Java
char doublequote = '"';
 Java is a true OO language and therefore the underlying structure of all Java programs is classes.
 Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and
“behaviour” of the basic program components known as objects.
 Classes create objects and objects use methods to communicate between them. They provide a convenient
method for packaging a group of logically related data items and functions that work on them.
A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore
important to understand how the fields and methods are defined in a class and how they are used to build a Java
program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.
Class
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.

 The basic syntax for a class definition:


class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}

Class vs. Object

1. A piece of the program’s source code 1. An entity in a running program

2. Written by a programmer 2. Created when the program is running (by the main
method or a constructor or another method)
3. Specifies the structure (the number and
types) of its objects’ attributes — the same 3. Holds specific values of attributes; these values can
for all of its objects change while the program is running

4. Specifies the possible behaviors of its 4. Behaves appropriately when called upon
objects.
5.
5.

You might also like