Simple programs to get started in Java

From Knowledge Kitchen
Jump to navigation Jump to search


Examples

Simple program

Save the following code into a file named HelloWorldAgain.java;

package edu.nyu.cs.fb1258;

import java.util.Scanner;

/**
 * Simple program that asks for user input and then prints out a  meaningless message.
 * @author Foo Barstein
 * @version 0.1
 */ 

public class HelloWorldAgain {

	public static void main(String[] args) {

		//print a welcome message and instructions
		System.out.println("Hello world!");
		System.out.println("Please enter your favorite  number:");

		//get user input
		Scanner scnr = new Scanner(System.in);
		String response = scnr.nextLine();
				
		//print output
		System.out.println("Thanks for entering that " +  response);
		
		//close the scanner to free up memory resources on the computer
		scnr.close(); 
		
	}

}

Simple program with GUI

This program proves to you (in case you were in disbelief) that Java's API comes with the built-in ability to create programs with Graphical User Interfaces (GUIs), rather than simply text-based input and output. The built-in part of the Java API used here is known as the Swing GUI toolkit. It is one of several GUI APIs bundled into Java SE.

Save the following code into a file named HelloWorldSwing.java;

package edu.nyu.cs.fb1258;

import javax.swing.JOptionPane;
 
/**
 * Using the Java API's Swing library to pop open a GUI dialog with a message in it.
 * @author Foo Barstein
 * @version 0.1
 */ 

public class HelloWorldSwing {

	public static void main(String[] args) {

		JOptionPane.showInputDialog(null, "Hello World",  JOptionPane.OK_CANCEL_OPTION);

	}

}

Simple program with a custom function

Save the following code into a file named BasicJavaSyntax.java:

package edu.nyu.cs.fb1258;

/**
 * Did you think you wouldn't see functions with return values  in this class?
 * @author Foo Barstein
 * @version 0.1
 */
public class BasicJavaSyntax {
	
	/**
	 * This method adds one to any integer
	 * @param y any integer
	 * @return returns y + 1
	 */
	public static int foo(int y) {
		int z = 1 + y;
		return z;
	}
	
	public static void main(String[] args) {
		
		//call the foo() function and store the number it  returns
		int num = foo(2);
		
		//output the number
		System.out.println(num);
		
	}
		
}

What links here