// the first java program: just print something
// the class is named Test, so the file name must be Test.java
// Note: java is case-sensitive, so test is not the same as Test
public class Test {
// every java application must have a main method
// declared exactly as below
public static void main( String [] args) {
// the program code is inside the main method
// printing the message to java console
System.out.println("Here we go!");
}
}
Program 2:
// demonstrating variables in java
public class Variables {
public static void main(String [] args) {
// declaring an integer variable x
int x;
// initializing x
x = 0;
// declaring and initializing y:
int y = 5;
// printing out the values:
System.out.println("x = " + x + " y = " + y);
// changing x:
x = 3;
System.out.println("x = " + x);
// changing y using x:
y = x * 2;
System.out.println("y = " + y);
// changing x using x and y
x = x - y/3;
System.out.println("x = " + x + " y = " + y);
// what would be the result of this?
x = y/4;
System.out.println("x = " + x);
// and this?
x = -x - 3;
y = x/3;
System.out.println("x = " + x + " y = " + y);
}
}
public class Variables2 {
public static void main (String[] args) {
// variables of type double
// you can declare variables of the same type on one line
double x = 5.2, y = 3.5;
//
double z = x - y;
System.out.println("z = " + z);
x = x/2;
System.out.println("x = " + x);
// what happens here?
x = 5/2;
System.out.println("x = " + x);
//but if at least one of the arguments is a double,
//the result is different:
x = 5.0/2;
System.out.println("x = " + x);
// guess the result of this one:
int i = 2;
x = y/i + i/3;
// System.out.println("x = " + x);
// typecasting:
z = (double)i/3;
System.out.println("z = " + z);
}
}
Test.java
) in a folder
on C drive.
cd C:\myprograms
(replace myprograms by the folder
where you copied the files).
javac Test.java
in the
Command Prompt window.
java Test
.