First Program, Variables, and Types

First lesson of the Java Fundamentals course, free to read: about 20 minutes, 4 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Write, compile, and run a Java program
  • Declare variables with primitive types and String
  • Read keyboard input with Scanner and display a formatted result

Program structurePrimitive types and StringConsole input/output

Java is a compiled, statically typed language used for enterprise applications, web back ends (Spring Boot), Android, and data tools. The source code is compiled into bytecode, run by the Java Virtual Machine (JVM) on any system.

The minimal program

public class Main {                                  // the file is called Main.java
    public static void main(String[] args) {         // program entry point
        System.out.println("Hello, Java!");          // prints, then moves to a new line
    }
}
java Main.java          # compiles in memory and runs (single file)
# or in two steps:
javac Main.java && java Main

Each statement ends with ;, blocks are delimited by { }, and Java is case-sensitive (main is not Main).

New in Java 25 (the current LTS version): compact source files. For a small program, the class can disappear and main no longer needs to be public static or to receive args:

void main() {                                   // file Hello.java, no class
    String prenom = IO.readln("Your first name: "); // IO (java.lang) reads and prints
    IO.println("Hello " + prenom);
}

It runs with java Hello.java, and common classes (List, ArrayList, Scanner…) are available in it without an import. Here we use the classic public class Main form, which you will find in all existing projects.

Variables and types

int age = 34;                 // 32-bit integer
long population = 68_000_000L; // 64-bit integer (L suffix), _ for readability
double prix = 19.99;          // floating-point number (decimal point!)
boolean actif = true;         // true or false
char initiale = 'A';          // one character, in single quotes
String nom = "Ada";           // text, in double quotes (String is a class)
var quantite = 3;             // inferred type: int
final double TVA = 0.20;      // constant: can no longer change

The type is checked at compile time: int x = "bonjour"; does not compile. This is valuable safety on large projects.

Operations and conversions

int a = 7, b = 2;
System.out.println(a / b);          // 3   (integer division!)
System.out.println(a % b);          // 1   (remainder)
System.out.println((double) a / b); // 3.5 (explicit conversion)
int arrondi = (int) 3.99;           // 3   (truncation)
int n = Integer.parseInt("42");     // text -> integer
String s = "Total: " + 42;          // + concatenates with a string

Careful: 5 / 2 is 2. As soon as one of the two operands is a double, the result is too.

Reading input with Scanner

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String prenom = sc.nextLine();      // a complete line
        int annee = sc.nextInt();           // an integer
        System.out.println("Hello " + prenom + ", you will be " + (2026 - annee) + " years old this year.");
    }
}

next() reads a word, nextInt() an integer, nextLine() the rest of the line. For decimal numbers, Double.parseDouble(sc.next()) avoids surprises related to the system language (comma or point).

Displaying a formatted result

double moyenne = 14.0 / 3;
System.out.printf("Average: %.2f%n", moyenne);   // Average: 4.67
String ligne = String.format(java.util.Locale.ROOT, "%.2f", moyenne); // decimal point guaranteed

%d displays an integer, %.2f a decimal with 2 digits, %s a string, and %n a line break. Without specifying a Locale, the decimal separator depends on the system settings: in French, 4,67.

You now know how to write a program that reads, computes, and displays: the foundation of all the following exercises.

Exercises

Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.

  1. CodeDifficulty 1Server sandbox2 hints

    Greet the user

    Write a program that reads a first name from standard input (one line) and prints Bonjour, <prénom> !.

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            // À compléter
        }
    }
  2. CodeDifficulty 2Server sandbox2 hints

    Division calculator

    Read two integers a and b (b non-zero) and print on four lines:

    Somme : <a+b>
    Quotient entier : <a/b>
    Reste : <a%b>
    Division : <a/b avec 2 décimales>

    Use String.format(Locale.ROOT, "%.2f", ...) for the last line.

    import java.util.Locale;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            // À compléter
        }
    }
  3. CodeDifficulty 2Server sandbox2 hints

    Convert seconds

    Read a whole number of seconds and print it in the format HH:MM:SS (hours on at least 2 digits). Example: 3725 → 01:02:05.

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int total = sc.nextInt();
            // heures, minutes, secondes avec / et %
        }
    }
  4. Multiple choiceDifficulty 11 hint

    Integer division

    What is the value of double r = 7 / 2;?

    • 3.5
    • 3.0
    • Compilation error

End-of-lesson quiz

  1. Which method is the entry point of a classic Java program?

    • public static void main(String[] args)
    • public void start()
    • static int run()
  2. Which type should you choose to store 19.99?

    • int
    • double
    • char
  3. What does var x = 10; do?

    • Creates a variable with no type
    • Declares a variable whose int type is inferred by the compiler
    • Creates a constant

The rest of the course

  1. Conditions, Logical Operators, and switch15 min
  2. for, while, and do-while Loops20 min
  3. Writing Methods20 min
  4. Arrays, Strings, and ArrayList20 min

Java Fundamentals · Beginner · 3 h 5 min