2 Operators and Statements Flashcards

1
Q

Numeric Promotion Rule 1

A
  1. If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Numeric Promotion Rule 2

A
  1. If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Numeric Promotion Rule 3

A
  1. Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.

For the third rule, note that unary operators are excluded from this rule.

For example, applying ++ to a short value results in a short value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Numeric Promotion Rule 4

A
  1. After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the data type of x * y?
int x = 1;
long y = 33;

A

If we follow the first rule, since one of the values is long and the other is int, and long is larger than int, then the int value is promoted to a long, and the resulting value is long.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the data type of x + y?
double x = 39.21;
float y = 2.1;

A

This is actually a trick question, as this code will not compile!
Floating-point literals are assumed to be double, unless postfixed with an f, as in 2.1f.

This means that you have two ways of initialising floats.
either with an integral number or a floating point with f/F in the end, both valid.
First one because an int is promoted to floating point.

So float y = 2.1; // Wont compile

If the value was set properly to 2.1f, then the promotion would be similar to the last example, with both operands being promoted to a double, and the result would be a double value, because double olds 64 bits while float olds 32 bits.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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

A

In this case, we must apply the third rule, namely that x and y will both be promoted to int before the operation, resulting in an output of type int.
Pay close attention to the fact that the resulting output is not a short.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the data type of x * y / z?
short x = 14;
float y = 13;
double z = 30;

A

In this case, we must apply all of the rules. First, x will automatically be promoted to int solely because it is a short and it is being used in an arithmetic binary operation.

The promoted x value will then be automatically promoted to a float so that it can be multiplied with y.

The result of x * y will then be automatically promoted to a double, so that it can be multiplied with z, resulting in a double value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Working with Unary Operators

A

Working with Unary Operators

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is an unuary operator?

A

A unary operator is one that requires exactly one operand, or variable, to function.
They often perform simple tasks, such as increasing a numeric variable by one, or negating a boolean value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which unuary operators exist in Java?

A

+, - , ++ , – , !
+ -> Indicates a number is positive, although numbers are assumed to be positive in Java unless accompanied by a negative unary operator.

  • (minus) Indicates a literal number is negative or negates an expression

++ Increments a value by 1

– Decrements a value by 1

! Inverts a Boolean’s logical value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Increment and Decrement Operators

A

Increment and Decrement Operators

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Common practice in a certification exam, question

int x = 3;
int y = ++x * 5 / x– + –x;
System.out.println(“x is “ + x);
System.out.println(“y is “ + y);

A

So how do you read this code?
First, the x is incremented and returned to the expression, which is multiplied by 5.

We can simplify this:
int y = 4 * 5 / x– + –x; // x assigned value of 4

Next, x is decremented, but the original value of 4 is used in the expression, leading to
this:

int y = 4 * 5 / 4 + –x; // x assigned value of 3

The final assignment of x reduces the value to 2, and since this is a pre-increment opera-
tor, that value is returned to the expression:

int y = 4 * 5 / 4 + 2; // x assigned value of 2

Finally, we evaluate the multiple and division from left-to-right, and finish with the addi- tion. The result is then printed:
x is 2
y is 7

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Assignment Operators

A

An assignment operator is a binary operator that modifies, or assigns, the variable on the left-hand side of the operator, with the result of the value on the right-hand side of the equation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Can larger dat types be assigned to smaller datatypes?

A

Java will automatically promote from smaller to larger data types, as we saw in the pre- vious section on arithmetic operators, but it will throw a compiler exception if it detects you are trying to convert from larger to smaller data types.

int x = 1.0; // DOES NOT COMPILE ( double 64 bits to int 32 bits)

short y = 1921222; // DOES NOT COMPILE (is outside of
the range of short which is-32,768 to 32,767)

int z = 9f; // DOES NOT COMPILE ( floating-point value)

long t = 192301398193810323; // DOES NOT COMPILE
(because the declaration doesn’t have L in the end, java interprets the long as an int nd notices that the value is larger than int allows )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

In Java, there are two types of casting..

Whaats the order

A
Widening Casting (automatically) - converting a smaller type to a larger type size:
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What would be the resulting type of this operation?
short x = 10;
short y = 3;
short z = x * y;

A

short z = x * y; // DOES NOT COMPILE

Smaller types are automatically casted to int, so x and y will become ints.
Following the rules a larger type does not fit in a smaller type.
To make this compile an explicit casting to short would have to be made:

short z = (short)(x * y);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Compound Assignment Operators

A

Only two of the compound operators listed in Table 2.1 are required for the exam, += and -=.

x = x * z; // Simple assignment operator
x *= z; // Compound assignment operator

The left-hand side of the compound operator can only be applied to a variable that is already defined and cannot be used to declare a new variable. In the previous example, if x was not already defined, then the expression x *= z would not compile.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What’s the alternative for this operation that will makes avoid an explicit casting?

long x = 10;
int y = 5;
y = y * x; //DOES NOT COMPILE

A

Compound operators are useful for more than just shorthand—they can also save us from having to explicitly cast a value.

long x = 10;
int y = 5;
y = y * x; // DOES NOT COMPILE

This last line could be fixed with an explicit cast to (int), but there’s a better way using the compound assignment operator:

long x = 10;
int y = 5;
y *= x;

The compound operator will first cast x to a long, apply the multiplication of two long values, and then cast the result to an int.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

One final thing to know about the assignment operator is that the result of the assign- ment is an expression in and of itself, equal to the value of the assignment.

long x = 5;
long y = (x=3);
System.out.println(x); // Outputs 3
System.out.println(y); // Also, outputs 3

A

For example, the following snippet of code is perfectly valid, if not a little odd looking:
long x = 5;
long y = (x=3);
System.out.println(x); // Outputs 3
System.out.println(y); // Also, outputs 3

The key here is that (x=3) does two things.
First, it sets the value of the variable x to be 3.
Second, it returns a value of the assignment, which is also 3.

The exam creators are fond of inserting the assignment operator = in the middle of an expression and using the value of the assignment as part of a more complex expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Relational operators

A

< Strictly less than

<= Less than or equal to

> Strictly greater than

> = Greater than or equal to

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

instanceof rules

A
1. The instanceof operator cannot tell you the exact type of the object being pointed to by a variable. 
It can only tell you whether that object is-a something. For example, if you do finstanceof Fruit, it will return true if the object referred to by f is-a Fruit, which means it will return true even if f points to a Mango because a Mango is-a Fruit. In the case of interfaces, it will return true if the class of the object pointed to by the reference implements the given interface (directly or indirectly).
  1. The compiler will let you use instanceof operator only if it is possible for the variable to refer to an object of the type given on the right-hand side, with exception for interfaces which are accepted even if there isno relation on the type.

For example, f instanceof Mango is valid because the compiler knows that the declared type of f is Fruit and since Mango is a Fruit, it is possible for f to point to a Mango. But f instanceof String will not compile because the compiler knows that there is no way f can ever point to a String. The instanceof operator behaves the same way as the cast operator in this respect.

Summing up:

when using instanceof operator pay attention to 2 details:

  • The left operand of instanceof MUST be a reference variable and not a primitive.
  • Right operand of instanceof MUST be a reference type name, i.e., a class, an interface, or an enum name.
  • the class must have a is-a relation with the left-hand side object however if it is an interface the is-a relation is not mandatory - IMPORTANT

2 the instanceof can only tell you if an object is of a certain type, and returns a boolean, however keep in mind that

3 if the right hand side is an interface, even if there is no relation ( is-a ), it the class of the object doesn’t implements that interface, it will compile fine. and return false.

interface Flyer{ }
class Bird implements Flyer {}
class Eagle extends Bird{ }
class Bat {}
        Flyer f = new Eagle();
        Eagle e = new Eagle();
        Bat b = new Bat();
    if(f instanceof Flyer) System.out.println("f is a Flyer");
    if(e instanceof Bird) System.out.println("e is a bird");
    if(b instanceof Flyer) System.out.println("bis a Flyer");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Logical operators

A

x^y (EXCLUSIVE OR)
x&y (AND)
x | y (INCLUSIVE OR)

Here are some tips to help remember:

  • AND is only true if both operands are true.
  • Inclusive OR is only false if both operands are false.
  • Exclusive OR is only true if the operands are different.
24
Q

Short circuit operators

A

&& and ||, which are often referred to as short-circuit operators.
The short-circuit operators are nearly identical to the logical opera- tors, & and |, respectively, except that the right-hand side of the expression may never be evaluated if the final result can be determined by the left-hand side of the expression.

boolean x = true || (y < 4);

because the first is already true, the second part wont be evaluated

if(x != null &amp;&amp; x.getValue() < 5) { 
// Do something
}
In this example, if x was null, then the short-circuit prevents a NullPointerException from ever being thrown, since the evaluation of x.getValue() < 5 is never reached.
25
Q

Equality Operators

A

The equality operators are used in one of three scenarios:

  1. Comparing two numeric primitive types. If the numeric values are of different data types, the values are automatically promoted as previously described. For example, 5 == 5.00 returns true since the left side is promoted to a double.
  2. Comparing two boolean values.
  3. Comparing two objects, including null and String values.

The comparisons for equality are limited to these three cases, so you cannot mix and match types. For example, each of the following would result in a compiler error:

boolean x = true == 3; // DOES NOT COMPILE
boolean y = false != “Giraffe”; // DOES NOT COMPILE boolean z = 3 == “Kangaroo”; // DOES NOT COMPILE

Any two numeric primitives can be compared using == operator.
Even a numeric primitive and a primitive wrapper (for example, an int with a Short or a Double) can be compared.
However, two wrappers of different types (for example, an Integer and a Short) cannot be compared using ==.

26
Q

EXAM TRICKS WITH EQUALITY AND ASSIGNEMENT OPERATORS

A

The exam creators also have a habit of mixing assignment operators and equality opera- tors, as in the following snippet:

boolean y = false;

boolean x = (y = true); // y is assigned first since parentisis have precedence over assigment

System.out.println(x); // Outputs true

27
Q

Equality operator with objects

A

For object comparison, the equality operator is applied to the references to the objects, not the objects they point to.
Two references are equal if and only if they point to the same object or both point to null.

File x = new File("myFile.txt");
File y = new File("myFile.txt");
File z = x;
System.out.println(x == y); // Outputs false System.out.println(x == z); // Outputs true
28
Q

if statement tricks exam

A

One area that the exam writers will try to trip you up is on if-then statements without braces ({}). For example, take a look at this slightly modified form of our example:

if(hourOfDay < 11)
System.out.println(“Good Morning”);
morningGreetingCount++;

static final boolean DEBUG = false;

if(false) // compiles
if(DEBUG) //also compiles even with debig being false and final
while(false ) // does not compile unreachable code

29
Q

Ternary Expression Evaluation - similar to short circuit operator or an if then-else

A

As of Java 7, only one of the right-hand expressions of the ternary operator will be evalu- ated at runtime. In a manner similar to the short-circuit operators, if one of the two right- hand expressions in a ternary operator performs a side effect, then it may not be applied at runtime.

int y = 1;
int z = 1;
final int x = y<10 ? y++ : z++;
System.out.println(y+”,”+z); // Outputs 2,1

For the exam, be wary of any question that includes a ternary expression in which a variable is modified in one of the right-hand side expressions.

int y = 1;
int z = 1;
final int x = y>=10 ? y++ : z++; // condition false only else evaluated
System.out.println(y+”,”+z); // Outputs 1, 2

30
Q

The switch Statement

A

A switch statement, as shown in Figure 2.4, is a complex decision-making struc- ture in which a single value is evaluated and flow is redirected to the first matching branch, known as a case statement. If no such case statement is found that matches the value, an optional default statement will be called.

31
Q

Supported Data Types in a switch statement

A
byte and Byte - 8 bits
short and Short - 16 bits
char and Character  16 bits
int and Integer 32 bits
String 
Enum values

Note that boolean and long, and their associated wrapper classes, are not supported by switch statements.

32
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
Signature of equals method is : 
boolean equals(Object o); 

So it can take any object.

The equals methods of all wrapper classes first check if the two object are of same class or not. If not, they immediately return false. Hence it will print not equal.

33
Q

what’s the signature of the equals method and how it works?

A
Signature of equals method is : 
boolean equals(Object o); 

The equals methods of all wrapper classes first check if the two object are of same class or not. If not, they immediately return false.

Hence it will print not equal.

34
Q

Whats the type that results from this expression?

A

float d = 0 * 1.5f; and
float d = 0 * (float)1.5 ; are OK

An implicit narrowing primitive conversion may be used if all of the following conditions are satisfied:

  1. The expression is a compile time constant expression of type byte, char, short, or int.
  2. The type of the variable is byte, short, or char.
  3. The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

Note that implicit narrowing conversion does not apply to long or double.

So, char ch = 30L; will fail even though 30 is representable in char.

35
Q

How do you assign an octal number to a long or any other integral type?

A

long g = 012 ;

012 is a valid octal number.

Literals with a leading zero are octal literals.
Any number prefixed with a 0 is considered octal.
Octal numbers can only use digits 0-7, just like decimal can use 0-9, and binary (ex. 0b010) can use 0-1.

36
Q

Are. this two varibles considered to have the exact same value?
int x = 1_000_000;
int y = 1000000;

A

Adding underscores doesn’t actually change the number. The compiler ignores the underscores. So 1_000_000 and 1000000 are actually same.

37
Q

Does the code compile? if so, what’s the output?
If not which lines make the code fail to compile?

int value = 1,000,000; //1

switch(value){             
case 1_000_000 : 
           System.out.println("A million 1"); //2                 
           break;             
case 1000000 : 
           System.out.println("A million 2"); //3                 
           break;         
}

Does the code

A
  1. You may use underscores (but not commas) to format a number for better code readability.
    So //1 is invalid.
  2. Adding underscores doesn’t actually change the number.
    The compiler ignores the underscores.
    So 1_000_000 and 1000000 are actually same and you cannot have two case blocks with the same value.

Therefore, the second case at //3 is invalid.

You may use underscore for all kinds of numbers including
long, double, float, binary, as well as hex.
For example, the following are all valid numbers -
int hex = 0xCAFE_BABE;
float f = 9898_7878.333_333f;
int bin = 0b1111_0000_1100_1100;

38
Q

What will the an instance variable type char, not initialize print when sout is called?

char c ;
System.out.println(c);

A

For char, the print/println methods translate the character into one or more bytes according to the platform’s default character encoding.

That is why while printing a char value of 0, a blank space is printed instead of 0 (even though the char’s integral value is 0).

  1. the default values that are given to variables of various primitive types. You should remember that all numeric types, including char, get the value of 0 (or 0.0 for float and double) and boolean gets the value of false.
  2. how the value is printed by System.out.print method - java.lang.System class has a public static variable named out, which is of class java.io.PrintStream.The PrintStream class has multiple print/println methods for printing out primitive values as well as objects. Remenber that sout with print wont compile if doesn’t have parameters.

For byte, short, and int, these print/println methods simply print the integer value as it is.

For long, float, and double values, these print/println methods use the respective primitive wrapper class’s toString method to get the String representation of that primitive.
For example, to print the value of a float variable f, it internally calls Float.toString(f).
Now, this method doesn’t append an “f” at the end of a float value.
That is why a float value of 0.0 is printed as 0.0 and not 0.0f.

Example:
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); 
 } 
}
39
Q

Garbage collector rules:

A

The official exam objectives now explicitly mention Garbage collection. All you need to know is:

  1. An object can be made eligible for garbage collection by making sure there are no references pointing to that object.
  2. You cannot directly invoke the garbage collector. You can suggest the JVM to perform garbage collection by calling System.gc();
40
Q

Switch statemenet rules:

A

Here are the rules for a switch statement:

  1. Only String, byte, char, short, int, (and their wrapper classes Byte, Character, Short, and Integer), and enums can be used as types of a switch variable. (String is allowed only since Java 7).
  2. The case constants must be assignable to the switch variable. For example, if your switch variable is of class String, your case labels must use Strings as well.
  3. The switch variable must be big enough to hold all the case constants. For example, if the switch variable is of type char, then none of the case constants can be greater than 65535 because a char’s range is from 0 to 65535.
  4. All case labels should be COMPILE TIME CONSTANTS.
  5. No two of the case constant expressions associated with a switch statement may have the same value.
  6. At most one default label may be associated with the same switch statement.
41
Q

Is this a valid declaration?

short condition = new Short(1);

A

This is almost a valid option but for the fact that 1 is an int and you can’t instantiate a Short object with an int argument.

It will, therefore, not compile. short condition = new Short((short)1); would have been valid

42
Q

Consider the following method…

Does this code compile?
If so what will be printed if is passed false as argument?

public static void ifTest(boolean flag){
   if (flag)   //1
   if (flag)   //2
   if (flag)   //3
   System.out.println("False True");
   else        //4
   System.out.println("True False");
   else        //5
   System.out.println("True True");
   else        //6
   System.out.println("False False");
}
A

If run with an argument of ‘false’, it will print ‘False False’

It will never print ‘True True’ because on the first if , the flag is true then will be true for all if is false the last else will print immediately.

Note that if and else do not cascade. They are like opening an closing brackets. So, else at //4 is associated with if at //3 and else at //5 is associated with if at //2

This code is the same as the code below..

public static void ifTest(boolean flag){
   if (flag)   //1
   if (flag)   //2
   if (flag)   //3
   System.out.println("False True");
   else        //4
   System.out.println("True False");
   else        //5
   System.out.println("True True");
   else        //6
   System.out.println("False False");
}
 if (flag)      //1
   {
       if (flag)       // 2
       {
            if (flag)        //3
            {
                  System.out.println("False True");
            }
            else            //4
            {
                  System.out.println("True False");
            }
       }
       else           //5
       {
             System.out.println("True True");
       }
   }
  else           //6
  {
        System.out.println("False False");
   }
43
Q

Consider the following program:

public class TestClass{
   public static void main(String[] args)  {     calculate(2);    }
   public static void calculate(int x){
      String val;
      switch(x){
         case 2:
         default:
         val = "def";
      }
      System.out.println(val);
   }
}
What will happen if you try to compile and run the program?

It will not compile saying that variable val may not have been initialized.
It will compile and print def
As such it will not compile but it will compile if calculate(2); is replaced by calculate(3);
It will compile for any int values in calculate(…);

A

When you try to access a local variable, the compiler makes sure that it is initialized in all the cases.

If it finds that there is a case in which it may not be initialized then it flags an error.

For example:
int i;
if( somecondition) i = 20;
int k = I;

Here, if some condition returns false, then i remains uninitialized hence the compiler flags an error.

In the given question:

As there is no break after case 2, val will always be initialized in the switch block.

So it will compile and run fine.

Note that it will not compile if break is placed after case 2 because the compiler will figure out that in certain cases val may be left uninitialized.

44
Q

Is it possible for an if/else or if/else if cimbines curly braces sintax with no curly braces on the same structure?

A

Yes it is.
Note the last else doesn’t have curly braces. So this is a valid sintax.

if (true){
}else if (false){
}else System.out.println();

This is also valid:

Note that a comma is considered an instruction.. So an empty if or else block with only a ; is valid and compiles.
Also remember that unreachable code doesn’t affect if’s, due to use cases like feature switch flags for example.

if (true) ;
        else if (false) System.out.println();
        else {
            System.out.println();
        }
45
Q

Rules for ternary operators ?

A
  1. the cases must return something. so method calls must not be void. a value is something, a string as well.
46
Q

What will happen on running the following program?

public class DatabaseWrapper {   
 static String url = "jdbc://derby://localhost:1527//mydb";   
 static DatabaseWrapper getDatabase()   {      
   System.out.println("Getting DB");      
   return null;  
  }   
public static void main(String[ ] args)   {     
    System.out.println( getDatabase().url );   
  } 
}
A

answer:

It will print:

Getting DB and jdbc://derby://localhost:1527//mydb without throwing an exception.

Note:
Things to retain: methods can return null, if they return a reference type. 
If the class being returned have static members, those members may be accessed with the method_call -> dot_operator -> static_member. mymethod.staticMember()

This question demonstrates that a null reference may be used to access a class (static) variable without causing an exception .

Note the method signature. It returns a reference to an object of class DatabaseWrapper.

Thus, getDatabase().url means we are accessing url field of the object returned by the method.

Now, since the class of the object returned by the method is DatabaseWrapper and the field url is a static field of the class, the compiler creates the instruction for the JVM to access this field directly using the class reference instead of the object reference returned by the method at runtime.

Thus, the JVM does not need to depend on the actual object returned by the method at run time to access URL.

So even if the method returns null at run time, it doesn’t matter because the JVM doesn’t even access the reference returned by the method

47
Q

Consider the following class:

class TestClass{
    void probe(int... x) { System.out.println("In ..."); }  //1
void probe(Integer x) { System.out.println("In Integer"); } //2

void probe(long x) { System.out.println("In long"); } //3 

void probe(Long x) { System.out.println("In LONG"); } //4
    public static void main(String[] args){
        Integer a = 4; new TestClass().probe(a); //5
        int b = 4; new TestClass().probe(b); //6
    }
}
What will it print when compiled and run?
A

In Integer and In long
It will not compile, if //1, //2, and //3 are commented out.

To answer this type of questions, you need to know the following rules:

  1. The compiler always tries to choose the most specific method available with least number of modifications to the arguments.
  2. Java designers have decided that old code should work exactly as it used to work before boxing-unboxing functionality became available.
  3. Widening is preferred to boxing/unboxing (because of rule 2), which in turn, is preferred over var-args.

Thus,

  1. probe(Integer) will be bound to probe(Integer) (exact match). If that is not available, it will be bound to probe(long), and then with probe(int…) in that order of preference.

probe(long) is preferred over probe(int…) because unboxing an Integer gives an int and in pre 1.5 code probe(long) is compatible with an int (Rule 2).

It is never bound to probe(Long ) because Integer and Long are different object types and there is no IS-A relation between them. IMPORTANT (This holds true for any two wrapper classes).

It could, however, be bound to probe(Object ) (if it existed), because Integer IS-A Object.

  1. probe(int) is bound to probe(long) (because of Rule 2) , then to probe(Integer ) because boxing an int gives you an Integer, which matches exactly to probe(Integer), and then to probe(int…).

It is never bound to probe(Long ) because int is not compatible with Long.

We advise you to run this program and try out various combinations.

The exam has questions on this pattern but they are not this tough. If you have a basic understanding, you should be ok.

48
Q

Abstract Classes points to remember

A
Here are some points to remember:  
A class is uninstantiable if the class is declared abstract. 

If a method has been declared as abstract, it cannot provide an implementation (i.e. it cannot have a method body ) and the class containing that method must be declared abstract).

If a method is not declared abstract, it must provide a method body (the class can be abstract but not necessarily so).

If any method in a class is declared abstract, then the whole class must be declared abstract.

An class can still be made abstract even if it has no abstract method.

49
Q

Interfaces rules

A

1 - All methods that you declare in an interface can have ‘ static ’, ‘ default ’ or ‘ abstract ’ modifiers ( Since Java 8 ). Implicitly they are ‘ public abstract ’.

2 - Since Java 8, methods can be implemented ( can have a code body ) in an interface if only if it is declared static or default. Abstract methods cannot have a body; all they can have is a method signature as shown in the example above.

3 - Variables are not allowed in interface. Hence any data declaration is ‘ public static final ’; hence only constants.

4 - Interfaces can extend other interfaces ( one or more ) but not classes ( abstract or not ).

5 - Interfaces cannot be instantiated as they are not concrete classes.

6 - Methods and constants cannot be declared ‘ private ’, methods cannot be declared ‘ final ’.

50
Q

Abstract classes rules

A

1 - A class can be an abstract class without having any methods inside it. But if it has any methods inside it, it must have at least one abstract method. This rule does not apply to static methods.

2 - As abstract classes can have both abstract and non abstract methods, hence the abstract modifier is necessary here ( unlike in interface where only abstract methods are allowed ).

3 - Static members are allowed. (Fields and methods)

4 - Abstract classes can extend other at most one abstract or concrete class and implement several interfaces.

5 - Any class that does not implement all the abstract methods of it’s super class has to be an abstract class itself.

51
Q

Consider the following class :

public class Parser{
   public static void main( String[] args){
       try{
           int i = 0;
           i =  Integer.parseInt( args[0] );
       }
       catch(NumberFormatException e){
          System.out.println("Problem in " + i );
       }
   }
}
What will happen if it is run with the following command line:
java Parser one
A

It will not even compile.

Because ‘i’ is defined in try block and so it is not visible in the catch block.

So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

Local variables − These variables belong to and declared/defined within the methods/blocks/constructors. The scope of these variables lies within the method (or, block or, constructor) and will be destroyed after he execution of it

52
Q

How do we assign a binary value?

A

If you want to write a value in binary, it must be prefixed with 0b or 0B.

You may use underscore for all kinds of numbers including long, double, float, binary, as well as hex.
For example, the following are all valid numbers -
int hex = 0xCAFE_BABE;
float f = 9898_7878.333_333f;
int bin = 0b1111_0000_1100_1100;

53
Q

null on object references

A

printing a non initialized instance reference will return null and not NullPointerException

54
Q

Operators precedence

A
  1. postfix increment and decrement ++ –
  2. prefix increment and decrement, and unary ++ – + - ~ !
  3. multiplicative * / %
  4. additive + -
  5. shift &laquo_space;»&raquo_space;>
  6. relational < > <= >= instanceof
  7. equality == !=
  8. bitwise AND &
  9. bitwise exclusive OR ^
  10. bitwise inclusive OR |
  11. logical AND &&
  12. logical OR ||
  13. ternary ? :
  14. assignment = += -= *= /= %= &= ^= |= «=&raquo_space;=&raquo_space;>=
55
Q

Associativity of Operators in Java

A

If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left). Let’s take an example.

a = b = c;

Here, the value of c is assigned to variable b. Then the value of b is assigned of variable a.

56
Q

floating points in binary (important)

A

float x = 0b10_000f;
This is invalid because the floating point suffices f, F, d, and D are used only when using decimal system and not while using binary.

However, since f is a valid digit in hexadecimal system, a hex number may end with an f although it will not be interpreted as float but as the digit f.

Thus, float x = 0x10_000f;
and float x = 10_000f;
are valid because they are written in hex and decimal respectively but float x = 0b10_000f;is invalid because is written in binary.

Note that a floating point number cannot be written in Octal.

Therefore, float x = 010_000f; is valid but it is not octal even though it starts with a 0. It is interpreted in decimal.

A floating point number written in binary or hex cannot use any suffix for float. But a floating point number written in decimal can use the floating point suffices f, F, d, and D. Thus, float dx = 0xff; is valid but the f here is not for indicating that it is a float but is interpreted as the hex digit F.

57
Q

Unnitialized vars in methods:

A
  1. Java doesn’t have a problem if you have uninitialized variables as long as you don’t try to use them. That is why the first code compiles even though the variables have not been initialized.
  2. Java initializes static and instance variables to default values if you don’t initialize them explicitly. That is why the second code prints 0 0.
  3. Java doesn’t initialize local variables if you don’t initialize them explicitly and it will not let the code to compile if you try to use such a variable. That is why the third code doesn’t compile.