Results 1 to 2 of 2

Thread: int to byte

  1. #1
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Rep Power

    Default int to byte

    I found something strange. Please review the code below:

    Java Code:
    final int i = 100;
    byte b = i;
    Java Code:
    Removing the final keywords, causes exception.
    Java Code:
    int i = 100;
    byte b = i;
    Java Code:
    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    	Type mismatch: cannot convert from int to byte
    What is the reason? What role final keywords plays here?


  2. #2
    afsina is offline Member
    Join Date
    Jan 2008
    Rep Power


    This is because once you marked a variable as final, it is now immutable, cannot be changed after the declaration. compiler is intelligent enough to make the decision by allowing it to be set to a byte variable if the value is in range.
    the other case, compiler cannot guarantee if there will not be a change on the int before it is assigned to the byte so it does not allow the setting it. Otherwise this code would create a runtime error:

    int i = 100;
    ... lots of code here and i may be altered and set to 10000...
    byte b=i; <-- error!!

Similar Threads

  1. Byte Array
    By sandor in forum New To Java
    Replies: 12
    Last Post: 01-15-2009, 03:31 AM
  2. Byte Values
    By javaplus in forum New To Java
    Replies: 1
    Last Post: 06-23-2008, 12:08 AM
  3. using Byte arrays
    By mew in forum New To Java
    Replies: 2
    Last Post: 01-30-2008, 03:54 AM
  4. BufferedImage to Byte
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-22-2008, 08:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts