import
java.applet.Applet;
import java.awt.*;
/* This applet tests various math expressions.
Run with appletviewer to see print out on
screen or with a browser Java console. OR
run as an application.
*/
public class MathTest1 extends
Applet {
//-------------------------------------------------------
public void init() {
// FP literals
are double type by default.
// Append F or f to make float, or cast
to float
float x=5.1f;
float y=(float)2.0;
System.out.println("First
look at mixed FP & integers");
int i=1;
int j= (int)(i*x);
System.out.println
(" Mixed int
and float: j=(int)(i*x) = " + j);
double dy=2.0;
double dz=dy *
y;
System.out.println
(" Mixed float and
double: dz=dy * y = " + dz);
System.out.println
("\nNow look at byte
types in expressions");
byte ba
= 10;// int literal converted without
cast to byte
//
if in range allow for bytes -128 to 127
byte bb
= 1;
// Even though
byte operands, the calculation is done as
// int integers so result must be
cast back to byte.
byte bc = (byte)(ba - bb);
System.out.println(" byte: 10 - 1 = " + bc);
ba = -128; bb = 1;
bc = (byte)(ba
- bb);
System.out.println(" byte -127 - 1 =
" + bc );
j
= (int)(ba - bb);
System.out.println(" (int)(-127 - 1) = " + j );
System.out.println
("\nNow look at short
types in expressions");
short sa
= 10; // int literal converted without
cast to
// byte if in range short
sb = 1;
// Even though
short operands, the calculation in the JVM
// uses int integers so result must be cast back to short.
short sc
= (short)(sa - sb);
System.out.println(" short: 10 - 1 =
" + sc );
sa = 32767;
sb = 1;
sc = (short)(sa + sb);
System.out.println(" short 32767 + 1 = " + sc );
System.out.println
("\nNow look at
char types in expressions");
char
ca = '\u000F';// unicode must be put
into quotes
char
cb = '\u0001';
// Can do arithmetic
operations on char types
int ic
= ca - cb; // auto widen to integer without cast
System.out.println(" char: \u000F
- \u0001 = " + ic );
//
ca = 0x000F; Cannot use hex value directly for the char
//
value. The compiler will flag this as an error.
ic = ca - 1; //
Char acts as unsigned integer in
// arithmetic
operations
System.out.println(" char(0x000F)
- 1 = " + ic);
ca
= '\uFFFF';
ic = ca;
System.out.println(" (int)(\uFFFF)
= " + ic);
sa = (short)ca;
System.out.println(" (short)(\uFFFF)
= " + sa);
sa = -32768;
ca = (char)sa;
ic = ca;
System.out.println(" -32768 short
to char to int = " + ic);
sa = -1;
ca = (char)sa;
ic = ca;
System.out.println(" -1 short to char
to int = " + ic);
}
//----------------------------------------------------------
public void paint(Graphics
g) {
g.drawString("Math tests",10,20);
}
//----------------------------------------------------------
// Allow for option of running as an application
public static void main(
String [] args){
MathTest1 mathTest1 = new
MathTest1();
MathTest1.init();
}
}
|