File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes impicit narrowing in method arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "impicit narrowing in method arguments" Watch "impicit narrowing in method arguments" New topic
Author

impicit narrowing in method arguments

Vaibhav Chauhan
Ranch Hand

Joined: Aug 16, 2006
Posts: 115
why java prevents impicit narrowing in types of method arguments ??

//code

public class MethodArgumentImplicitCast {

public static void main(String[] argv)
{
MethodArgumentImplicitCast i=new MethodArgumentImplicitCast();
System.out.println(i.Omb(2));
}
public int Omb(byte f)
{
System.out.println("from byte");
return (f+1);
}
}

ans.:complile error
2 is constant which falls in the range of byte.What is the possible error which compiler doesn't allow to occur.
amal shah
Ranch Hand

Joined: May 05, 2006
Posts: 92
public class MethodArgumentImplicitCast {

public static void main(String[] argv)
{
MethodArgumentImplicitCast i=new MethodArgumentImplicitCast();
System.out.println(i.Omb((byte)2)); //correction
}
public int Omb(byte f)
{
System.out.println("from byte");
return (f+1);
}
}

though value 2 is in range of a byte....it's defualt type is int...so int cannot be implicitly casted to byte..above correction would work

thanking you
amal shah
Dave Reinhardt
Ranch Hand

Joined: Aug 07, 2006
Posts: 54
public class ImplicitCast {

public static void main(String[] argv)
{
ImplicitCast i=new ImplicitCast();
System.out.println(i.Omb(2.2));
}
public float Omb(float f)
{
System.out.println("from byte");
return (f+1);
}
}

In java integer literals are type int and floating point literals are type double. Apparently, all the compiler knows is that you're passing an int to a method that requires a byte and that this "could" be a problem. The same thing happens with a double being passed to a method that accepts floats above.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
This is from the Java Language Specification 5.3.

Method invocation conversions specifically do not include the implicit narrowing of integer constants which is part of assignment conversion (�5.2). The designers of the Java programming language felt that including these implicit narrowing conversions would add additional complexity to the overloaded method matching resolution process (�15.12.2).
 
GeeCON Prague 2014
 
subject: impicit narrowing in method arguments