GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java3 / 25

Variables, Types, Text, and Input

Representing information before making decisions

2.1 Learning objectives

By the end of this chapter, you should be able to:

  • declare, initialize, and update variables;
  • choose types that fit the problem;
  • manipulate and compare text correctly;
  • read input with Scanner and convert text to numbers;
  • recognize conversions that can lose information.

2.2 Variables and types

A variable links a name, a type, and a value.

Figure 2.1. A variable links a name, a type, and a value.

A variable binds a name to a value of a specific type:

String userName = "Ana";
int age = 19;
double average = 8.5;
boolean activeStudent = true;

In Java, declaration, initialization, and assignment are distinct steps:

int totalMessages;      // declaration
totalMessages = 1;      // initialization
totalMessages = 2;      // reassignment

The eight primitive types are byte, short, int, long, float, double, char, and boolean. To get started, int, double, char, and boolean cover most exercises. String is not a primitive type: it is a class used to represent text.

Prefer names that express intent, such as attemptCount and validCommand.

2.3 Numeric precision and conversions

Use integer types for counts and decimal types for measurements and averages. Real monetary values require extra care; in financial systems, BigDecimal is normally used instead of double.

Dividing two integers produces an integer result:

int correctAnswers = 7;
int totalQuestions = 10;

double wrongRate = correctAnswers / totalQuestions;          // 0.0
double correctRate = (double) correctAnswers / totalQuestions; // 0.7

Converting from a larger-capacity type to a smaller one can discard information:

double average = 8.75;
int wholePart = (int) average; // result: 8

Do not add a cast just to make the code compile. First check whether losing precision is acceptable.

2.4 Working with text

Strings are immutable: methods such as strip and toLowerCase return a new string.

String input = "  HELP  ";
String command = input.strip().toLowerCase();

System.out.println(command); // help

To compare content, use equals or equalsIgnoreCase. The == operator compares references and must not be used to check whether two strings have the same text.

if (command.equals("help")) {
    System.out.println("Commands: help, tip, and exit.");
}

In modern Java, isBlank() checks whether a string is empty or contains only whitespace.

2.5 Reading input with Scanner

Comic: variables are not magic boxes.

Figure 2.2. Comic: variables are not magic boxes.

A predictable strategy is to read every input with nextLine() and parse numbers when needed. This avoids the leftover newline bug caused by mixing nextInt() with nextLine().

import java.util.Scanner;

public class Chapter02Input {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Your name: ");
            String name = scanner.nextLine().strip();

            System.out.print("Your age: ");
            int age = Integer.parseInt(scanner.nextLine());

            System.out.printf("Hello, %s! Recorded age: %d.%n", name, age);
        }
    }
}

If the age is not in numeric format, Integer.parseInt throws NumberFormatException. Handling that case will be covered in the error handling chapter.

2.6 Project evolution: version 2

The chatbot now asks for the user’s name and displays a personalized greeting. Store:

  • the user’s name as a String;
  • the total number of messages as an int;
  • the conversation status as a boolean.

The complete example is in examples/src/Chapter02Input.java.

2.7 Verifiable practice

Write a program that reads a name, a city, and the weekly number of study hours. Then display a complete sentence.

Test cases:

InputExpected result
Ana, Boston, 6the sentence contains all three values
name with leading/trailing spacesouter spaces do not appear
hours equal to 0the program accepts and displays the value

Challenge: calculate the total study load over four weeks, storing the result in a separate variable.

Scope of this chapter

Do not handle non-numeric text yet. First observe the exception; later you will implement controlled recovery.