Monday, 29 April 2013

How to Copy a long Java Variable Into an int

You might think that you could copy a long variable into an int variable like this:
 
Solaris > cat prog10.java
public class prog10
{
public static void main (String args[])
  {
  int a;
  long b = 100;
  a = b;
  System.out.println ("a = " + a);
  System.out.println ("b = " + b);
  }
}
Solaris >
 
… but you get a compilation error if you try:
 
Solaris > javac prog10.java
prog10.java:7: possible loss of precision
found   : long
required: int
  a = b;
      ^
1 error
Solaris >
 
You have to do it like this instead:
 
Solaris > cat prog11.java
public class prog11
{
public static void main (String args[])
  {
  int a;
  long b = 100;
  a = (int) b;
  System.out.println ("a = " + a);
  System.out.println ("b = " + b);
  }
}
Solaris > javac prog11.java
Solaris > java prog11
a = 100
b = 100
Solaris >

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.