AP Computer Science Java: Lesson 1.1a
Java Basics - A First Java Program

Lesson 1.1a - A First Java Program
Purpose: To see a Java program and learn about its basic parts

When writing your programs, keep the following steps in mind*:
1. Declare Variables : Declare all necessary variables for this program, including a keyboard input object.
2. Input Data : Prompt the program user to enter all necessary data and receive the data into appropriate variables that will be processed later in the program.
3. Process Data : Perform calculations and other actions that are needed to derive the intended results of the program.
4. Output Results : Display the final results of the program. Be careful to do so in an organized manner, as stated in the program description.

*These four steps are noted within the example program using comments.

Below is a simple Java program.
Note the use of green text as comments within the code. This text is ignored by the computer and is used by programmers to make notes for themselves and others who will read their code. You can use this program as a guide when you start writing your own programs.

//This program converts celsius temperatures to fahrenheit equivalent

import java.io.*; //a Java package that allows for input and output

public class TempConvert //Name of the file or class to be saved
  public static void main(String [] args) //main program heading
    // Step 1. Declare Variables
    Scanner keybd = new Scanner(System.in);
//an input variable object
    int celsius; //declare an integer variable named celsius
    double fahr; //declare a decimal variable named fahr
    // Step 2. Input Data    
.out.print("Please enter a Celsius temp: "); //output prompt
    celsius = keybd.nextInt(); //read an integer from the keyboard
    // Step 3. Process Data
    fahr = 1.8 * celsius + 32; //an assignment statement for fahr
    // Step 4. Output Results

    System.out.println("The Fahrenheit temp is " + fahr); //output
Note the use of semicolons to mark the end of statements. Further, take note of the use of brackets to open and close sections of the program.


© DanShuster.com