Chapter 2: Operators and Statements Flashcards Preview

Java SE exam > Chapter 2: Operators and Statements > Flashcards

Flashcards in Chapter 2: Operators and Statements Deck (90)
Loading flashcards...
1
Q

What is the structure of a while statement?

A

while ( booleanExpression ) {

// do something

}

2
Q

What is a termination condition in a while statement?

A

This is the boolean expression inside a while loop that will continue executing as long as the expression evaluates to true.

3
Q

In a while loop, when does a loop terminate

A

The boolean expression is evaluated before each iteration of the loop and when the expression becomes false, the loop terminates

4
Q

What is the structure of a do while loop?

A

do {

statement(s)

} while (booleanExpression);

5
Q

How many times will a do while loop execute and why?

A

It will be executed at least once cos Java will execute the statement and then check the condition after

6
Q

Are the curly braces a requirement in both while and do while loops?

A

No, they are not required for single statements, only for a block of multiple statements.

7
Q

What is the structure of a for loop?

A

for ( 1) initialization block ; 2) booleanExpression ; 4) updateStatement) { 3) //body }

8
Q

What are the 5 steps involved in the execution of a for loop?

A

1) initialization of variable(s) occurs 2) if boolean expression is true, keep going else exit the loop 3) Execute statement(s) in the body 4) Execute the update statements 5) go back to step 2 and rinse and repeat until the expression is false

9
Q

Is this a valid statement? for( ; ; ) { System.out.println(“hello”) }

A

Yes, perfectly legal. This will create an infinite loop. The parentheses and semicolons are mandatory whereas the curly braces are only required for multiple statements.

10
Q

True or False, in a for statement, the initialisation and updation section can only contain one statement?

A

False, they can contain multiple statements separated by commas.

11
Q

What is the output of this code? for ( int i = 0; i<10; i++) { System.out.println( i + “ “); }

A

It will print numbers 0 - 9 and once it reaches the 10th iteration, the expression will evaluate to false and the loop will exit

12
Q

What is the output of this code? int x = 0; for (long y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.println( x + “ “); }

A

It won’t compile because the variable x is being redeclared in the for loop after already being initialised before. The compiler will recognise that is a duplicate

13
Q

What is the output of this code? for (long y = 0, int x = 4; x < 5 && y < 10; x++, y++) { System.out.println( x + “ “); }

A

It won’t compile as long and int and int are not of the same type which is required in the initialisation block

14
Q

What is the output of this code? for (long y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.println( y + “ “); } System.out.println( x);

A

This will not compile as the variable x is out of scope. As it was defined inside the loop, it can only be accessed there

15
Q

Is the following code legal in Java? int x = 0; for (long y = 0, z = 4; x <5 && y < 10; x++, y ++) { System.out.println( y + “ “); }

A

Yes, you can have multiple statements within the initialisation and updation section of a for loop. Additionally you can define random variables like z which is never used

16
Q

What is the structure of an enhanced for loop? which features are required?

A

for (datatype name : collection) { // Body } The for keyword, parentheses, colon are required and the curly braces only if there are multiple statements.

17
Q

What is on the RHS of an enhanced loop

A

An already defined Array or lterable object like ArrayList and List

18
Q

What is on the LHS of an enhanced loop

A

The LHS must have the matching type for the object on the right. e.g the type of an int []array will be an int the type for a 2D String [][]array is a String array[] the type of a list with type Integer will be an int

19
Q

Will this code compile? String [] names = new String[3] for(String name : names) { System.out.println( names + “ “); }

A

Yes even though the values inside names are null, the code will compile fine and output null 3 times.

20
Q

what is the output of this code? Explain your logic

int x = 20;

while (x>0) {

do { x - = 2;

}

while (x>5);

x–;

System.out.println(x);

}

A

// output is 3, 0 As x is 20, the statement inside the outer loop evaluates to true as a result, we enter the inner loop which tells us to keep repeating & decrementing the value of x by 2 until the condition (x>5) is false. when x is 4, the inner loop exits and x goes into the outer-loop where it is decremented by 1. Output is now 3. x>0 is still true thus another iteration begins even though x is not greater than 5 cos a do while loop will always execute at least once. x is decremented again by 1 and is 0. The loop finally terminated .

21
Q

What is a label?

A

A label is a marker that points to the head of a statement.

Labels allow the application flow to jump to the statement or break from it.

22
Q

What is the structure of a label?

A

It is a single word with a colon after it. e.g OUTER_LOOP:

23
Q

Is a label a requirement?

A

No they are optional

24
Q

What is the convention for labels?

A

They follow the same rules for identifiers however the convention is that they are written in uppercase separated by underscore similar to constants

25
Q

What does the break statement do?

A

Exits out of a statement/loop and returns control to the enclosing statement

26
Q

What does continue do?

A

Essentially skips the iteration of a loop if a certain condition is met and carries on with the next iteration of the loop. e.g for (int k = 0; k<100; k++) { if (k % 7 == 0) { continue; } System.out.println(k) //

27
Q

Which data types are supported in a switch statement?

A

Strings, Enums & Integral values: byte, char, short, int and their wrapper classes.

28
Q

What is an unreachable statement?

A

This is when the JVM throws a compile error when it knows that a certain code/ statement will never be executed. For instance code written after an infinite loop

29
Q

When can you not use break?

A

you can’t use break in an if statement UNLESS the if statement is placed within a switch statement or a loop

30
Q

When can you not use continue?

A

you can’t use break in an “if” or “switch” statement UNLESS in a while, do, or for loop

31
Q

Can the String class name be used as a label or a variable?

A

yes, String is still a valid identifier however it is not advised

32
Q

Another definition of continue

A

continue means we shouldn’t bother executing any of the statements for this current iteration. Basically skip this iteration and continue with the rest.

33
Q

What are labels used for?

A

Optional label allows us to break out of a higher level outer loop

34
Q

Name the logical operators and what they are used for

A

& - AND - only true if both operands are true | - INCLUSIVE OR - only false if both operands are false ^ - EXCLUSIVE OR - only true if the operands are different

35
Q

What is the resulting data type of the equation x * y where: int x = 1; long y = 33;

A

long // the result is automatically promoted to the larger data type

36
Q

What will this code print? double x = 39.21; float y = 2.1f; float z = x + y; System.out.println(z);

A

line : float z = x + y; will not compile when you add a float and a double together, the value returns a double due to numeric promotion. Therefore to fit into a float variable you need an explicit cast. e.g float z = (float) x+y;

37
Q

What is the data type of x / y, where short x = 10; short y = 3;

A

int. //smaller data types values get automatically promoted to int

38
Q

What will this print? short s = 45; byte b = 120; char c = ‘8’; System.out.println(s+ b +c);

A

221 smaller data types values get automatically promoted to int. a char into an int changes its value.

39
Q

if two operators have the same level of precedence, how do you determine which one should be evaluated first? e.g int x = 9-5+2-1;

A

You evaluate from left to right.

40
Q

How many bytes can a float hold?

A

32 bits

41
Q

Name the 4 integral types and their sizes

A

byte - 8 bit short - 16 bit int - 32 bit long - 64 bit

42
Q

How many bytes can a double hold?

A

64 bits

43
Q

What are the 4 rules regarding numeric promotion when dealing with arithmetic operations?

A

1) With values that have different data types, java will automatically promote the smaller to the larger one 2) If one of the values is integral and the other floating, the integral value gets promoted to floating point 3) Smaller data types like byte, short & char are first promoted to int whenever they use the binary operator even if none are int. 4)After promotion has occurred and all operands are of the same type, the result will also have the same type as its promoted operands

44
Q

Up to what value can a byte hold?

A

-128 - 127 calculation is 2 to the power of 8 -1 on the positive side as we include 0.

45
Q

Why does //1 compile where //2 doesn’t? float y = 13. //1 float z = 13.0 // 2

A

// 1 compiles as 13 which is assumed to be an int is small enough to fit into a float variable //2 won’t compile as 13.0 is assumed to be a double unless postfixed with f. thus a double won’t fit into a float without explicit cast.

46
Q

Will this code compile? long x = 10; int y = 5; y * = x;

A

yes. The compound assignment operator first casts int y to a long, then it executes the multiplication between the two long values x & y. Finally the compiler automatically casts the result into an int/ the value of the LHS of the operation

47
Q

What are the final values of x and y? long x = 5; long y = (x=3);

A

x is 3 y is 3

48
Q

What are the 3 logical operators and what kind of data can they be applied to?

A

&, |, ^ They can be applied to numeric and boolean data

49
Q

What are the logical operators used for?

A

& - AND - only true if both operands are true | - INCLUSIVE OR - only false if both operands are false ^ - EXCLUSIVE OR - only true if the operands are different

50
Q

What do these expressions evaluate to: true & false = ? false & false = ? true & true = ? false & true = ?

A

false false true false

51
Q

What do these expressions evaluate to: true | false = ? false | false = ? true | true = ? false | true = ?

A

true false true true

52
Q

What do these expressions evaluate to: true ^ false = ? false ^ false = ? true ^ true = ? false ^ true = ?

A

true false false true

53
Q

What are the short-circuit operators and what do they do?

A

&&, || if the left side is true, then the RHS never gets evaluated. e.g - boolean y = (x >=6) || (++x <=7) the first part of the statement is true thus the RHS will never be evaluated

54
Q

How do you fix the following lines of code: int x = 1.0; short y = 1921222; int z = 9f; long t = 192301398193810323;

A

int x = (int) 1.0; short y = (short)1921222; // Stored as 20678 int z = (int)9f; long t = 192301398193810323L;

55
Q

Is this legal in java? while (true) break;

A

yes it is legal, it prints nothing.

56
Q

What will this print? if (true) System.out.println(1);

A

1 // although the if statement is redundant as the condition is always true

57
Q

What will this print? while (true) System.out.println(1);

A

It will result in an infinite loop, printing 1 until the program runs out of memory and an error occurs

58
Q

What is the structure of a ternary operator?

A

booleanExpression ? expression if true : expression if false

59
Q

What does this code print? public class Test{ public static void testInts(Integer obj, int var){ obj = var++; obj++; } public static void main(String[] args) { Integer val1 = new Integer(5); int val2 = 9; testInts(val1++, ++val2); System.out.println(val1+” “+val2); } }

A

6 10 // Explanation: 1) val1 object with the boxed value of 5 is created. 2) val2 primitive is assigned value 9. 3) Method testInts is invoked. 4) val1++ uses post-increment which implies that you note down the current value of val1, increment it, and then pass a copy of the original noted down value to the method testInts. However inside main, val1 points to 6 now. As val1 is immutable, instead of changing the actual object, a new object is created with the incremented value of 6. val2 original is incremented first to 10. A copy is created (due to pass by value) and is passed as argument two in testInts. Inside of the method: int var which has the value of 10 is assigned to obj which originally had the value of 5 then incremented. So now obj is 11 Since all wrapper classes are immutable, obj++ does nothing. The method ends. Scope of the arguments ends. Original val1 refers to the object with the value of 6, and val2 primitive is 10. Lastly the values in testInts are not reflected in main as they were just copies of the original (pass by value) val1 in main still points to 6 after the call to testInts returns.

60
Q

What class do wrapper classes Byte, Short, Integer, Long, Float and Double extend from?

A

java.lang.Number

61
Q

What is autoboxing?

A

All it means is that if you assign a primitive value to a wrapper variable, the compiler will automatically box the primitive value into a wrapper object. e.g Integer i = 100; or Integer i = new Integer(100); Integer i = new Integer(“100”);

62
Q

What are the ways of creating wrapper objects?

A

1) Constructors- All wrapper classes except Character provide two constructors each one that takes the relevant primitive type and the second one that takes a String . 2) valueOf methods - same case here, all classes bar Character have 2 static methods that take a String or relevant primitive type 3)Autoboxing

63
Q

How do you construct a new Character object using its constructor & valueOf ?

A

Character c = new Character(‘c’); Character c = Character.valueOf(‘c’);

64
Q

What are the 5 ways of creating a new Float object using its constructors and valueOf?

A

Constructors:

Float f = new Float(10.2f); // actual type

Float b = new Float(“10.2”); // using a String

Float c = new Float(10.2); // using a double

valueOf methods:

Float f1 = Float.valueOf(f); // takes float literal

Float f2 = Float.valueOf(“10.2”);

65
Q

Will these compile? Float f2 = Float.valueOf(10.2); // 1 Short s3 = new Short(10); // 1 short s = 10; Short s1 = new Short(s); // 3

A

1) compile error as 10.2 is a double & not accepted by valueOf 2) compile error as 10 is an int 3) compiles successfully

66
Q

What happens if you pass an incorrect value or null to the constructors or valueOf methods?

A

A NumberFormatException will be thrown e.g Integer i = Integer.valueOf(“10.2”) throws an exception

67
Q

What does this code print? Boolean bool = new Boolean(null); Boolean bool1 = Boolean.valueOf(null); System.out.println(bool + “ “ + bool1);

A

false false. you can pass null or any string to Boolean ‘s constructor or valueOf method without any exception.

68
Q

What will the following code print? public class TestClass{ static char ch; static float f; static boolean bool; public static void main(String[] args){ System.out.print(f); System.out.print(“ “); System.out.print(ch); System.out.print(“ “); System.out.print(bool); } }

A

0.0 false float and double have default values of 0.0, empty string, char is also empty and boolean is false

69
Q

Which of the following are false? Boolean.parseBoolean(“true”) == true Boolean.parseBoolean(“TrUe”) == new Boolean(null) new Boolean(“TrUe”) == new Boolean(true) new Boolean() == false new Boolean(“true”) == Boolean.TRUE new Boolean(“no”) == false

A

1) Boolean.parseBoolean(“TrUe”) == new Boolean(null) false because the former will return true and new Boolean(null) will return a Boolean wrapper object containing false. 2) new Boolean(“TrUe”) == new Boolean(true) Even though both the sides have a Boolean wrapper containing true, this returns false as they point to two different Boolean wrapper objects. 3) new Boolean(“true”) == Boolean.TRUE same explanation as point 2. not equal

70
Q

What will be the output of the following program? public class EqualTest{ public static void main(String args[]){ Integer i = new Integer(1) ; Long m = new Long(1); if( i.equals(m)) System.out.println(“equal”); // 1 else System.out.println(“not equal”); } }

A

not equal. The equals takes any object. For all wrapper classes, it first checks if the two object are of same class or not. If not, it immediately return false.

71
Q

What will the following compile? public class TestClass { public static void main(String[] args) { int x = 1____3; //1 long y = 1_3; //2 float z = 3.234_567f; //3 } }

A

yes they will all compile as it is legal to have multiple underscores between 2 digits

72
Q

What will the following program print? public class TestClass{ public static void main(String[] args){ unsigned byte b = 0; b–; System.out.println(b); } }

A

It won’t compile. no keyword as unsigned. A char can be used as an unsigned integer.

73
Q

What happens to uninitialised local variables

A

local variables have to be initialised explicitly if not may cause compile error.. However, it is ok to leave them uninitialised if you don’t use them anywhere in the code

74
Q

Given the following declarations: int a = 5, b = 7, k = 0; Integer m = null; and the following statements: k = new Integer(a) + new Integer(b); //1 k = new Integer(a) + b; //2 k = a + new Integer(b); //3 m = new Integer(a) + new Integer(b); //4 Executed independent of each other, what will be the value of k (for //1, //2, and //3) and m (for //4) after execution of each of these statements?

A

12 12 12 12 In all of these statements, auto-unboxing of integers will occur. For the last statement, after unboxing a and b, the value 12 will be boxed into an Integer object.

75
Q

What will the following code print when run? public class TestClass{ public static Integer wiggler(Integer x){ Integer y = x + 10; x++; System.out.println(x); return y; } public static void main(String[] args){ Integer dataWrapper = new Integer(5); Integer value = wiggler(dataWrapper); System.out.println(dataWrapper+value); } }

A

6 and 20 1. Wrapper objects are always immutable. Therefore, when dataWrapper is passed into wiggler() method, it is never changed even when x++; is executed. 2)When you do x++, it is same as doing x = x + 1; So the original object that was passed was not changed but a new object containing 6 is created and assigned back to x. ‘x’ is a reference. x changes but not the object that was originally pointed to by it. 3. 20 is printed as If both the operands of the + operator are numeric, it adds the two operands. Here, Integer 5 and Integer 15, are unboxed and added.

76
Q

What will this print? System.out.println(new Boolean());

A

This code wont compile as Boolean doesn’t have a no-args constructor, it has two; one that takes a string and the other takes a boolean.

77
Q

true or false: new Boolean(“true”) == new Boolean(“true”) // 1 new Boolean(“true”) == Boolean.parseBoolean(“true”) //2

A

1) false & 2) true When using == with booleans, if exactly one of the operands is a wrapper, it is first unboxed then the two primitives are compared which is why 2 is true. if both are wrappers, then the two objects are compared like normal which returns false.

78
Q

true or false? Integer i1 = 100; Integer i2 = 100; System.out.println(i1 ==i2)

A

true. autoboxing and valueOf methods return cached objects for integral types ranging from -128 -127 instead of creating new instances

79
Q

What will be the output of this program? 1. public class Whiz { 2. static int x = 1; 3. public static void main(String args[]) { 4. int [] nums = {0,1,2,3,4}; 5. for(int x: nums) { 6. System.out.println(x); 7. continue; 8. System.out.println(x + Whiz.x); 9. } 10. } 11. }

A

Compilation will fail due to line 10. Explanation: Using continue implies to the compiler that the print statement on line 10 never gets executed therefore it throws an unreachable statement error.

80
Q

What will be the output of this program? 1. public class Whiz { 2. public static void main(String args[]) { 3. int x = 20 4. while(x > 0) { 5. do { 6. x - = 2; 7. } while (x > 5); 8. x –; 9. System.out.println(x); 10. } 11. } 12. }

A

Answer is 3 0 Explanation: There are 2 loops here, the outer loop starts off with x being 20, it enters the inner do loop where x is decremented by 2 until the condition (x>5) has been met. so x is 18,16,14,12,10,8,6,4. the inner loop exits and outer loop resumes where x is decremented and the output is 3. The outer loops starts again cos (x>0) is true, the inner loop is executed even though x is not greater than 5 as do loops execute at least once. inner loop exits and x which now has the value of 1 is decremented again to 0

81
Q

What will be the output of this program? 1. public class Whiz { 2. public static void main(String args[]) { 3. do { 4. int i = 1; 5. System.out.println(i ++ + “”); 6. } while (x > 5); 7. } 8. }

A

Compilation will fail at line 6. I is out of scope as it has been declared within the body of the do while statement

82
Q

Will this code compile, what will be the output? int x = 10; if (x> 10) System.out.println(“>”); else if(x< 10) System.out.println(“

A

The code will compile and with no output. if statements don’t require curly braces for single statements thus this code is perfectly legal. As neither condition is true, there isn’t an else statement to fall back on thus, nothing is printed

83
Q

What will this code print?

String out = “o”;

int x = -1, y =-5;

if (x< 5)

if(y> 0)

if (x>y)

out += “1”;

else out += “2”;

else out += “3”;

else out += “4”;

System.out.println(out);

A

o3 Explanation: nested if statements, The 2nd if will only be entered if the first if stmt is true. if false, control goes to the first else stmt. here the 3rd if is not entered cos control has gone to the 2nd else stmt.

84
Q

Which one of these ternary statements represent this is statement? int x = 1 ; if (x> 1) System.out.println(“>”); } else if(x< 1) System.out.println(“1 ? “>” : x<1? “1 ? “>” : “1 ? “>” ? “1? “>” ? “

A

A is correct We are combining 2 ternary operators x>1 ? “>” and x<1? “

85
Q

Which of the following will evaluate to false? A. true ^ false | true B. (true ^ false) | true C. (true ^ false | true) D. true ^ (false | true) E. None of the above

A

Correct answer is D. (false | true) = true true ^ true = false A is true - true ^ false = true , true | true = true B and C are the same as A

86
Q

What will be the outcome of this code?

  1. public class Whiz {
  2. public static void main(String args[]) {
  3. final int x ;
  4. x = 0;
  5. final int y = 2;
  6. switch(x) {
  7. case x : {System.out.println(“A”);}
  8. case 1 : System.out.println(“B”);
  9. default : System.out.println(“default”); break;
  10. case y : System.out.println(“C”);
  11. }
  12. }
  13. }
A

Compilation fails on line 7 as x isnt a compile time constant.

A final variable becomes compile time constant when it is declared and initialised in the same line

so final int x = 10; would compile

The curly braces on line 7 dont do anything in switch statements but it is legal to have them

87
Q

What will be the outcome of this code?

  1. public class Whiz {
  2. public static void main(String args[]) {
  3. do{
  4. int i = 1;
  5. System.out.println( i ++ + “”);

6 } while (i < = 5);

7 }

8 }

9 }

A

Compilation fails as i is out of scope on line . As i was declared inside the body of do while statement, it can’t be acessed outside of it

88
Q

What will be the outcome of this code?

  1. public class Whiz {
  2. public static void main(String args[]) {
  3. int x = 2;
  4. for (int x = 0; x<3; x++){
  5. System.out.print(x)
  6. }
  7. }
  8. }
A

Code will not compile as x is being defined twice, first on line 3 and then again on line 4 inside the for loop

89
Q

What will be the outcome of this code?

  1. public class Whiz {
  2. static int x = 10;
  3. public static void main(String args[]) {
  4. for (int x = 0; x<3; x++){
  5. System.out.print(x).
  6. }
  7. System.out.print(x)
  8. }
  9. }
A

123 is the answer.

The for loop gets executed, printing values 1 & 2 and when x gets to 3, the loop terminates as the condition(x<3) is no longer true. On line 7, the final value of x is printed which is 3

90
Q

What will this code print?

// class and main

boolean flag = true;

do {

if(flag = !flag) { //Line 1

System.out.print(1); //Line 2

continue; //Line 3

}

System.out.print(2); //Line 4

} while(flag);

A

It will print 12.

  1. Inside the do-while loop, we enter the if statement on line 1, where flag is assigned true.
  2. 1 is printed and the continue statement skips the rest of the iteration of the do-while loop.
  3. As flag is now true, we enter the second iteration and flag is now set to false. Because of this, the if statement is not entered and we go straight to line 4 to print 2.
  4. The loop then terminates as the condition is now false.