Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dan exam dought 5

 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys
in one question of DAN ...

class Sienna {
static double a; static float b; static int c; static char d;
public static void main(String[] args) {
a = b = c = d = 'a';
System.out.println(a+b+c+d == 4 * 'a');
}}

What is the result of attempting to compile and run the program?

a. Prints: true
b. Prints: false
c. Compile-time error
d. Run-time error
e. None of the above


its answer is "a"

with explanations
The literal, 'a', is promoted to type int; and is then multiplied by the value of the left operand, 4. If one of the two operands of a numeric expression is of type int, then the other operand will be promoted to type int if it is of type short, char or byte.


----------------
the above explanation is true but its only half explantion... !!!

but why "a" and not "b" ??
as in above question... left side of == operator will be changed into double .... and which is not equalant to interger no. on the right hand side...




pls correct my post ...if wrong ...

thanx
 
Akash Roy
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

During == operator implicit widening takes place. Hence the Integer on the right side gets promoted to double.

Regards,
 
Carol Enderlin
drifter
Ranch Hand
Posts: 1364
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit,

Did you try compiling and running the code? Playing around with it a little to see what it is doing? (see code below, I added a couple of print statements since I didn't remember what int value 'a' had and wanted to "SEE IT".)

If the == part was confusing, how about this:

1. static double a; static float b; static int c; static char d;
2. a = b = c = d = 'a';

Line 2 assigned a char to a char to an int to a float to a double!


 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx a ton Carol Enderlin

regards
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic