Download presentation
Presentation is loading. Please wait.
Published byAmberly Carpenter Modified over 9 years ago
1
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
2
Strong Typing Java is a strongly-typed language: a) every variable and expression has a type b) every type is strictly defined c) all assignments are checked for type-compatibility d) no automatic conversion of non-compatible, conflicting types e) Java compiler type-checks all expressions and parameters f) any typing errors must be corrected for compilation to succeed
3
Simple Types Java 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
4
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.
5
Simple Type: byte 8-bit integer type. Range: -128 to 127. Example: byte b = -15; Usage: particularly when working with data streams.
6
Simple Type: short 16-bit integer type. Range: -32768 to 32767. Example: short c = 1000; Usage: probably the least used simple type.
7
Simple Type: int 32-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.
8
Simple Type: long 64-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
9
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.
10
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
11
Simple Type: float 32-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
12
Simple Type: double 64-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
13
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); } }
14
Simple Type: char 16-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 a character 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.
15
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
16
Another Example: char It 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 X ch1 is now Y
17
Simple Type: boolean Two-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
18
Example: boolean class 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 false b is true This is executed. 10 > 9 is true
19
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."); }
20
abstractcontinuegotopackagesynchronize assertdefaultifprivatethis booleandoimplementsprotectedthrow breakdoubleimportpublicthrows byteelseinstanceofreturntransient caseextendsintshorttry catchfinalinterfacestaticvoid charfinallylongstrictfpvolatile classfloatnativesuperwhile constfornewswitch Keywords Keywords are reserved words recognized by Java that cannot be used as identifiers. Java defines 49 keywords as follows:
21
Control Flow Writing a program means typing statements into a file. Without control flow, the interpreter would execute these statements in the order 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.
22
Control Flow Statements Java control statements cause the flow of execution to advance and branch based 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 the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion
23
Selection Statements Java selection statements allow to control the flow of program’s execution based upon conditions known only during run-time. Java provides four selection statements: 1)if 2)if-else 3)if-else-if 4)switch
24
if Statement General form: if (expression) statement If expression evaluates to true, execute statement, otherwise do nothing. The expression must be of type boolean.
25
Simple/Compound Statement The component statement may be: 1) simple if (expression) statement; 2) compound if (expression) { statement; }
26
if-else Statement Suppose you want to perform two different statements depending on the outcome 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.
27
if-else-if Statement General 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
28
Example: if-else-if class 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 + "."); }}}}
29
switch Statement switch provides a better alternative than if-else-if when the execution follows 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; }
30
switch Assumptions/Semantics Assumptions: 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 evaluated 2) 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.
31
Example: switch 1 class 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;
32
Example: switch 2 case 9: case 10: case 11: season = "Autumn"; break; default: season = "Bogus Month"; } System.out.println("April is in " + season + "."); }}}}
33
Nested switch Statement A 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; } case 2: … } Since, every switch statement defines its own block, no conflict arises between the case constants in the inner and outer switch statements.
34
Comparing switch and if Two main differences: 1) switch can only test for equality, while if can evaluate any kind of boolean expression 2) Java creates a “jump table” for switch expressions, so a switch statement is usually more efficient than a set of nested if statements
35
Iteration Statements Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true. Java provides three iteration statements: 1)while 2)do-while 3)for
36
while Statement General 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
37
Simple/Compound Statement The component statement may be: 1) simple while (expression) statement; 2) compound while (expression) { statement; }
38
do-while Statement If a component statement has to be executed at least once, the do-while statement is more appropriate than the while statement. General form: do statement while (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
39
Example: while class 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
40
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 '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;
41
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. if 2. switch 3. while 4. do-while 5. for Choose one: 4 The do-while: do { statement; } while (condition);
42
Example: do-while class DoWhile { public static void main(String args[]) { int i; i = 0; do i++; while ( 1/i < 0.001); System.out.println(“i is “ + i); }}}}
43
for Statement When 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 to determine when the loop should terminate 3) increment statement is executed after each iteration
44
for Statement Semantics This 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)
45
Loop Control Variable The 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.
46
Example: for class 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"); }}}}
47
Many Initialization/Iteration Parts The 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 = 1 b = 4 a = 2 b = 3
48
for Statement Variations The 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++; }}}}}}
49
Empty for In 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); }}}}}}
50
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:.......................................................
51
Jump Statements Java 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 control flow of a program. Exception handling will be explained in its own section.
52
break Statement The 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).
53
Loop Exit with break When break is used inside a loop, the loop terminates and control is transferred 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: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9
54
break in Nested Loops Used 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 9 Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Loops complete.
55
Control Transfer with break Java does not have an unrestricted “goto” statement, which tends to produce 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.
56
Labeled break General 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 immediately after the block of code identified by label.
57
Example: Labeled break class 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(“After second block."); } } Output: Before the break. This is after second block.
58
Example: Nested Loop break class 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.
59
break Without Label It is not possible to break to any label which is not defined for an enclosing block. 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 + " "); }}}}}}
60
continue Statement The break statement terminates the block of code, in particular it terminates the execution of an iterative statement. The continue statement forces the early termination of the current iteration to 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
61
Example: Unlabeled continue class 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 1 2 3 4 5 6 7 8 9
62
Example: Labeled continue class 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: 0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81
63
Return Statement The return statement is used to return from the current method: it causes program control to transfer back to the caller of the method. Two forms: 1) return without value return; 2) return with value return expression;
64
Example: Return 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."); }}}} Output: Before the return.
65
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.
66
Type Differences Suppose 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
67
Type Compatibility When types are compatible: 1) integer types and floating-point types are compatible with each other 2) 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;
68
Widening Type Conversion Java 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;
69
Narrowing Type Conversion When: 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;
70
Type Casting General form: (targetType) value Examples: 1) integer value will be reduced module byte 3 s range: int i; byte b = (byte) i; 2) floating-point value will be truncated to integer value: float f; int i = (int) f;
71
Example: Type Casting 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("\ndouble to int."); i = (int) d; System.out.println("d and i " + d + " " + i); }}}} Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67
72
Type Promotion In an expression, precision required to hold an intermediate value may sometimes 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.
73
Type Promotion Rules 1) 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?
74
Example: Type Promotion class 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.3616 result = 626.7784146484375
75
Operators Types Java operators are used to build value expressions. Java provides a rich set of operators: 1) 2) 3) 4) 5) 6) assignment arithmetic relational logical bitwise other
76
Operators and Operands Each 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++;
77
Assignment Operator A 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 expression on the right, so it is possible to chain assignment expressions as follows: int x, y, z; x = y = z = 2;
78
Arithmetic Operators Java 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
79
The operands of the arithmetic operators must be of a numeric type. You cannot use them on Boolean types.
80
+op1+op2addsop1andop2 -op1–op2subtractsop2fromop1 *op1*op2multipliesop1byop2 /op1/op2dividesop1byop2 %op1%op2computestheremainderofdividingop1byop2 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.
81
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 = 2 y mod 10 = 2.25
82
Arithmetic Assignment Operators Java 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 as a %= 2; Thus, any statement of the form var = var op expression; can be rewritten as var op= expression; Benefits of the assignment operators: 1) save some typing 2) are implemented more efficiently by the Java run-time system
83
+=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
84
//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
85
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 the increment/decrement operation postfix version evaluates the value of the operand before performing the increment/decrement operation
86
++v++returnvalueofv,thenincrementv ++++vincrementv,thenreturnitsvalue --v--returnvalueofv,thendecrementv ----vdecrementv,thenreturnitsvalue Table: Increment/Decrement
87
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
88
Increment/Decrement Operators x = x + 1; y = x; However, when written like this, x = 42; y = x++; OR y = x; x = x + 1;
89
Example: Increment/Decrement class 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 = 2 b = 3 c = 4 d = 1
90
Relational Operators Relational operators determine the relationship that one operand has to the other 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.
91
==equalstoapplytoanytype !=notequaltoapplytoanytype >greaterthanapplytonumericaltypesonly <lessthanapplytonumericaltypesonly >=greaterthanorequalapplytonumericaltypesonly <=lessthanorequalapplytonumericaltypesonly Table: Relational Operators
92
Logical Operators Logical operators act upon boolean operands only. The outcome is always a value of type boolean.
93
&op1&op2logicalAND |op1|op2logicalOR &&op1&&op2short-circuitAND ||op1||op2short-circuitOR !!oplogicalNOT ^op1^op2logicalXOR Table: Logical Operators
94
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 = true b = false a|b = true a&b = false a^b = true a&b|a&!b = true !a = false
95
Bitwise Operators Bitwise 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) basic 2) shifts bitwise AND, OR, NOT and XOR left, right and right-zero-fill 3) assignmentsbitwise assignment for all basic and shift operators
96
Table: Bitwise Operators
97
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.
98
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.
99
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
100
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
101
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 binary int b = 6; // 4 + 2 + 0 or 0110 in binary int 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 = 0011 b = 0110 a|b = 0111 a&b = 0010 a^b = 0101 ~a&b|a&~b = 0101 ~a = 1100
102
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.
103
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: 64 i and b: 256 0
104
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:
105
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: 536870908 1073741816 2147483632 -32
106
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
107
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.
108
Conditional Operator General form: expr1? expr2 : expr3 where: 1) expr1 is of type boolean 2) expr2 and expr3 are of the same type If expr1 is true, expr2 is evaluated, otherwise expr3 is evaluated.
109
Example: Conditional Operator class 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); }}}}
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.