• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using Final Keyword & Casting

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Compare following code

public class Cat{

public static void main(String args[]){

int x = 20;
byte y = 10;

y = x;

System.out.println(y);
}
}


Compilation Error

java:8: possible loss of precision
found : int
required: byte
y = x;
^
1 error

Above code is OK, because I have to do casting like this

y =(byte) x;


but look at this


public class Cat{

public static void main(String args[]){

final int x = 20;
byte y = 10;

y = x;

System.out.println(y);
}
}

This example prints 20 and no compilation error

I do not understand why it implicitly converts int to byte, when I use final keyword.

Thanks in advance.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a situation of a narrowing primitive conversion.

Basically the reason that it works is that because the int value on the right of the assignment statement is a compile-time constant, and its value is compatible with a byte, the compiler will accept the assignment.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic