109
MPL Week #02 Primitive Data Types Comments The for Statement The if Statement The while and do while Statements The switch Statement The break Statement The continue Statement Operators Casts and Conversions Keywords

MPL Week #02 Primitive Data Types Comments The for Statement The if Statement The while and do while Statements The switch Statement The

Embed Size (px)

Citation preview

MPL Week #02Primitive Data TypesCommentsThe for StatementThe if Statement The while and do while Statements The switch Statement The break StatementThe continue Statement OperatorsCasts and Conversions Keywords

Strong Typing

Java is a strongly-typed language:a) every variable and expression has a typeb) every type is strictly definedc) all assignments are checked for type-compatibilityd) no automatic conversion of non-compatible, conflicting typese) Java compiler type-checks all expressions and parametersf) any typing errors must be corrected for compilation to succeed

Simple TypesJava defines eight simple types:

1)byte

2)short

3)int

4)long

5)float

6)double

7)char

8)boolean

– 8-bit integer type

– 16-bit integer type

– 32-bit integer type

– 64-bit integer type

– 32-bit floating-point type

– 64-bit floating-point type

– symbols in a character set

– logical values true and false

Simple Types• The simple types represent single values not complex objects.

Although Java is otherwise completely object-oriented, the simple types are

not. • The reason for this is efficiency. • Making the simple types into objects would have degraded

performance too much.• Integers: • Java defines four integer types: byte, short, int, and long. All

of these are signed, positive and negative values. • Java does not support unsigned, positive only integers.• Many other computer languages, including C/C++, support

both signed and unsigned integers.

Simple Type: byte8-bit integer type.

Range: -128 to 127.

Example:byte b = -15;

Usage: particularly when working with data streams.

Simple Type: short16-bit integer type.

Range: -32768 to 32767.

Example:short c = 1000;

Usage: probably the least used simple type.

Simple Type: int32-bit integer type.

Range: -2147483648 to 2147483647.

Example:int b = -50000;

Usage:1) Most common integer type.2) Typically used to control loops and to index arrays.3) Expressions involving the byte, short and int values are promoted

to int before calculation.

Simple Type: long64-bit integer type.

Range: -9223372036854775808 to 9223372036854775807.

Example:long l = 10000000000000000;

Usage:1) useful when int type is not large enough to hold the desired value

Example: long// compute the light travel distance

class Light {

public static void main(String args[]) {

int lightspeed = 186000;

long days = = 1000;

long seconds = days * 24 * 60 * 60;

long distance = lightspeed * seconds;

System.out.print(“\n " + days);

System.out.print(" light will travel about");

System.out.println(distance + " miles.");

}

}

Output:In 1000 days light will travel about 16070400000000 miles.

Floating-Point Types• Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. • For example, calculations such as square root.• There are two kinds of floating-point types, float and double, which represent

single- and double-precision numbers, respectively.• Name Width in Bits Approximate Range• Double 64 4.9e–324 to 1.8e+308• float 32 1.4e−045 to 3.4e+038

Simple Type: float32-bit floating-point number.

Range: 1.4e-045 to 3.4e+038.

Example:

float f = 1.5;

Usage:

1) fractional part is needed

2) large degree of precision is not required

Simple Type: double64-bit floating-point number.

Range: 4.9e-324 to 1.8e+308.

Example:

double pi = 3.1416;

Usage:

1) accuracy over many iterative calculations

2) manipulation of large-valued numbers

Example: double// Compute the area of a circle.

class Area {

public static void main(String args[]) {

double pi = 3.1416;

double r = 10.8;

double a = pi * r * r;

// approximate pi value

// radius of circle

// compute area

System.out.println("Area of circle is " + a);

}

}

Simple Type: char16-bit data type used to store characters.

Range: 0 to 65536.

Example:

char c = ‘a’;

Usage:

1) Represents both ASCII and Unicode character sets; Unicode defines acharacter set with characters found in (almost) all human languages.

2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.

Example: char// Demonstrate char data type.

class CharDemo {

public static void main(String args[]) {

char ch1, ch2;ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);

}

}

Output:ch1 and ch2: X Y

Another Example: charIt is possible to operate on char values as if they were integers:

class CharDemo2 {

public static void main(String args[]) {

char c = 'X';

System.out.println("c contains " + c);c++; // increment c

System.out.println("c is now " + c);

}

}

Output:ch1 contains Xch1 is now Y

Simple Type: booleanTwo-valued type of logical values.

Range: values true and false.

Example:

boolean b = (1<2);

Usage:

1) returned by relational operators, such as 1<2

2) required by branching expressions such as if or for

Example: booleanclass BoolTest {

public static void main(String args[]) {

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

if (b) System.out.println("executed");

b = false;

if (b) System.out.println(“not executed");

System.out.println("10 > 9 is " + (10 > 9));

}

}

Output:b is falseb is trueThis is executed.10 > 9 is true

Comments 2/**

* MyProgram implements application that displays

a simple message on the standard output*device.

*/

class MyProgram {

/* The main method of the class.*/

public static void main(String[] args) {

//display string

System.out.println(“First Java program.");

}

}

abstract continue goto package synchronize

assert default if private this

boolean do implements protected throw

break double import public throws

byte else instanceof return transient

case extends int short try

catch final interface static void

char finally long strictfp volatile

class float native super while

const for new switch

Keywords

Keywords are reserved words recognized by Java that cannot be used asidentifiers. Java defines 49 keywords as follows:

Control FlowWriting a program means typing statements into a file.

Without control flow, the interpreter would execute these statements in theorder they appear in the file, left-to-right, top-down.

Control flow statements, when inserted into the text of the program,determine in which order the program should be executed.

Control Flow StatementsJava control statements cause the flow of execution to advance and branchbased on the changes to the state of the program.

Control statements are divided into three groups:

1) selection statements allow the program to choose different parts of theexecution based on the outcome of an expression

2) iteration statements enable program execution to repeat one or morestatements

3) jump statements enable your program to execute in a non-linear fashion

Selection StatementsJava selection statements allow to control the flow of program’s executionbased upon conditions known only during run-time.

Java provides four selection statements:

1)if

2)if-else

3)if-else-if

4)switch

if StatementGeneral form:

if (expression) statement

If expression evaluates to true, execute statement, otherwise do

nothing.

The expression must be of type boolean.

Simple/Compound StatementThe component statement may be:

1) simple

if (expression) statement;

2) compound

if (expression) {statement;

}

if-else StatementSuppose you want to perform two different statements depending on theoutcome of a boolean expression. if-else statement can be used.

General form:

if (expression) statement1

else statement2

Again, statement1 and statement2 may be simple or compound.

if-else-if StatementGeneral form:

if (expression1) statement1

else if (expression2) statement2

else if (expression3) statement3

…else statement

Semantics:1) statements are executed top-down

2) as soon as one expressions is true, its statement is executed

3) if none of the expressions is true, the last statement is executed

Example: if-else-ifclass IfElse {

public static void main(String args[]) {int month = 4;String season;if (month == 12 || month == 1 || month == 2)

season = "Winter";else if(month == 3 || month == 4 || month == 5)

season = "Spring";else if(month == 6 || month == 7 || month == 8)

season = "Summer";else if(month == 9 || month == 10 || month == 11)

season = "Autumn";else season = "Bogus Month";System.out.println("April is in the " + season + ".");

}}

switch Statementswitch provides a better alternative than if-else-if when the executionfollows several branches depending on the value of an expression.

General form:

switch (expression) {

case value1: statement1; break;

case value2: statement2; break;

case value3: statement3; break;

…default: statement;

}

switch Assumptions/SemanticsAssumptions:

1) expression must be of type byte, short, int or char

2) each of the case values must be a literal of the compatible type

3) case values must be unique

Semantics:1) expression is evaluated2) its value is compared with each of the case values

3) if a match is found, the statement following the case is executed

4) if no match is found, the statement following default is executed

break makes sure that only the matching statement is executed.

Both default and break are optional.

Example: switch 1class Switch {

public static void main(String args[]) {

int month = 4;

String season;switch (month) {

case 12:

case 1:

case 2: season = "Winter"; break;

case 3:

case 4:

case 5: season = "Spring"; break;

case 6:

case 7:case 8: season = "Summer"; break;

Example: switch 2case 9:case 10:

case 11: season = "Autumn"; break;

default: season = "Bogus Month";}

System.out.println("April is in " + season + ".");

}

}

Nested switch StatementA switch statement can be nested within another switch statement:

switch(count) {

case 1:switch(target) {

case 0:System.out.println(“target is zero”);

break;

case 1:System.out.println(“target is one”);break;

}

break;

case 2: …

}

Since, every switch statement defines its own block, no conflict arisesbetween the case constants in the inner and outer switch statements.

Comparing switch and ifTwo main differences:

1) switch can only test for equality, while if can evaluate any kind ofboolean expression

2) Java creates a “jump table” for switch expressions, so a switchstatement is usually more efficient than a set of nested if statements

Iteration StatementsJava iteration statements enable repeated execution of part of a programuntil a certain termination condition becomes true.

Java provides three iteration statements:

1)while

2)do-while

3)for

while StatementGeneral form:

while (expression) statement

where expression must be of type boolean.

Semantics:

1) repeat execution of statement until expression becomes false

2) expression is always evaluated before statement

3) if expression is false initially, statement will never get executed

Simple/Compound StatementThe component statement may be:

1) simple

while (expression) statement;

2) compound

while (expression) {statement;

}

do-while StatementIf a component statement has to be executed at least once, the do-whilestatement is more appropriate than the while statement.

General form:

do statementwhile (expression);

where expression must be of type boolean.

Semantics:

1) repeat execution of statement until expression becomes false

2) expression is always evaluated after statement

3) even if expression is false initially, statement will be executed

Example: whileclass MidPoint {

public static void main(String args[]) {

int i, j;

i = 100;

j = 200;while(++i < --j) {

System.out.println(“i is " + i);

System.out.println(“j is " + j);}

System.out.println(“The midpoint is " + i);

}

}

Output:Midpoint is 150

• Using a do-while to process a menu selection -- a simple help system.• class Menu {• public static void main(String args[]) • throws java.io.IOException {• char choice;

• do {• System.out.println("Help on:");• System.out.println(" 1. if");• System.out.println(" 2. switch");• System.out.println(" 3. while");• System.out.println(" 4. do-while");• System.out.println(" 5. for\n");• System.out.println("Choose one:");• choice = (char) System.in.read();• } while( choice < '1' || choice > '5');

• System.out.println("\n");• • switch(choice) {• case '1':• System.out.println("The if:\n");• System.out.println("if(condition) statement;");• System.out.println("else statement;");• break;

• case '2':• System.out.println("The switch:\n");• System.out.println("switch(expression) {");• System.out.println(" case constant:");• System.out.println(" statement sequence");• System.out.println(" break;");• System.out.println(" // ...");• System.out.println("}");• break;• case '3':• System.out.println("The while:\n");• System.out.println("while(condition) statement;");• break;• case '4':• System.out.println("The do-while:\n");• System.out.println("do {");• System.out.println(" statement;");• System.out.println("} while (condition);");• break;• case '5':• System.out.println("The for:\n");• System.out.print("for(init; condition; iteration)");• System.out.println(" statement;");• break;• }• }• }

Output:Help on:1. if2. switch3. while4. do-while5. forChoose one:4The do-while:do {statement;} while (condition);

Example: do-whileclass DoWhile {

public static void main(String args[]) {

int i;

i = 0;

doi++;

while ( 1/i < 0.001);

System.out.println(“i is “ + i);

}

}

for StatementWhen iterating over a range of values, for statement is more suitable to use

then while or do-while.

General form:

for (initialization; termination; increment)

statement

where:

1) initialization statement is executed once before the first iteration

2) termination expression is evaluated before each iteration todetermine when the loop should terminate

3) increment statement is executed after each iteration

for Statement SemanticsThis is how the for statement is executed:

1) initialization is executed once

2) termination expression is evaluated:

a) if false, the statement terminates

b) otherwise, continue to (3)

3) increment statement is executed

4) component statement is executed

5) control flow continues from (2)

Loop Control VariableThe for statement may include declaration of a loop control variable:

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

}

The variable does not exist outside the for statement.

Example: forclass FindPrime {

public static void main(String args[]) {

int num = 14;

boolean isPrime = true;for (int i=2; i < num/2; i++) {

if ((num % i) == 0) {

isPrime = false;

break;

}

}

if (isPrime) System.out.println("Prime");

else System.out.println("Not Prime");

}

}

Many Initialization/Iteration PartsThe for statement may include several initialization and iteration

parts.

Parts are separated by a comma:

class Comma {public static void main(String args[]) {int a, b;for(a=1, b=4; a<b; a++, b--) {System.out.println("a = " + a);System.out.println("b = " + b);}}}

Output:

a = 1b = 4a = 2b = 3

for Statement VariationsThe for statement need not have all components:

class ForVar {

public static void main(String args[]) {int i = 0;

boolean done = false;

for( ; !done; ) {

System.out.println("i is " + i);

if(i == 10) done = true;

i++;

}

}

}

Empty forIn fact, all three components may be omitted:

public class EmptyFor {

public static void main(String[] args) {

int i = 0;

for (; ;) {

System.out.println(“Infinite Loop “ + i);

}

}

}

Nested Loops• one loop may be inside another. For example, here is a program that nests for

loops:class Nested {public static void main(String args[]) {int i, j;for(i=0; i<10; i++) {for(j=i; j<10; j++)System.out.print(".");System.out.println();}}}

Output:

..........

.........

........

.......

......

.....

....

...

..

.

Jump StatementsJava jump statements enable transfer of control to other parts of program.

Java provides three jump statements:

1) break

2) continue

3) return

In addition, Java supports exception handling that can also alter the controlflow of a program. Exception handling will be explained in its own section.

break StatementThe break statement has three uses:

1) to terminate a case inside the switch statement

2) to exit an iterative statement

3) to transfer control to another statement

(1) has been described.

We continue with (2) and (3).

Loop Exit with breakWhen break is used inside a loop, the loop terminates and control istransferred to the following instruction.

class BreakLoop {

public static void main(String args[]) {for (int i=0; i<100; i++) {

if (i == 10) break;

System.out.println("i: " + i);

}System.out.println("Loop complete.");

}

}

Output:i: 0 i: 1i: 2i: 3i: 4i: 5i: 6i: 7i: 8 i: 9

break in Nested LoopsUsed inside nested loops, break will only terminate the innermost loop:

class NestedLoopBreak {

public static void main(String args[]) {for (int i=0; i<3; i++) {

System.out.print("Pass " + i + ": ");

for (int j=0; j<100; j++) {

if (j == 10) break;System.out.print(j + " ");

}

System.out.println();

}System.out.println("Loops complete.");

}

}

Output:Pass 0: 0 1 2 3 4 5 6 7 8 9Pass 1: 0 1 2 3 4 5 6 7 8 9Pass 2: 0 1 2 3 4 5 6 7 8 9Loops complete.

Control Transfer with breakJava does not have an unrestricted “goto” statement, which tends toproduce code that is hard to understand and maintain.

However, in some places, the use of gotos is well justified. In particular,when breaking out from the deeply nested blocks of code.

break occurs in two versions:

1) unlabelled

2) labeled

The labeled break statement is a “civilized” replacement for goto.

Labeled breakGeneral form:

break label;

where label is the name of a label that identifies a block of code:

label: { … }

The effect of executing break label; is to transfer control immediatelyafter the block of code identified by label.

Example: Labeled breakclass Break {

public static void main(String args[]) {

boolean t = true;

first: {second: {

third: {

System.out.println("Before the break.");

if (t) break second;System.out.println("This won't execute");

}

System.out.println("This won't execute");

}System.out.println(“After second block.");

}

} }

Output:Before the break.This is after second block.

Example: Nested Loop breakclass NestedLoopBreak {

public static void main(String args[]) {

outer: for (int i=0; i<3; i++) {

System.out.print("Pass " + i + ": ");

for (int j=0; j<100; j++) {

if (j == 10) break outer; // exit both loops

System.out.print(j + " ");

}System.out.println("This will not print");

}

System.out.println("Loops complete.");

}

}

Output:Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

break Without LabelIt is not possible to break to any label which is not defined for an enclosingblock. Trying to do so will result in a compiler error.

class BreakError {

public static void main(String args[]) {one: for(int i=0; i<3; i++) {

System.out.print("Pass " + i + ": ");

}

for (int j=0; j<100; j++) {if (j == 10) break one;

System.out.print(j + " ");

}

}

}

continue StatementThe break statement terminates the block of code, in particular it terminatesthe execution of an iterative statement.

The continue statement forces the early termination of the current iterationto begin immediately the next iteration.

Like break, continue has two versions:

1) unlabelled – continue with the next iteration of the current loop

2) labeled – specifies which enclosing loop to continue

Example: Unlabeled continueclass Continue {

public static void main(String args[]) {

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

System.out.print(i + " ");

if (i%2 == 0) continue;

System.out.println("");

}

}

}

Output:0 12 34 56 78 9

Example: Labeled continueclass LabeledContinue {

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();

}

}

Output:00 10 2 40 3 6 90 4 8 12 160 5 10 15 20 250 6 12 18 24 30 360 7 14 21 28 35 42 490 8 16 24 32 40 48 56 640 9 18 27 36 45 54 63 72 81

Return StatementThe return statement is used to return from the current method: it causesprogram control to transfer back to the caller of the method.

Two forms:

1) return without value

return;

2) return with value

return expression;

Example: Returnclass Return {

public static void main(String args[]) {

boolean t = true;

System.out.println("Before the return.");

if (t) return; // return to callerSystem.out.println("This won't execute.");

}

}

Output:Before the return.

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.

• For instance, there is no conversion defined from double to byte. Fortunately, it is still possible to obtain a conversion between incompatible types.

• To do so, you must use a cast, which performs an explicit conversion between incompatible types.

Type DifferencesSuppose a value of one type is assigned to a variable of another type.

T1 t1;

T2 t2 = t1;

What happens? Different situations:

1) types T1 and T2 are incompatible

2) types T1 and T2 are compatible:

a) T1 and T2 are the same

b) T1 is larger than T2

c) T2 is larger than T1

Type CompatibilityWhen types are compatible:

1) integer types and floating-point types are compatible with each other2) numeric types are not compatible with char or boolean

3) char and boolean are not compatible with each other

Examples:

byte b;

int i = b;

char c = b;

Widening Type ConversionJava performs automatic type conversion when:

1) two types are compatible

2) destination type is larger then the source type

Example:

int i;double d = i;

Narrowing Type ConversionWhen:

1) two types are compatible

2) destination type is smaller then the source type

then Java will not carry out type-conversion:

int i;byte b = i;

Instead, we have to rely on manual type-casting:

int i;byte b = (byte)i;

Type CastingGeneral form: (targetType) value

Examples:

1) integer value will be reduced module byte3s range:

int i;

byte b = (byte) i;

2) floating-point value will be truncated to integer value:

float f;int i = (int) f;

Example: Type Castingclass 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("\ndouble to int.");

i = (int) d;System.out.println("d and i " + d + " " + i);

}

}

Conversion of int to byte.i and b 257 1Conversion of double to int.d and i 323.142 323Conversion of double to byte.d and b 323.142 67

Type PromotionIn an expression, precision required to hold an intermediate value maysometimes exceed the range of either operand:

byte a = 40;

byte b = 50;

byte c = 100;int d = a * b / c;

Java promotes each byte operand to int when evaluating the expression.

Type Promotion Rules1) byte and short are always promoted to int

2) if one operand is long, the whole expression is promoted to long

3) if one operand is float, the entire expression is promoted to float

4) if any operand is double, the result is double

Danger of automatic type promotion:

byte b = 50;

b = b * 2;

What is the problem?

Example: Type Promotionclass Promote {

public static void main(String args[]) {

byte b = 42;

char c = 'a';

short s = 1024;

int i = 50000;

float f = 5.67f;

double d = .1234;

double result = (f * b) + (i / c) - (d * s);System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));System.out.println("result = " + result);}

}

238.14 + 515 - 126.3616result = 626.7784146484375

Operators TypesJava operators are used to build value expressions.

Java provides a rich set of operators:

1)2)3)4)5)6)

assignmentarithmeticrelationallogicalbitwiseother

Operators and OperandsEach operator takes one, two or three operands:

1) a unary operator takes one operand

j++;

2) a binary operator takes two operands

i = j++;

3) a ternary operator requires three operands

i = (i>12) ? 1 : i++;

Assignment OperatorA binary operator:

variable = expression;

It assigns the value of the expression to the variable.

The types of the variable and expression must be compatible.

The value of the whole assignment expression is the value of the expressionon the right, so it is possible to chain assignment expressions as follows:

int x, y, z;

x = y = z = 2;

Arithmetic OperatorsJava supports various arithmetic operators for:

1) integer numbers

2) floating-point numbers

There are two kinds of arithmetic operators:

1) basic: addition, subtraction, multiplication, division and modulo

2) shortcut: arithmetic assignment, increment and decrement

The operands of the arithmetic operators must be of a numeric type. You cannot use them on Boolean types.

+ op1+op2 addsop1andop2

- op1–op2 subtractsop2fromop1

* op1*op2 multipliesop1byop2

/ op1/op2 dividesop1byop2

% op1%op2 computestheremainderofdividingop1byop2

Table: Basic Arithmetic Operators

Remember that when the division operator is applied to an integer type, there will be no fractional component attached to the result.

The Modulus Operator• The modulus operator, %, returns the remainder of a division operation. It

can be applied to floating-point types as well as integer types.• This differs from C/C++, in which the % can only be applied to integer types.• The following example program demonstrates the %:• // Demonstrate the % operator.• class Modulus {public static void main(String args[]) {int x = 42;double y = 42.25;System.out.println("x mod 10 = " + x % 10);System.out.println("y mod 10 = " + y % 10); }}

Output:x mod 10 = 2y mod 10 = 2.25

Arithmetic Assignment OperatorsJava provides special operators that can be used to combine an arithmetic operation with an assignment. As you probably know, statements like the following are quite common in programming:a = a + 4;In Java, you can rewrite this statement as shown here:a += 4;a = a % 2;which can be expressed asa %= 2;

Thus, any statement of the formvar = var op expression;can be rewritten asvar op= expression;

Benefits of the assignment operators:

1) save some typing

2) are implemented more efficiently by the Java run-time system

+= v+=expr; v=v+expr;

-= v-=expr; v=v-expr;

*= v*=expr; v=v*expr;

/= v/=expr; v=v/expr;

%= v%=expr; v=v%expr;

Table: Arithmetic Assignments

• //Demonstrate several assignment operators.• class OpEquals {• public static void main(String args[]) {• int a = 1;• int b = 2;• int c = 3;• a += 5;• b *= 4;• c += a * b;• c %= 6;• System.out.println("a = " + a);• System.out.println("b = " + b);• System.out.println("c = " + c);• }• }• The output of this program is shown here:• a = 6• b = 8• c = 3

Increment/Decrement Operators

Two unary operators:

1) ++ increments its operand by 1

2) -- decrements its operand by 1

The operand must be a numerical variable.

Each operation can appear in two versions:

prefix version evaluates the value of the operand after performing theincrement/decrement operation

postfix version evaluates the value of the operand before performing theincrement/decrement operation

++ v++ returnvalueofv,thenincrementv

++ ++v incrementv,thenreturnitsvalue

-- v-- returnvalueofv,thendecrementv

-- --v decrementv,thenreturnitsvalue

Table: Increment/Decrement

Increment/Decrement Operators

• For example, this statement:• x = x + 1;• can be rewritten like this by use of the increment operator:• x++;• Similarly, this statement:• x = x - 1;• is equivalent to• x--;• For example:• x = 42;• y = ++x; OR

Increment/Decrement Operators

• x = x + 1;• y = x;• However, when written like this,• x = 42;• y = x++;• OR• y = x;• x = x + 1;

Example: Increment/Decrementclass IncDec {

public static void main(String args[]) {

int a = 1;

int b = 2;

int c, d;

c = ++b;

d = a++;

c++;System.out.println(“a= “ + a);

System.out.println(“b= “ + b);

System.out.println(“c= “ + c);

}

}

The output of this program follows:a = 2b = 3c = 4d = 1

Relational OperatorsRelational operators determine the relationship that one operand has to theother operand, specifically equality and ordering.

The outcome is always a value of type boolean.

They are most often used in branching and loop control statements.

== equalsto applytoanytype

!= notequalto applytoanytype

> greaterthan applytonumericaltypesonly

< lessthan applytonumericaltypesonly

>= greaterthanorequal applytonumericaltypesonly

<= lessthanorequal applytonumericaltypesonly

Table: Relational Operators

Logical OperatorsLogical operators act upon boolean operands only.

The outcome is always a value of type boolean.

& op1&op2 logicalAND

| op1|op2 logicalOR

&& op1&&op2 short-circuitAND

|| op1||op2 short-circuitOR

! !op logicalNOT

^ op1^op2 logicalXOR

Table: Logical Operators

Example: Logical Operators// Demonstrate the boolean logical operators.class BoolLogic {public static void main(String args[]) {boolean a = true;boolean b = false;boolean c = a | b;boolean d = a & b;boolean e = a ^ b;boolean f = (!a & b) | (a & !b);boolean g = !a;System.out.println(" a = " + a);System.out.println(" b = " + b);System.out.println(" a|b = " + c);System.out.println(" a&b = " + d);System.out.println(" a^b = " + e);System.out.println("!a&b|a&!b = " + f);System.out.println(" !a = " + g);}}

Output:a = trueb = falsea|b = truea&b = falsea^b = truea&b|a&!b = true!a = false

Bitwise OperatorsBitwise operators apply to integer types only(long, int, short, char, and byte).

They act on individual bits of their operands.

There are three kinds of bitwise operators:

1) basic2) shifts

bitwise AND, OR, NOT and XORleft, right and right-zero-fill

3) assignments bitwise assignment for all basic and shift operators

Table: Bitwise Operators

Bitwise Operators

• All of the integer types (except char) are signed integers. This means that they can represent negative values as well as positive ones.

• Java uses an encoding known as two’s complement.• For example, –42 is represented by inverting all of the bits in

42, or 00101010, which yields 11010101, then adding 1, which results in 11010110, or –42.

• To decode a negative number, first invert all of the bits, then add 1. –42, or 11010110 inverted yields 00101001,or 41, so when you add 1 you get 42.

The Bitwise Logical Operators• The bitwise logical operators are &, |, ^, and ~. The following table

shows the outcome of each operation. • The bitwise operators are applied to each individual bit within each

operand.

The Bitwise Logical Operators• The Bitwise NOT:• For example, the number 42, which has the following bit pattern:• 00101010• becomes• 11010101 after the NOT operator is applied.• The Bitwise AND:• The AND operator, &, produces a 1 bit if both operands are also 1.

A zero is produced• in all other cases. Here is an example:• 00101010 42• &00001111 15• --------------• 00001010 10

The Bitwise Logical Operators• The Bitwise OR:• The OR operator, |, combines bits such that if either of the bits in the

operands is a 1,then the resultant bit is a 1, as shown here:• 00101010 42 00001111 15• --------------• 00101111 47• The Bitwise XOR: The XOR operator, ^, combines bits such that if exactly

one operand is 1, then the result is 1. Otherwise, the result is zero.• 00101010 42• ^00001111 15• -------------• 00100101 37

Example: Using the Bitwise Logical Operators

// Demonstrate the bitwise logical operators.class BitLogic {public static void main(String args[]) {String binary[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111","1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};int a = 3; // 0 + 2 + 1 or 0011 in binaryint b = 6; // 4 + 2 + 0 or 0110 in binaryint c = a | b;int d = a & b;int e = a ^ b;int f = (~a & b) | (a & ~b);int g = ~a & 0x0f;System.out.println(" a = " + binary[a]);System.out.println(" b = " + binary[b]);System.out.println(" a|b = " + binary[c]);System.out.println(" a&b = " + binary[d]);System.out.println(" a^b = " + binary[e]);System.out.println("~a&b|a&~b = " + binary[f]);System.out.println(" ~a = " + binary[g]);}}

Output:a = 0011b = 0110a|b = 0111a&b = 0010a^b = 0101~a&b|a&~b = 0101~a = 1100

The Left Shift• The left shift operator, <<, shifts all of the bits in a value to the left

a specified number of times. It has this general form: value << num• Here, num specifies the number of positions to left-shift the value in

value. That is, the << moves all of the bits in the specified value to the left by the number of bit positions specified by num.

• For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on the right.

• This means that when a left shift is applied to an int operand, bits are lost once they are shifted past bit position 31. If the operand is a long, then bits are lost after bit position 63.

The Left Shift// Left shifting a byte value.class ByteShift {public static void main(String args[]) {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: 64i and b: 256 0

The Left Shift• Since a is promoted to int for the purposes of evaluation, left-

shifting the value 64 (0100 0000) twice results in i containing the value 256 (1 0000 0000).

• However, the value in b contains 0 because after the shift, the low-order byte is now zero.

• Its only 1 bit has been shifted out.• Since each left shift has the effect of doubling the original value.• Programmers frequently use this fact as an efficient alternative to

multiplying by 2. • But you need to watch out. If you shift a 1 bit into the high-order

position (bit 31 or 63), the value will become negative. • The following program illustrates this point:

The Left Shift• // Left shifting as a quick way to multiply by 2.• class MultByTwo {• public static void main(String args[]) {• int i;• int num = 0xFFFFFFE;• for(i=0; i<4; i++) {• num = num << 1;• System.out.println(num);• }• }• }

Output:53687090810737418162147483632-32

The Right Shift• The right shift operator, >>, shifts all of the bits in a value to the right a specified

number of times. • Its general form is shown here: value >> num• The following code fragment shifts the value 32 to the right by two positions,

resulting in a being set to 8:• int a = 32;• a = a >> 2; // a now contains 8• When a value has bits that are “shifted off,” those bits are lost.• int a = 35;• a = a >> 2; // a still contains 8• Looking at the same operation in binary shows more clearly how this

happens:• 00100011 35• >> 2• 00001000 8

The Right Shift• Each time you shift a value to the right, it divides that value by two

—and discards any remainder. • You can take advantage of this for high-performance integer division

by 2. • Of course, you must be sure that you are not shifting any bits off the

right end.

Conditional OperatorGeneral form:

expr1? expr2 : expr3

where:

1) expr1 is of type boolean2) expr2 and expr3 are of the same type

If expr1 is true, expr2 is evaluated, otherwise expr3 is evaluated.

Example: Conditional Operatorclass Ternary {

public static void main(String args[]) {

int i, k;

i = 10;

k = i < 0 ? -i : i;

System.out.print("Abs value of “ + i + " is " + k);

i = -10;

k = i < 0 ? -i : i;

System.out.print("Abs value of “ + i + " is " + k);

}

}