This English version is an adapted summary of my Turkish study notes on getting started with Java and Eclipse. The full notes, with all original examples and sources, are available in the Turkish version.

A short history of Java

Java is one of the most popular programming languages in the world. Sun Microsystems started developing it in 1991 as part of a project to let household electronic devices, such as microwaves, refrigerators, TVs and remote controls, communicate with each other. Its designers, including James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan, originally called it Oak. When they discovered that another language already had that name, they renamed it Java, reportedly inspired by the coffee they were drinking. The smart-appliance market grew much more slowly than Sun expected, and the project might well have been cancelled. Then, in 1993, the World Wide Web took off. Sun saw Java’s potential for building dynamic web pages and redirected the project, giving the language a new life.

Today Java underpins a huge range of applications: embedded and mobile systems, games, web content and enterprise software. At the time these notes were written, Oracle’s own figures spoke of around 9 million Java developers, Java on 97% of enterprise desktops and billions of devices, from mobile phones and Blu-ray players to smart cards and TVs.

Why Java?

  • It runs on every platform and is independent of the underlying server architecture.
  • Memory is managed automatically by the garbage collector.
  • It has a built-in exception handling mechanism.
  • It is statically typed, which helps the compiler optimize code, catches errors at compile time and makes auto-completion possible in IDEs. An int is always 32 bits and signed, whatever the platform; other types also have standard sizes.
  • Unlike C, it doesn’t allow macros or external header files, which makes the programmer’s life easier.
  • With Javadoc, interfaces and implementation classes, definitions and documentation can live inside the code.
  • A class cannot extend more than one class at a time. C++ allows this, but multiple inheritance can cause tangled problems.
  • Operator overloading is not allowed, so you always know what a + b does.
  • Errors such as segmentation faults and buffer overflows, part of everyday life in C/C++, are prevented by design.
  • Thanks to dynamic linking, implementation classes can be swapped without changing or recompiling the rest of the code.
  • Coming from the C/C++ family, it is easy to learn without a culture shock.
  • It supports object-oriented and multithreaded programming.
  • It has an enormous ecosystem; a large share of open-source projects are built on Java, and the community has a strong culture of sharing.

Setting up Java on your computer

To start developing in Java you need two things:

  1. The JDK (Java Development Kit): it contains the javac compiler, the Java Virtual Machine and supporting tools needed to compile and run your code.
  2. An IDE (Integrated Development Environment): you could write code in Notepad, but an IDE makes life much easier. Eclipse and NetBeans are the most common free, open-source choices; these notes use Eclipse.

After installing the JDK on Windows, set the environment variables under System Properties → Advanced → Environment Variables: add JAVA_HOME pointing to the JDK folder, append the JDK’s bin folder to Path, and optionally set CLASSPATH.

Then download Eclipse. For beginners the standard edition is enough; choose the Enterprise edition if you plan to build web applications. On first launch, Eclipse asks where to keep your workspace.

Your first program in Eclipse

Go to File → New → Project, choose Java Project, give it a name and click Finish. In the Project Explorer, right-click the src folder and choose New → Class. Enter a package name and a class name (by convention, each word starts with a capital letter) and tick the option to generate a main method. Then write the classic first program and click the green Run button; the output appears in the Console.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Welcome to the Java class!");
    }
}

Program structure

  • Text after //, or between /* … */, is a comment for human readers and is ignored by the compiler.
  • Every block of code, including class definitions, starts with { and ends with }, much like a paragraph.
  • A semicolon ; marks the end of a statement, like a full stop in a sentence.
  • public static void main(String[] args) is the entry point. What other languages call a function or procedure is called a method in Java. void means the method returns nothing, and public means it can be called from outside.
  • System.out.println(...) prints a string to the console, the Java equivalent of printf in C or cout << in C++. Common escape sequences are \n (new line), \t (tab), \\ (backslash) and \" (quote).

You can also show output in a dialog box using Swing:

import javax.swing.JOptionPane;

class Welcome {
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, "Welcome to the Java class!");
    }
}

And read input from the keyboard:

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = in.nextLine();
        System.out.println("Welcome to the Java class, " + name + "!");
    }
}

Data types and arithmetic

Computers store numbers in bits, each representing 1 (true) or 0 (false). Because the same group of bits can represent a letter or a number, the type of every variable must be known. Java’s basic arithmetic operators are +, -, *, / and % (remainder of integer division). There are also shorthand operators: ++ and -- (add or subtract one) and +=, -=, *=, /=, %=. Whether ++ comes before or after a variable makes no difference on its own, but it matters when used inside a larger expression.

import java.util.Scanner;

public class Sum {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int a = in.nextInt();
        System.out.print("Enter another number: ");
        int b = in.nextInt();
        System.out.println("Sum: " + (a + b));
    }
}

Evaluating a function such as y = x² + 2x − 2 for a value entered by the user:

double x = Double.parseDouble(JOptionPane.showInputDialog("x = "));
double y = x * x + 2.0 * x - 2;
JOptionPane.showMessageDialog(null, "x = " + x + "  y = " + y);

Conditional branching with if / else

The if statement evaluates a condition and chooses which path the program should take. This conditional branching is the most fundamental control structure in any language.

int grade = Integer.parseInt(JOptionPane.showInputDialog("Enter the grade (0-100): "));
String letter;
if (grade >= 90)      letter = "A";
else if (grade >= 75) letter = "B";
else if (grade >= 60) letter = "C";
else if (grade >= 50) letter = "D";
else if (grade >= 40) letter = "E";
else                  letter = "F";
JOptionPane.showMessageDialog(null, "The student's grade is " + letter);

Loops: for, while and do-while

Loops repeat a block of code as long as a condition holds. In for and while loops the condition is checked before each iteration; in a do-while loop it is checked after, so the body always runs at least once.

A for loop has three parts: initialization (runs once), the condition (checked every time) and the update (runs after each iteration). The following prints the numbers 5 to 9:

for (int value = 5; value < 10; value++) {
    System.out.println(value);
}

Nested loops can build a multiplication table:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        System.out.println(i + " * " + j + " = " + i * j);
    }
    System.out.println();
}

A while loop that sums five numbers entered by the user:

int total = 0, i = 1;
Scanner in = new Scanner(System.in);
while (i < 6) {
    System.out.println("Enter number " + i + ": ");
    total += in.nextInt();
    i++;
}
System.out.println("Total: " + total);

A do-while loop that adds the even numbers up to and including 10:

int total = 0, i = 0;
do {
    if (i % 2 == 0) total += i;
    i++;
} while (i <= 10);
System.out.println("Sum of even numbers up to 10: " + total);

switch / case

When a program has many conditions to check, long if-else chains become hard to follow. A switch statement chooses one of many paths based on the value of a single expression. Put a break after each case so that only the matching case runs, and use default for values that match no case.

switch (choice) {
    case 1:
        System.out.println("Central Europe tour: Vienna, Budapest, Prague");
        break;
    case 2:
        System.out.println("America tour: New York, Boston, Los Angeles");
        break;
    case 3:
        System.out.println("Far East tour: Bangkok, Hong Kong, Tokyo, Beijing");
        break;
    default:
        System.out.println("Invalid choice! Please enter 1, 2 or 3.");
}