Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Math.max(), Math.min()

 
M Rama
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Math.max( 5, (long) 5);

what primitive type would the result be in? Is there a way to check the primitive type, like we check the Objects with instanceof?
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have to check primitive types. Whatever you write it as that's what it is. For example you can put an int value into a long, but then it is a long and not an int.

In your example, because you cast one to a long, it should call the method Math.min(long, long) (closest match) which returns a long.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The result is a long.

To get the compiler's view of the expression type, put this in your program and read the error message:
boolean t = Math.max( 5, (long) 5);
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi rama

Its return type is long

to justify my statement

if u assign to int it shows error like this

int a = Math.max( 5, (long) 5);
System.out.println(a);

test.java:31: possible loss of precision
found : long
required: int
int a = Math.max( 5, (long) 5);


if we go with long ...no prob

long a = Math.max( 5, (long) 5);
System.out.println(a);

we checked it in indirect way...
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While a primitive variable's type may be saved in a debugging symbol table (javac -g), the type of an expression is a compile-time notion, so there is nothing to test at execution time.

You can look at the generated bytecode with javap and see what the compiler did with your expression. In this case, it's pretty obvious that Java created bytecode for a long expression. Try it yourself.
[ April 12, 2005: Message edited by: Mike Gershman ]
 
M Rama
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic