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

Doubt in question

 
Patr�cia Oliveira
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I saw this question in javablackbelt but I didn't understand the answer. Can someone explain it to me?

You have defined the following methods:

public void print(int val) {
System.out.println("int");
}

public void print(long val) {
System.out.println("long");
}

public void print(float val) {
System.out.println("float");
}

public void print(double val) {
System.out.println("double");
}

What will be printed after running this code fragment?

1: print('x');
2: print(10);
3: print(1 / 3);

The answer is:
int
int
int

I didn't understand the third print.

Thanks,

Pati
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whole numbers are considered ints.

The division of an int by an int is an int.

So 1/3 = 0.

So the method that accepts an int is the most specific for 0.
 
Patr�cia Oliveira
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for reply. Now I understood it.
 
S Thiyanesh
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To invoke print(double) version try print(1/3.0)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic