Showing posts with label Solaris. Show all posts
Showing posts with label Solaris. Show all posts

Monday, 29 April 2013

Compile Once - Run Anywhere

In the previous example, I compiled and ran prog11 on a Solaris machine. Java is designed to be platform independent or portable. To show that it could be run on a different platform, I copied the prog11.class file to a Windows 7 machine in binary mode. Then I ran it there as follows:
 
C:\Java>dir
Volume in drive C is System
Volume Serial Number is B068-444A
 
Directory of C:\Java
 
04/29/2013  05:37 PM    <DIR>          .
04/29/2013  05:37 PM    <DIR>          ..
04/29/2013  05:36 PM               717 prog11.class
               1 File(s)            717 bytes
               2 Dir(s)  204,152,512,512 bytes free
 
C:\Java>java prog11
a = 100
b = 100
 
C:\Java>

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.

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.