Site Navigation

Site Search

Chapter 2: Java Fundamentals

Learning Objectives

After completion of this chapter, you should be able to

Write simple procedural Java programs

Here is a simple Java program that displays "Programming is great fun" on the computer screen.

Code Example 2-1-1

   // Displays the message "Programming is great fun"
   public class Simple  
      public static void  main(String[] args)
         System.out.println("Programming is great fun");

Identify the elements that make up a Java program

Know the edit, compile, execute, debug process

The steps involved in writing a Java program:

  1. Type (or Edit) the program (Java source code *.java)
  2. Compile the program (Java bytecode *.class)
  3. Execute the program (Java Virtual Machine)

2-1a (22K)

  1. Debug the program (return to step 1)

While it is possible to perform all these steps at the command prompt, most programmers prefer to use an integrated development environment (IDE) that provides a Graphical User Interface (GUI also known as WIMP) to the four steps involved in writing Java programs.

The computers in the Hebeler labs have jGRASP IDE installed and ready to use with CS 110 and CS 111 assignments. jGRASP is available online with tutorials to help first time users.

All but the simplest Java programs consist of multiple source code files (*.java) and class files (*.class). jGRASP's projects manage the multiple source code and class files that make up a Java program.

Use comments, indentation, and proper brace placement to improve the readability of your programs

Programming style refers to the coding standards, conventions, and guidelines for writing correct, high-quality, and maintainable Java code.

The CS 110 Java Programming Style Guide outlines the conventions we will follow in CS 110 and 111. It contains separate sections for identifier naming conventions, commenting, and formatting.

If you are brand new to programming, some of the content of the Java Programming Style Guide at his point may be confusing. One student learning objective of CS 110 is to have you leave knowing how to correctly apply the style guidelines that produce readable and maintainable Java programs.

Declare and use Java variables and constants

Variables are names for values in our programs that can be changed.

In Java, every variable must be declared once before it can be used.

Declaring a variable means informing the compiler of the variable's name and its type.

The two most common primitive types in Java are

In Java, the pattern to declare (designate) a name with a variable is

    <the type> <the name>;

For example:

Code Example 2-1-2

// Declare two variables
   int milesWalked;
   double outsideTemperature;

The Java Style convention for capitalizing variable names is to use lower camel casing. Do not use spaces or underscore characters in your variable names.

If you know the variable's initial value, you can also set it to that value at the same time as the variable declaration.

The pattern to assign a name to variable along with an initial value is

    <the type> <the name> = <the initial value>;

For example:

Code Example 2-1-3

// Declare two variables with initial values
   double combinedWeight = 250.7;
   int age = 48;

List the 8 built-in primitive data types

Java has 8 built-in primitive data types

  1. byte
  2. short
  3. int (stores a whole number)
  4. long
  5. float
  6. double (stores a number with a decimal point)
  7. boolean (stores one of two values: true or false)
  8. char (stores a single character)

Of these eight, we will primarily use four of them in CS 110: int, double, boolean, and char.

Declare and use named constants using the final keyword

Named Constants are names for variables whose values cannot be changed

Java uses the keyword final to indicate constants.

In Java, the pattern to assign a name to constant value that cannot be changed is

   final <the type> <the name> = <the constant value>;


Code Example 2-1-4

// Declare two constants
   final int MINIMUM_AGE = 21;
   final double PI = 3.14159;

The Java Style convention for capitalizing constant names is to use all capital letters. To improve readability, subsequent words in the name are combined with the underscore character ('_')

Use an assignment statement to change the value of a variable

An assignment statement is used to change the value of a variable

The assignment operator is the equal sign: =

The pattern to write an assignment statement is

   <variableName> = <expression>;


Code Example 2-2-1

   // Declare and initialize the variable
      double weight = 199.9;
   // Use an assignment statement to go on a diet
      weight = 176.3;
   // Use an assignment statement to gain 15%
      weight =  weight * 0.15;

Use the five binary arithmetic operators

The first three operators work as expected. Division and modulus need some explanation.

Integer Division versus Modulus Operators

Integer division occurs with the / and two integer values (operands).

Code Example 2-3-1

Coding Shortcut for Code Example 2-3-1
   // Declare a variable
      int number1;
   // Do integer division
      number1 = 9 / 4;

number1 is 2 after the integer division operation. (The remainder of 1 is ignored)

Integer Division ignores any fractional part of the result, no matter how large. For example, even if the result was 7.9999, integer division would report the result as 7. Computer scientists say integer division truncates rather than rounds.

Use the modulus operator

If you want the remainder that results from the division, use the modulus operator: %

Code Example 2-3-2

Programming tip for Code Example 2-3-2
   //  Declare a variable
      int number2;
   // Find the <strong>modulus</strong>
      number2 = 9 % 4;

number2 is 1 after the integer modulus operation. (The quotient of 2 is ignored)

The modulus operator % is often referred to as remainder in simple mathematics. As you may learn later in discrete math, modulus actually means something slightly different.

Why are we interested in modulus? Some things cannot be divided easily. We have a basket of 22 apples that we would like to divide evenly between 4 students. Each student gets 5.5 apples? No, half an apple will spoil too quickly. Each student gets 5 apples and the remaining two apples go to their teacher.

Floating point division

If you want a precise (fractional) result, you must use floating point division (the / operator).

Floating Point Division occurs when one or both of the values being divided (operands) are double values.

Code Example 2-3-3

   // Declare a variable
      double number3;
   // Do floating point division
      number3 = 9.0  / 4.0;

number3 is 2.25 after the floating point division operation.

Understand operator precedence

Without parenthesis ( ... ) to help group values in expressions, the Java compiler uses precedence rules to determine the order to perform operations.

Code Example 2-3-4

   // Declare a variable
   int answer;
   answer = 3 + 5 / 4 - 2;       // answer is 2

   answer = 3 + (5 / 4) - 2;     // answer is 2

   answer = (3 + 5) / (4 - 2);    // answer is 4

Operator Precedence Rule: Without parenthesis, perform multiplication, division, and modulus operations before addition and subtraction.

With multiple operators of equal precedence, Use left-associativity. That is, perform the operations from left-to-right order.

Programming Tip: Always use parenthesis, don't rely on the precedence rule.

Use the Math Class

The Math class contains a number of methods for performing mathematical calculations. These methods are called by writing, where name is the name of the method.

The methods in the Math class return a value when they have completed execution.

Code Example 2-3-5

   answer = Math.pow(2.0, 3.0);     //  2 raised to the 3rd power. answer is 8.0
   answer = Math.sqrt(4.0);         //  square root of 4.  answer is 2.0
   answer = Math.abs(-3.0);         //  absolute value of -3. answer is 3.0
   answer = Math.max(3.0, 5.5);     //  larger of 3.0 or 5.5. answer is 5.5
   answer = Math.min(12.5, -23.2);  //  smaller of 12.5 or -23.2. answer is -23.2

Use System.out to display output to the console (screen)

System.out uses works with both print() and println() methods to display output on the computer screen.

      System.out.println(" World");

Do you know why I placed an blank space character before the word World?

Use escape sequences to control your output

One way to display a blank line on the computer screen is with System.out.println( );

I could display three blank lines by coding:

   // Display three blank lines
      System.out.println( );
      System.out.println( );
      System.out.println( );

Another way to print a blank line is to use an escape sequence: \n

Each occurrence of \n causes the output to begin on a new line.

   // Display three blank lines
   // Display four lines of text
      System.out.print("A hop,\na skip,\n\nand a jump\n");

There are a lot of different escape sequences built into Java.

Another common escape sequence is \", which represents " (a double quote):

System.out.println("He yelled \"Stop!\" and we stopped.");

In order to print a backslash character as part of a string, the string will need to contain two backslash characters:


Printing Multiple Items

The concatenation operator (+) operator can be used to combine multiple items into a single String for printing purposes:

System.out.print("Miles walked is " + milesWalked + "\n\n");

At least one of the two operands for the + operator must be a String.

Use the Scanner class to read keyboard input

Getting input from the user involves two tasks:

The prompt task is easily accomplished with the System.out.print method:

System.out.print("Enter number of clicks: ");

Reading in from the keyboard is more involved. Java was designed to create GUI applications. Input and output to the console window was expected to be used primarily for debugging purposes. However, since so many beginning programmers are now learning to program with Java, the Scanner class was introduced with Java 5 to simplify reading in values from the keyboard.

To use the Scanner in your programs, the line java.util.Scanner; must be at the start of your program to tell the Java compiler where to find the definition of the Scanner class.

Scanner objects work with To create a Scanner object, use

Scanner keyboard = new Scanner (

We can now use the keyboard object with the Scanner class methods to read in user input.

Scanner class methods are listed in Table 2-18 in the text. So far this quarter we have used

We can also use the nextLine() method to read in a String

   import java.util.Scanner; // Needed for the Scanner class

    public class Example{
       public static void main(String[] args)
       // Declare the variable
         String name = "";
      // Create a Scanner object to read input      
         Scanner keyboard = new Scanner(;
      // Prompt the user
         System.out.print("Enter your name: ");
      // Read in the user's name
         name = keyboard.nextLine();
      //Display the user's name
         System.out.println("Hello " + name);

Use the String class

The Java Application Programmer Interface (API) provides a huge number of pre-written classes. Of these, the String class is one of the most used.

The String class is included in the package named java.lang. This java.lang package is automatically imported into every Java program. (No other package has this property.)

We are used to using Strings as literal constants inside our println methods. We can also use Strings as reference variables inside our program.

   // Declare a local String reference variable
      String myString = "";
   // Assign myString to a literal constant
      myString  = "Hello World";

Using the String class length method

The String class length() method returns the number of characters in the String variable.

   // Declare a primitive type variable
      int size;
   // Assign size to the length of myString
      size = myString.length();   // size is now 11

Use the String Class charAt method

The String class charAt() method returns the single character stored at a specified position in the String object

   //Declare a primitive type variable
      char letter;
   // Get the character at the first position in myString
      letter = myString.charAt(0);       //letter is now 'H'

   //Get the character at the fifth position in myString
      letter = myString.charAt(4);       //letter is now 'o'

Change strings to upper or lower case

String methods toLowerCase() and toUpperCase() will convert the letters in a string to lowercase or uppercase.

      String allLower = myString.toLowerCase();

      myString = myString.toUpperCase();

Any characters other than letters inside the string object are not changed by methods toLowerCase and toUpperCase.

Use combined assignment operators

Java has some combined assignment operators that allow the programmer to perform an arithmetic operation and assignment with a single operator.

Although not required, these operators are popular since they shorten simple equations.

   // Declare a variable
     int number = 5;
   // Add three to it
     number = number + 3;
   // Add 4 to it (using combined assignment operator)
     number += 4;

Understand the concept of scope

Scope refers to the part of a program that has access to a variables contents.

Variables declared inside a method (like the main method) are called local variables. A local variables' scope begins at the declaration of the variable and ends at the end of the method in which it was declared.

   public static void main(String[] args)
      System.out.println(value); // ERROR!
      int value = 100;

Write single-line, multi-line, and javadoc comments

Java provides three methods for commenting code.

  1. Single line comments //
  2. Multi-line block comments /* ... */
  3. Javadoc comments /** ... */
   Written by Ed Gellenbeck
   This program calculates company payroll
   Last modification: Jan 20, 2006

/** Description of Class Example <br />
  * This program demonstrates three types of <strong>comments</strong>
  * @author Ed Gellenbeck
  * @version 1.0 Build 9000 Jan 20, 2006.

    public class Example
   /** Program begins here */
       public static void main(String[] args)      
         double payRate;      // Holds the hourly pay rate
         double hours;        // Holds the hours worked
         int employeeNumber;  // Holds the employee number
         // The Remainder of This Program is Omitted.

Use file header comments

File header comments provide readers and graders with the information they need to find your project on the network, identify the program's author, and to collect statistics on the project's difficulty based on the hours required to complete the program.

// Assignment: Program 2
// Account: (Enter your cs110 account number here)
// Author: (Enter your full name here)
// Completion time: (Enter the total number of hours you spent on the assignment)
// Honor Code: I pledge that this program represents my own program code. I received help
//    from (enter the names of others that helped with the assignment, write no one if
//   you received no help) in designing and debugging my program.

use the JOptionPane class to display input and message dialog boxes

A dialog box is a small graphical window that displays a message to the user or requests input.

A variety of dialog boxes can be displayed using the JOptionPane class. Two methods available with dialog boxes are:

   import javax.swing.JOptionPane;  // Required for the JOptionPane class

    public class Example
       public static void main(String[] args)
         String firstName = "";
         String lastName = "";
         String fullName = "";
      // Get the user's first name.
         firstName = JOptionPane.showInputDialog("What is your first name?");
      // Get the user's last name.
         lastName = JOptionPane.showInputDialog("What is your last name?");
      // Display a greeting
         fullName = firstName + " " + lastName;
         JOptionPane.showMessageDialog(null, "Hello " + fullName);

Convert Strings to numbers

The JOptionPane's showInputDialog method always returns the user's input as a String

A String containing a number, such as "127.89", can be converted to a numeric data type using the Java methods Double.parseDouble() and Integer.parseInt().

   // Declare the variables
      double temperature;
      int day;
      String userInput;

   // Get the temperature in Fahrenheit from the user
      userInput = JOptionPane.showInputDialog("Enter the degrees in Fahrenheit: ");
      temperature = Double.parseDouble(userInput);

   // Get the day number from the user
      userInput =  JOptionPane.showInputDialog("Enter the day (1-7): ");
      day = Integer.parseInt(userInput);