Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1089

Posted: Wed May 08, 2019 2:34 am
by andripos
Explanation

1. i = (int) k.shortValue();   --> You can use *= here but then you can't complete the 4th line.
2. str += b; -->  You can't use =, or *= here. Only += is valid.
3. b = !b; --> You can't use anything other than = here.
4. c *= i; --> You can only use *= or +=. = is not valid. Further, if you use += here, you can't complete line 2.
But it compile
1. i *= (int) k.shortValue();
4. c *= i;

Re: About Question enthuware.ocajp.i.v8.2.1089

Posted: Wed May 08, 2019 2:52 am
by admin
Yes, but if you use *= on 1st line, how will you complete the 4th?

Re: About Question enthuware.ocajp.i.v8.2.1089

Posted: Wed May 08, 2019 3:04 am
by andripos

Code: Select all

Short k = 9; Integer i = 9; Boolean b = false;
        char c = 'a'; String str = "123";

        i *= (int) k.shortValue();
        str += b;
        b = !b;
         c *= i;

        System.out.println(c);
will print '?'

Re: About Question enthuware.ocajp.i.v8.2.1089

Posted: Wed May 08, 2019 5:00 am
by admin
You can't use *= more than once in this question.

Re: About Question enthuware.ocajp.i.v8.2.1089

Posted: Mon Sep 16, 2019 5:50 am
by timwaagh
I can use some explanation as to why you cannot assign a boolean to a String, but can do += (concatenate and assign). And also why we cannot assign an int to a char, but can do += (add and assign).

Re: About Question enthuware.ocajp.i.v8.2.1089

Posted: Mon Sep 16, 2019 6:13 am
by admin
A String variable is a reference type and a boolean is a primitive, so, you cannot assign a boolean value to String variable. Thus, str = b; will not compile.

+= is a special operator in Java, which translates to concatenation and assignment. So, str += b becomes str = str + b;
Now, + operator is overloaded in Java. If one of the operands of + is a string, it converts the other operand into a string and concatenates the two string to produce a new string. In this case, b's value is converted to String. Therefore, it is ok to assign the string produced by str + b to be assigned back to str.

This is usually explained well in all certification books. Which book are you following? You may start with this book if you don't want to spend too much.