Java Tutorial

Java is one of the most popular programming languages in the world. It is used to develop mobile apps, web apps, desktop apps, games, and much more.

Key Concepts

  • Java was developed by Sun Microsystems (now owned by Oracle) in 1995.
  • Java is an object-oriented, class-based, concurrent programming language.
  • Java's motto: "Write Once, Run Anywhere" (WORA).
  • More than 3 billion devices run Java worldwide.
Java Example
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}
Live Editor

Java Introduction

Java is a general-purpose programming language that is class-based and object-oriented. It is designed to have as few implementation dependencies as possible.

Why Use Java?

  • Platform Independent: Java code is compiled to bytecode that runs on the Java Virtual Machine (JVM), making it platform independent.
  • Object-Oriented: Everything in Java is an object. OOP makes the full program simpler by breaking it into objects.
  • Secure: Java has built-in security features like no explicit pointer usage and bytecode verification.
  • Robust: Java has strong memory management, exception handling, and type checking.
  • Multithreaded: Java supports multithreading at the language level.

Java applications are compiled to bytecode that can run on any JVM regardless of the underlying hardware or OS. This makes Java extremely portable. The JVM acts as an intermediary between the Java code and the machine, translating bytecode into machine-specific instructions at runtime.

Java is widely used in enterprise-level applications, Android mobile development, big data technologies (like Hadoop and Spark), and server-side web development using frameworks like Spring Boot.

Common Mistakes and Pitfalls

  • Confusing Java with JavaScript — they are completely different languages.
  • Not understanding that Java is compiled to bytecode, NOT directly to machine code.

Java Get Started

To start writing Java programs, you need to install the Java Development Kit (JDK) and set up your environment.

Key Steps

  • Download the JDK from oracle.com.
  • Set the JAVA_HOME environment variable.
  • Verify: Run java -version and javac -version in terminal.
  • Use an IDE like IntelliJ IDEA, Eclipse, or VS Code.

After installing the JDK, you write your code in a .java file. The Java compiler (javac) compiles it into a .class file (bytecode). You then run the bytecode using the java command.

Compile and Run


# Save code as Main.java
javac Main.java    # Compile
java Main          # Run
            

Best Practices

  • Always name the file with the same name as the public class inside it.
  • Use an IDE for autocompletion, debugging, and project management.

Java Syntax

Every Java application must contain a main method. The main method is the entry point of any Java program.

Key Concepts

  • Every line of code in Java must be inside a class.
  • The class name should always start with an uppercase letter and match the filename.
  • Java is case-sensitive.
  • Every statement ends with a semicolon ;.
Syntax Example
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}
Live Editor

Common Mistakes

  • Forgetting the semicolon at the end of a statement.
  • Not matching the filename to the public class name.
  • Using system instead of System (case sensitivity).

Java Output

You can use println() to output values or print text in Java.

Key Concepts

  • System.out.println() — prints and adds a new line.
  • System.out.print() — prints without adding a new line.
  • You can print numbers, text, and expressions.
Output Example
System.out.println("Hello World!");
System.out.println(3 + 3);
System.out.print("I am learning ");
System.out.print("Java!");

Java Comments

Comments can be used to explain Java code and to make it more readable. They can also be used to prevent execution when testing alternative code.

Key Concepts

  • Single-line comments start with //.
  • Multi-line comments start with /* and end with */.
  • Javadoc comments start with /** and are used for documentation.
Comment Example
// This is a single-line comment

/* This is a
multi-line comment */

/** This is a Javadoc comment
 * @param args command line arguments
 */

Java Variables

Variables are containers for storing data values. In Java, there are different types of variables.

Key Concepts

  • String — stores text like "Hello".
  • int — stores integers like 123.
  • float — stores floating point numbers like 19.99f.
  • char — stores single characters like 'a'.
  • boolean — stores values with two states: true or false.
  • Use final keyword to declare a constant.

In Java, you must declare the variable type before using it. Java is a statically typed language, meaning the type of a variable is known at compile time. This is different from Python where types are inferred at runtime.

Variable Example
String name = "John";
int myNum = 15;
float myFloat = 5.99f;
char myLetter = 'D';
boolean myBool = true;
final int CONSTANT = 100;
Live Editor

Common Mistakes

  • Using a variable before declaring it.
  • Trying to reassign a final constant variable.
  • Forgetting to add f suffix to float literals.

Java Data Types

Data types specify the different sizes and values that can be stored in a variable.

Primitive Data Types

  • byte — 1 byte, stores whole numbers from -128 to 127.
  • short — 2 bytes, stores whole numbers from -32,768 to 32,767.
  • int — 4 bytes, stores whole numbers up to ~2.1 billion.
  • long — 8 bytes, stores very large whole numbers.
  • float — 4 bytes, stores fractional numbers (6-7 decimal digits).
  • double — 8 bytes, stores fractional numbers (15 decimal digits).
  • boolean — 1 bit, stores true or false.
  • char — 2 bytes, stores a single character/ASCII value.

Note: Non-primitive data types include String, Arrays, and Classes. They refer to objects and can be null.

Java Type Casting

Type casting is when you assign a value of one primitive data type to another type.

Key Concepts

  • Widening Casting (automatic): byte → short → int → long → float → double
  • Narrowing Casting (manual): double → float → long → int → short → byte
Type Casting Example
// Widening Casting (automatic)
int myInt = 9;
double myDouble = myInt;  // 9.0

// Narrowing Casting (manual)
double myDouble2 = 9.78d;
int myInt2 = (int) myDouble2;  // 9
Live Editor

Java Operators

Operators are used to perform operations on variables and values.

Operator Types

  • Arithmetic: +, -, *, /, %, ++, --
  • Assignment: =, +=, -=, *=, /=
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: &&, ||, !

Java Strings

Strings are used for storing text. A String variable contains a collection of characters surrounded by double quotes.

String Methods

  • length() — returns the length of a string.
  • toUpperCase() / toLowerCase() — case conversion.
  • indexOf() — finds the position of a substring.
  • concat() — concatenates two strings.
String Example
String greeting = "Hello";
System.out.println(greeting.length());        // 5
System.out.println(greeting.toUpperCase());   // HELLO
System.out.println(greeting.indexOf("llo"));  // 2

Java If...Else

Java supports the usual logical conditions from mathematics. Use these conditions to perform different actions for different decisions.

Key Concepts

  • if — specifies a block of code to be executed if a condition is true.
  • else — specifies a block to execute if the condition is false.
  • else if — specifies a new condition to test if the first condition is false.
  • Ternary: variable = (condition) ? expressionTrue : expressionFalse;
If...Else Example
int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
Live Editor

Java Switch

Use the switch statement to select one of many code blocks to be executed.

Switch Example
int day = 4;
switch (day) {
  case 1: System.out.println("Monday"); break;
  case 2: System.out.println("Tuesday"); break;
  case 3: System.out.println("Wednesday"); break;
  case 4: System.out.println("Thursday"); break;
  default: System.out.println("Other day");
}

Warning: Don't forget the break keyword! Without it, the code will "fall through" and execute the next case as well.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true.

While Loop Example
int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}
Live Editor

Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop.

Loop Types

  • for — traditional counter-based loop.
  • for-each — iterates over elements of arrays and collections.
For Loop Example
for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

// For-each loop
String[] cars = {"Volvo", "BMW", "Ford"};
for (String car : cars) {
  System.out.println(car);
}

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Key Concepts

  • Arrays are declared with square brackets: String[] cars;
  • Array elements are accessed by their index (starting from 0).
  • Use .length to find the number of elements.
  • Multidimensional arrays are arrays of arrays.
Array Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);     // Volvo
System.out.println(cars.length); // 4
cars[0] = "Opel";                // Change element
Live Editor

Java Methods

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method.

Key Concepts

  • Methods are defined with an access modifier, return type, name, and parameters.
  • void means the method does not return a value.
  • Methods can have parameters and return values.
  • Method Overloading: Multiple methods can have the same name but different parameters.
Method Example
static void myMethod(String fname, int age) {
  System.out.println(fname + " is " + age);
}

public static void main(String[] args) {
  myMethod("Liam", 5);
  myMethod("Jenny", 8);
}
Live Editor

Java Classes & Objects

Java is an object-oriented programming language. Everything in Java is associated with classes and objects, along with its attributes and methods.

Key Concepts

  • A class is a blueprint for creating objects.
  • An object is an instance of a class.
  • Attributes are variables within a class.
  • Methods define behaviors of the class.
  • Use new keyword to create an object.
Class Example
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}

Java Inheritance

In Java, it is possible to inherit attributes and methods from one class to another using the extends keyword.

Key Concepts

  • Subclass (child): The class that inherits from another class.
  • Superclass (parent): The class being inherited from.
  • Use extends to inherit from a class.
  • Java does not support multiple inheritance (use interfaces instead).
Inheritance Example
class Vehicle {
  protected String brand = "Ford";
  public void honk() {
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";
  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.honk();
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

Java Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. It lets us perform a single action in different ways.

Key Concepts

  • Method Overriding: A subclass provides a specific implementation of a method already provided by its parent class.
  • Method Overloading: Multiple methods with the same name but different parameters.
Polymorphism Example
class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}
class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

Java Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user. It can be achieved with either abstract classes or interfaces.

Key Concepts

  • Abstract Class: Cannot be used to create objects. Must be inherited from another class.
  • Abstract Method: Can only be used in an abstract class, and has no body.
  • Interface: A completely "abstract class" that groups related methods with empty bodies.

Java Encapsulation

Encapsulation means making sure that "sensitive" data is hidden from users. To achieve this, declare class variables as private and provide get and set methods.

Encapsulation Example
public class Person {
  private String name;

  // Getter
  public String getName() { return name; }
  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}

Best Practices

  • Always use private for class attributes.
  • Provide public getter and setter methods to access and update the value.
  • Add validation logic inside setters to protect data integrity.

Java Exceptions

When executing Java code, different errors can occur. Java provides a powerful mechanism to handle runtime errors using try...catch.

Key Concepts

  • try — defines a block of code to be tested for errors.
  • catch — defines a block of code to handle the error.
  • finally — executes code after try/catch, regardless of the result.
  • throw — creates a custom error.
Try...Catch Example
try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
} finally {
  System.out.println("The 'try catch' is finished.");
}
Live Editor

Java File Handling

The File class from the java.io package allows us to work with files.

File Operations

  • createNewFile() — creates a new file.
  • write() — writes to a file (using FileWriter).
  • read() — reads a file (using Scanner).
  • delete() — deletes a file.
File Example
import java.io.File;
import java.io.IOException;

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
    }
  }
}

Java Quiz

Test your Java skills with our Quiz!

Java Exercises

We have gathered a variety of Java exercises (with answers) for each Java Chapter.

🎉 Congratulations!

You've completed the Java module.