Tutorial 1: Types, Operators, and Console Input

Unit 2 ยท Expressions and input

Objectives

Java is statically typed: every variable has a declared type. Use int for whole numbers, double for measurements, boolean for truth values, and char for one character. A String is an object representing text.

import java.util.Scanner;

public class Average {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("First mark: ");
        double first = input.nextDouble();
        System.out.print("Second mark: ");
        double second = input.nextDouble();
        double average = (first + second) / 2.0;
        System.out.printf("Average: %.1f%n", average);
    }
}

Use 2.0, not 2, when you want floating-point division. A cast such as (double) total / count converts before division.

Practice

  1. Write a converter from Celsius to Fahrenheit.
  2. Read a rectangle's width and height and print area and perimeter.
  3. Test zero, negative, and decimal inputs. Decide what should be rejected.

Self-check

  1. What is 7 / 2 as an int?
  2. Why is String capitalized?
  3. When is a cast necessary?

Mastery task: Build a receipt calculator that reads item price, quantity, and tax rate, then prints subtotal, tax, and total to two decimal places.