This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from New Boone

 
Rekha Sivadasan
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output for the below given code is 3. It could have easily been 1 also. How is this the method choosen here?
class Test {
public static void main(String[] args) {
Test t = new Test();
t.test(1.0, 2L, 3);
}
void test(double a, double b, short c) {
System.out.println("1");
}
void test(float a, byte b, byte c) {
System.out.println("2");
}
void test(double a, double b, double c) {
System.out.println("3");
}
void test(int a, long b, int c) {
System.out.println("4");
}
void test(long a, long b, long c) {
System.out.println("5");
}
}
Thanks
Rekha
 
Hima Mangal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi rekha..
it couldn't have been 1.. the correct answer is 3) only.. let me explain..
the method signatures for 1) and 3) are :
void test(double a, double b, short c) {
System.out.println("1");
}
void test(double a, double b, double c) {
System.out.println("3");
}
and the method u call is :
t.test(1.0, 2L, 3);
where the first arg is a double, second one is a long and the third one is an integer. Now 1) can't satisfy the method invocation because its third arg is a short and not an int and short cannot be narrowed down to an int implicitly by the compiler EVEN THOUGH IT IS WITHIN PERMISSIBLE LIMITS OF A BYTE LITERAL.
hope this helps..

------------------
Hima
 
Axel Janssen
Ranch Hand
Posts: 2166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rekha,
method call is: t.test(1.0, 2L, 3);
I think 3 is actually treated as an int. And signature
void test(double a, double b, short c)
(returns "3")
would be an narrowing conversion.
Corect me if I'm wrong,
Axel
 
Axel Janssen
Ranch Hand
Posts: 2166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry I muddled up the two methods. I agree with Hima.
 
S Dave
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
u could also go through the following thread for a similar discussion:
http://www.javaranch.com/ubb/Forum24/HTML/008618.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic