This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Argument Scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Argument Scope" Watch "Argument Scope" New topic
Author

Argument Scope

Dominic Choo
Greenhorn

Joined: Jan 30, 2003
Posts: 26
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

Joined: Aug 22, 2003
Posts: 61
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

Joined: Feb 12, 2002
Posts: 89
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.


The Code is the Programmer
Dominic Choo
Greenhorn

Joined: Jan 30, 2003
Posts: 26
Thanks Richard and Uma.
 
 
subject: Argument Scope
 
Similar Threads
Dan's Mock Exam
doubt in method argument declared final
compile time constant doubt
Compile-time Constants
primitive widening doubt