File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

impicit narrowing in method arguments

 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic