Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Argument Scope

 
Dominic Choo
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across this question:
==========================================================
class B {
static int m1(byte b) {;
return b; // 1
}
static int m2(char c) {;
return c; // 2
}
static int m3(short s) {
return s; // 3
}
static int m4(long l) {
return l; // 4
}
static int m5(float f) {
return f; // 5
}
public static void main(String[] args) {
byte b = 1;
char c = 'c'-'a';
short s = 3;
long l = 4L;
float f = 5.0f;
System.out.print(""+m1(b)+m2(c)+m3(s)+m4(l)+m5(f));
}
}
What is the result of attempting to compile and run the program?
a. Prints: 12345
b. Prints: 12345.0
c. Prints: 15
d. Prints: 15.0
e. Compiler Error at 1.
f. Compiler Error at 2.
g. Compiler Error at 3.
h. Compiler Error at 4.
i. Compiler Error at 5.
j. Runtime Error
k. None of the Above
==========================================================
Why the answer is h and i since all the type of argument match the method parameters ?
Rgds,
Dominic
 
Uma Balu
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Answer is h and i, 'coz in the methods m4 and m5, long and float are been sent back to the caller as int, so, there will be precision loss, try down casting long and float to int before you return, the code will compile and the output will be 12345.
class B {
static int m1(byte b) {;
return b; // 1
}
static int m2(char c) {;
return c; // 2
}
static int m3(short s) {
return s; // 3
}
static int m4(long l) {
return (int)l; // 4
}
static int m5(float f) {
return (int)f; // 5
}
public static void main(String[] args) {
byte b = 1;
char c = 'c'-'a';
short s = 3;
long l = 4L;
float f = 5.0f;
System.out.print(""+m1(b)+m2(c)+m3(s)+m4(l)+m5(f));
}
}
Thanks,
Uma.
 
Richard Teston
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dominic,
Because you are returning large pattern of number into small one. In the code above method(long l) and method(float f) has a return type of int. You have to explicitly cast the return variable into int (also called narrowing converion)e.g. return (int)l to clear away the compile error.
 
Dominic Choo
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Richard and Uma.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic