Program 1:

// 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);
	}
}

Program 3:

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);
	}
}

To run (on Windows):
  1. Copy the code into a java file with the same name as the the class (for instance, the first program will go into the file Test.java) in a folder on C drive.
  2. Open Command Prompt window. Go to the folder where your programs are: cd C:\myprograms (replace myprograms by the folder where you copied the files).
  3. Compile the code: javac Test.java in the Command Prompt window.
  4. Run it by command java Test.

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.