Basic Java Program

Objective

  • Create a basic Java program

A simple Java program

/* Filename Your Name Course Assignment number Date Brief description of program. */ import java.util.Scanner; public class ProgramName { public static void main(String[] args) { // Program code goes here // Declare variables Scanner kbd = new Scanner(System.in); int number1 = 0; int number2 = 0; int sum = 0; // Get input System.out.print("Enter an integer: "); number1 = kbd.nextInt(); System.out.print("Enter another integer: "); number2 = kbd.nextInt(); // Perform calculations sum = number1 + number2 // Display results System.out.println("The sum of " + number1 + " and " + number2 + " is " + sum); } }

Notes on program example

  • The program name should start with an uppercase letter.
  • The file name should be the program name with ".java" appended.
  • Variable and method names should start with a lowercase letter.
  • The line after an opening { is indented on level (four spaces).
  • Spaces should be used for indentation rather than tabs.
  • Lines consisting of a closing } should be unindented one level.
  • /* and */ surround block comments.
  • // specifies that the rest of the line is a comment.
  • Comments are for programmers to read. They do not execute.
  • Statements end with a semicolon (;)
  • Continuation lines ere indented one level.
  • Unless specified above, lines should stay at the same level of indentation as the previous line.