Java Programming4
Java Programming4
Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
The operands of the arithmetic operators must be of a numeric type. You cannot
use them on boolean types, but you can use them on char types, since the char type in Java is,
essentially, a subset of int.
The Bitwise Operators
Java defines several bitwise operators which can be applied to the integer types, long,
int, short, char, and byte. These operators act upon the individual bits of their operands.
They are summarized in the following table:
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are
shown here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
The outcome of these operations is a boolean value. The relational operators are
most frequently used in the expressions that control the if statement and the various
loop statements.
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types ofif-
then-else statements. This operator is the ?, and it works in Java much like it doesin C, C++, and
C#. It can seem somewhat confusing at first, but the ? can be used very effectively once
mastered. The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required to
return the samevoidtype,. which can’t be
CONTROL STATEMENTS
if
The if statement was introduced in Chapter 2. It is examined in detail here. The if statement is Java’s
conditionalprogrambranchexecution state through two different paths. Here is the general form of the if
statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block). The condition is any expression that returns a boolean value. The
else clause is optional.
int a,
b; // ...
if(a < b) a = 0;
else b = 0;
switch
The switch statement is Java’s multiway branch dispatch execution to different parts of your code
based on the value of an expression. As such, it
often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression)
{ case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified
in the case statements must be of a type compatible with the expression. Each case
value must be a unique literal (that is, it must be a constant, not a variable). Duplicate
case values are not allowed
Iteration Statements
Java’s iterationfor,while, andstatementsdo-while.Thesestatementsarecreate what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met. As you will see, Java has a loop to fit any
programming need.
While
The while loop is Java’sfundamentalloopingmoststatement. It repeats a statement or
block while its controlling expression is true. Here is its general form:
While (condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as
the conditional expression is true. When condition becomes false, control passes to the next line
of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated.
do-while
As you just saw, if the conditional expression controlling a while loop is initially false,
then the body of the loop will not be executed at all. However, sometimes it is desirable to
execute the body of a while loop at least once, even if the conditional expression is false to begin
with.
Systex:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the loop will
repeat. Otherwise, the loop terminates.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " +
n); n--;
} while(n > 0);
}
}
For
You were introduced to a simple form of the for loop in Chapter 2. As you will see, it is a
powerful and versatile construct. Here is the general form of the for statement:
for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows. When the loop first starts, the initialization portion of the loop
is executed. Generally, this is an expression that sets the value of the loopcontrol variable, which
acts as a counter that controls the loop.. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If this expression is
true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration
portion of the loop is executed. This is usually an expression that increments or decrements the
loop control variable.
// Demonstrate the for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be
used as a ―civilized‖ form of goto. The last
Return
The last control statement is return. The return statement is used to explicitly return
from a method. That is, it causes program control to transfer back to the caller of the method. As
such, it is categorized as a jump statement. Although a full discussion of return must wait until
methods are discussed in Chapter 7, a brief look at return is presented here.
As you can see, the final println( ) statement is not executed. As soon as return
is executed, control passes back to the caller.
Type Conversion and Casting
If you have previous programming experience, then you already know that it is fairly common to
assign a value of one type to a variable of another type. If the two types are compatible, then
Java will perform the conversion automatically. For example, it is always possible to assign an
int value to a long variable. However, not all types are compatible, and thus, not all type
conversions are implicitly allowed.
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the sou
When these two conditions are met, a widening conversion takes place. For example, the
int type is always large enough to hold all valid byte values, so no explicit cast statement is
required.
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. For
example, the following fragment casts an int to a byte. If the integer’s valu than the range of a byte, it will be
reduced modulo (the remainder of an integer
division by the) byte’s range.
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. As you know, integers do not have fractional components.Thus, when a
floating-point value is assigned to an integer type, the fractional component is lost. For example,
if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have
been truncated. Of course, if the size of the whole number component is too large to fit into the
target integer type, then that value will be
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to
byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to
int."); i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to
byte."); b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
Access Control
As you know, encapsulation links data with the code that manipulates it. However,
encapsulation provides another important attribute: access control.
How a member can be accessed is determined by the access specifier that modifies its
declaration. Java supplies a rich set of access specifiers. Some aspects of access control are
related mostly to inheritance or packages. (A package is, essentially, a grouping of classes.)
These parts of Java’s access control mechanism examining access control as it applies to a
single class. Once you understand the fundamentals of access control, the rest willpublic,
privatebe, andeasyprotected. . Java’s
Java also defines a
default access level. protected applies only when inheritance is involved. The other
access specifiers are described next.
Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current object. That
is, this is always a reference to the object on which the method was invoked. You can use this
anywhere a reference to an object of the cur what this refers to, consider the following version of Box( ):
As you know, it is illegal in Java to declare two local variables with the same name inside
the same or enclosing scopes. Interestingly, you can have local variables,
including formal parameters to methods, which instance variables. However, when a local variable has the same
name as an instance
variable, the local variable hides the instance variable.
Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation. In some languages, such as C++, dynamically allocated objects must
be manually released by use of a delete operator. Java takes a different approach; it
handles deallocation for you automatically. The technique that accomplishes this is
Called garbage collection. It works like this: when no references to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
Furthermore, different Java run-time implementations will take varying approaches to garbage
collection, but for the most part, you should not have to think about it while writing your
programs.
Overloading methods and constructors
Overloading Methods
In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the
methods are said to be overloaded, and the process is referred to as
method overloading. Method overloading is one of the ways that Java implements
polymorphism.
// Demonstrate method
overloading. class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer
parameter. void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) { System.out.println("a
and b: " + a + " " + b);
}
// overload test for a double
parameter double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new
OverloadDemo(); double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
This program generates the following
output: No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
As you can see, test( ) is overloaded four times.