Showing posts with label long. Show all posts
Showing posts with label long. Show all posts

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.

Saturday, 27 April 2013

How Big (or Small) Can a Java Long Integer Be?

Java long variables let you store even larger numbers. The program below shows how you can display the maximum and minimum values allowed:

UBUNTU > cat prog9.java
public class prog9
{
public static void main (String args[])
  {
  System.out.println
  ("The largest long you can have is " + Long.MAX_VALUE );
  System.out.println
  ("The smallest long you can have is " + Long.MIN_VALUE );
  }
}
UBUNTU > javac prog9.java
UBUNTU > java prog9
The largest long you can have is 9223372036854775807
The smallest long you can have is -9223372036854775808
UBUNTU > 

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.