Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

casting  RSS feed

 
prakash s
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by default every integer literal is an int
so how does this works witjout typecasting
byte b=6;
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it looks at a value of 6 and sees that it's in a range of byte so no casting is necessary. But if you do this
byte b = 6;
b = b + 1; // Error because binary operation causes an error you try to add 1 which is an int and the result is not in the range of byte so you must cast
operations like this b++; will not caouse an error because implicit cast is being performed.
 
puneet pruthi
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!!
constants which r in range wont throw any error.like byte b=10;though 10 is in range ,still the compiler knows that it is a constant whose value is not going to change and it is within limits so it is okie
another thing which will work is
final int j=30;
byte b=j;
this will also work fine.
 
Lafayette Hubert
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So why doesn't this work with floats/doubles, etc?
e.g., why can't I do:
float f = 3.14; //clearly within range & precision of f.
Originally posted by puneet pruthi:
Hi!!
constants which r in range wont throw any error.like byte b=10;though 10 is in range ,still the compiler knows that it is a constant whose value is not going to change and it is within limits so it is okie
another thing which will work is
final int j=30;
byte b=j;
this will also work fine.

 
Ishaan Mohan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rules apply on char,short and byte. If the integer literal is in range of the given primitive, compiler allow narrowing cast.
float f=3.14; here 3.14 is double and you cannot assign it without explicit cast. If expression is float f=30; compiles fine.
 
Try 100 things. 2 will work out, but you will never know in advance which 2. This tiny ad might be one:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!