Java PDF
Java PDF
Java PDF
– Bitwise OR |
– Bitwise AND &
– Bitwise XOR ^
– Bitwise NOT ~
• The Left Shift (<<)
– shifts all of the bits in a value to the left a specified
number of times.
value << num
– For each shift left, the high-order bit is shifted out
(and lost), and a zero is brought in on the right.
– Left shifting a byte value
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
• Output
Original value of a: 64
i and b: 256 0
binary form
0010 0011 (35)
>>2
0000 1000 (8)
• When you are shifting right, the top (leftmost) bits
exposed by the right shift are filled in with the
previous contents of the top bit.
• This is called sign extension and serves to preserve
the sign of negative numbers when you shift them
right.
11111000 (–8)
>>1
11111100 (–4)
• Sometimes it is not desirable to sign-extend values
when you are shifting them to the right.
• The Unsigned Right Shift
– In case of working with pixel-based values and
graphics, you will generally want to shift a zero into
the high-order bit no matter what its initial value
was. This is known as an unsigned shift.
– To accomplish this, Java’s unsigned, shift-right
operator, >>> is used, which always shifts zeros into
the high-order bit.
eg) int a = -1;
a = a >>> 24;
11111111 11111111 11111111 11111111 (–1)
>>>24
00000000 00000000 00000000 11111111 (255)
• Bitwise Operator Assignments
– All of the binary bitwise operators have a
shorthand form similar to that of the algebraic
operators, which combines the assignment with
the bitwise operation.
– eg) a = a >> 4; a >>= 4;
a = a | b; a |= b;
3.Relational Operators
• The relational operators determine the
relationship that one operand has to the other.
• The outcome of these operations is a boolean value.
int a = 4;
int b = 1;
boolean c = a < b;
• In this case, the result of a<b (which is false) is stored in c.
• In C/C++, these types of statements are very common:
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not valid in Java.
• In Java, these statements must be written like this:
if(done == 0)) ... // This is Java-style.
if(done != 0) ...
• In Java, true and false are nonnumeric values which do not
relate to zero or nonzero.
4.Boolean Logical Operators
• The Boolean logical operators operate only on boolean
operands.
• The logical Boolean operators, &, |, and ^, operate
on boolean values in the same way that they operate
on the bits of an integer.
• The logical ! operator inverts the Boolean state:
!true == false and !false == true.
• Short-Circuit Logical Operators
– Java provides two interesting Boolean operators,
&&, ||, that are secondary versions of the
Boolean AND and OR operators and are knows as
short-circuit logical operators.
– The OR operator results in true when A is true, no
matter what B is.
– Similarly, the AND operator results in false when A
is false, no matter what B is.
– If the short-circuit operators || and &&, rather
than | and &, then Java will not evaluate the right-
hand operand when the outcome of the
expression can be determined by the left operand
alone.
• Eg) if (denom != 0 && num / denom > 10)
– Since the short-circuit form of AND (&&) is used,
there is no risk of causing a run-time exception when
denom is zero.
– when using &&, the right hand operand is not
evaluated.
– If & is used, then the right hand operand will also be
evaluated and that causes a run-time exception when
denom==0.
• It is standard practice to use the short-circuit
AND(&&) and OR(||) in cases involving boolean
logic and the logical AND(&) and OR(|)
exclusively for bitwise operations.
• The Assignment Operator
– The assignment operator is the single equal sign, =
var = expression;
– The = is an operator that yields the value of the
right-hand expression.
• The ? Operator
– Java includes a special ternary (three-way)
operator that can replace certain types of if-then-
else statements.
– 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.
• Eg) ratio = denom == 0 ? 0 : num / denom;
– If denom equals zero, then the expression between the
question mark (?) and colon (: ) is evaluated and used as the
value of the entire ? expression. ( then ratio = 0)
– If denom does not equal zero, then the expression after the
colon is evaluated and ratio is assigned the resulting value.
• Operator Precedence
• Paranthesis are used to alter the precedence
of an operation.
eg) a >> (b+3)
first adds 3 to b and then shifts right by that
result.
(a >> b) + 3
first shift right by b positions and then add
3 to that result.
• The square brackets provide array indexing.
• The dot operator is used to dereference
objects.
Control Statements
• Java’s program control statements can be put into the
following categories:
– Selection
– Iteration
– Jump
• Selection statements allow your program to choose
different paths of execution based upon the outcome
of an expression or the state of a variable.
• Iteration statements enable program execution to
repeat one or more statements.
• Jump statements allow your program to execute in a
nonlinear fashion.
1. Java’s Selection Statements
• Java supports two selection statements: if and switch.
• if statement
if (condition) statement1;
else statement2;
• Most often, the expression used to control the if will
involve the relational operators.
• However, It is possible to control the if using a single
boolean variable.
boolean dataAvailable;
// ...
if (dataAvailable)
ProcessData();
else
waitForMoreData();
• Nested ifs
– A nested if is an if statement that is the target of
another if or else.
– When you nest ifs, an else statement always refers
to the nearest if statement that is within the same
block as the else.
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100) // this if is
c = d;
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
• The if-else-if Ladder
– based upon a sequence of nested ifs
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
– The if statements are executed from the top down.
– As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of
the ladder is bypassed.
– If none of the conditions is true, then the final else statement
will be executed.
• switch statement
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
• Nested switch Statements
switch(count)
{
case 1:
switch(target) // nested switch
{
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
• 3 important features of switch statement
– The switch differs from the if in that switch can
only test for equality, whereas if can evaluate any
type of Boolean expression.
– No two case constants in the same switch can
have identical values.
– A switch statement is usually more efficient than a
set of nested ifs.
2. Java’s Iteration Statements
• while statement
while(condition)
{
// body of loop
}
– 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.
• do-while statement
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.
• for statement
for(initialization; condition; iteration)
{
// body
}
– When the loop first starts, the initialization portion of the
loop is executed.
– Next, condition is evaluated. This must be a Boolean
expression. 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. The loop
then iterates, first evaluating the conditional expression, then
executing the body of the loop, and then executing the
iteration expression with each pass.
– This process repeats until the controlling expression is false.
• Declaring Loop Control Variables Inside the for
Loop
– it is possible to declare the variable inside the
initialization portion of the for.
for(int n=10; n>0; n--)
– When you declare a variable inside a for loop, the
scope of that variable ends when the for
statement does.
– When the loop control variable will not be
needed elsewhere, it can be declared inside the
for.
• Using the Comma
– if you want to include more than one statement in
the initialization and iteration portions of the for
loop, then the comma separator is used.
for(a=1, b=4; a<b; a++, b--)
– Each statement is separated from the next by a
comma.
• for Loop Variations
– The for loop supports a number of variations that
increase its power and applicability.
– One of the most common variations involves the
conditional expression.
– the condition controlling the for can be any
Boolean expression.
boolean done = false;
for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}
– In this example, the for loop continues to run until the
boolean variable done is set to true.
• Another for loop variation is that, in a for loop, either
the initialization or the iteration expression or both
may be absent.
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
• one more for loop variation is that, we can
intentionally create an infinite loop by leaving
all 3 parts of the for empty.
for( ; ; ) {
// ...
}
• This loop will run forever, and are called
infinite loops with special termination
requirements.
3.Java’s Jump Statements
• Java supports three jump statements:
– break,
– continue, and
– return.
• These statements transfer control to another
part of your program.
(another way in Java Exception Handling)
• Using break
– In Java, the break statement has three uses.
• It terminates a statement sequence in a switch
statement.
• It can be used to exit a loop.
• It can be used as a “civilized” form of goto.
– Using break to Exit a Loop
• By using break, you can force immediate termination
of a loop, bypassing the conditional expression and any
remaining code in the body of the loop.
eg) if(i == 10) break; // terminate loop if i is 10
– Using break as a Form of Goto
• Java does not have a goto statement, because it provides
a way to branch in an arbitrary and unstructured manner.
• The goto can be useful when you are exiting from a
deeply nested set of loops.
• To handle such situations, Java defines an expanded form
of the break statement , called labeled break statement
by which you can break out of one or more blocks of
code.
• General form
break label;
• label is the name of a label that identifies a block of code.
• A label is any valid Java identifier followed by a colon.
• When this form of break executes, control is transferred
out of the named block of code.
• The labeled block of code must enclose the break
statement, but it does not need to be the immediately
enclosing block.
class Break
{
public static void main(String args[])
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the break.");
if(t) break second; // break out of second
block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
• Using continue
– To force an early iteration of a loop.
– In while and do-while loops, a continue
statement causes control to be transferred
directly to the conditional expression that
controls the loop.
– As with the break statement, continue may
specify a label to describe which enclosing loop
to continue.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(j > i)
{
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
• return statement
– The return statement is used to explicitly return
from a method.
– It causes program control to transfer back to the
caller of the method.
– The return statement immediately terminates
the method in which it is executed.
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
The Java Keywords
• There are 49 reserved keywords currently
defined in the Java language.
• These keywords cannot be used as names for
a variable, class, or method.
The Java Class Libraries
• The java built-in methods println() and print()
are members of the System class, which is a
class predefined by java that is automatically
included in your programs.
• The Java environment relies on several built-in
class libraries that contain many built-in
methods that provide support for such things
as I/O, string handling, networking, and
graphics.
• Java as a totality is a combination of the Java
language itself, plus its standard classes.
Arrays
• An array is a group of like-typed variables that are
referred to by a common name.
• A specific element in an array is accessed by its index.
• One-Dimensional Arrays
– A one-dimensional array is, essentially, a list of like-typed
variables.
– General form
type var-name[ ];
– type declares the base type of the array.
– The base type determines the data type of each element that
comprises the array.
– Eg) int month_days[];
• The value of month_days is set to null, which represents
an array with no value.
• To link month_days with an actual, physical array of
integers, you must allocate one using new and assign it
to month_days.
• new is a special operator that allocates memory.
• General form
array-var = new type[size];
• To use new to allocate an array, you must specify the
type and number of elements to allocate.
• Eg) month_days=new int[12];
• Obtaining an array is a two-step process.
– Declare a variable of the desired array type.
– allocate the memory that will hold the array, using
new, and assign it to the array variable.
• In Java all arrays are dynamically allocated.
• Once you have allocated an array, you can
access a specific element in the array by
specifying its index within square brackets.
month_days[1] = 28;
• All array indexes start at zero.
class Array {
public static void main(String args[]) {
String colors[];
colors=new String[7];
colors*0+=“violet”;
colors*1+=“Indigo”;
colors*2+=“Blue”;
colors*3+=“Green”;
colors*4+=“Yellow”;
colors*5+=“Orange”;
colors*6+=“Red”;
for(int i=0;i<7;i++){
System.out.println(“Rainbow Colours:”+colors*i+);
}
}
}
• Arrays can be initialized when they are declared.
• An array initializer is a list of comma-separated
expressions surrounded by curly braces.
• The commas separate the values of the array elements.
• Eg)
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
• The Java run-time system will check to be sure that all
array indexes are in the correct range.
• If elements outside the range of an array were tried to
be accessed, then a run-time error will be caused.
• C/C++ provide no run-time boundary checks.
Multidimensional Arrays
• In Java, multidimensional arrays are actually
arrays of arrays.
• To declare a multidimensional array variable,
specify each additional index using another
set of square brackets.
int twoD[][] = new int[4][5];