Back to Java
2026-03-197 min read

JAVA

Learn JAVA step by step with clear examples and exercises.

Why This Matters

Java is a widely used programming language for developing applications across various platforms such as desktop, web, mobile, and embedded systems. Understanding Java can open up opportunities in numerous industries like finance, healthcare, e-commerce, and more. In this tutorial, we will delve into the core concepts of Java, provide worked examples, discuss common mistakes, offer practice questions, and answer frequently asked questions.

Prerequisites

Before diving into Java, it is essential to have a basic understanding of programming concepts such as variables, data types, control structures (if-else statements, loops), functions, and arrays. Familiarity with object-oriented programming principles will also be beneficial but not required.

Core Concept

Java is an object-oriented programming language that follows the "write once, run anywhere" philosophy. The core concept of Java revolves around classes, objects, methods, variables, data types, operators, control structures, and exception handling.

Classes and Objects

A class is a blueprint for creating objects (also known as instances). It defines the properties (variables) and behaviors (methods) that an object can have.

public class Car {
private String color;
private int speed;

public void setColor(String newColor) {
this.color = newColor;
}

public String getColor() {
return this.color;
}

public void accelerate() {
// code to increase speed
}
}

In the example above, Car is a class with two private properties (color and speed) and methods for setting and getting the color property, as well as an accelerate method.

An object is an instance of a class. To create an object, we use the keyword new followed by the class name:

Car myCar = new Car();
myCar.setColor("Red");

In this example, myCar is an object of the Car class with a red color.

Variables and Methods

Variables store data within a class. In Java, we can declare variables using different access modifiers (public, private, protected, or default).

public class Car {
public String color;
private int speed;
protected double price;
}

In this example, color has a public access level, speed is private, and price is protected.

Methods are functions that perform specific actions within a class. In Java, we can declare methods using the public, private, or protected access modifiers.

public class Car {
public String color;
private int speed;
protected double price;

public void accelerate() {
// code to increase speed
}

private void brake() {
// code to decrease speed
}
}

In this example, accelerate has a public access level, and brake is private.

Data Types and Operators

Java supports various data types such as integers (int), floating-point numbers (double), characters (char), booleans (boolean), and more. Here's an example:

int age = 25;
double pi = 3.14;
char initial = 'A';
boolean isStudent = true;

Java also provides operators for performing arithmetic, comparison, and logical operations. Here are some examples:

int a = 5 + 3; // 8
double b = 2.0 * 4.0; // 8.0
boolean c = (a > b); // false

Control Structures

Java provides control structures for making decisions and looping through code. Here are examples of conditional statements and loops:

if (age >= 18) {
System.out.println("You can vote.");
} else {
System.out.println("You cannot vote yet.");
}

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

Exception Handling

Java provides a way to handle exceptions that may occur during program execution using try, catch, and finally blocks. Properly handling exceptions can make your code more robust and avoid crashes.

Worked Example

Now that we've covered the basics of Java, let's create a simple application called "Hello World."

  1. Open your preferred IDE (Eclipse, IntelliJ IDEA, or Visual Studio Code) and create a new Java project.
  2. Create a new class called HelloWorld in the src folder. Replace the generated code with the following:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
  1. Save the file and run the program. You should see "Hello, World!" printed in the console.

Common Mistakes

  1. Forgetting to import necessary libraries: Always check the JavaDoc for the library you're using to ensure that all required imports are included.
  2. Using uppercase letters in variable names: In Java, variables should always be declared with lowercase letters (e.g., myVariable instead of MY_VARIABLE).
  3. Forgetting semicolons: Semicolons are used to separate statements in Java. Forgetting them can cause syntax errors.
  4. Not closing resource streams: Always close resource streams (such as files and network connections) when you're done using them to prevent leaks.
  5. Ignoring exception handling: Properly handle exceptions to make your code more robust and avoid crashes.
  6. Using improper access modifiers: Be aware of the different access modifiers (public, private, protected, default) and use them appropriately within classes and methods.
  7. Not understanding garbage collection: Understand how Java's automatic memory management works to avoid creating memory leaks.
  8. Overusing static members: Avoid overusing static members as they can lead to issues with code organization and testing.
  9. Not following coding conventions: Follow the Java coding conventions for readability and maintainability of your code.
  10. Not documenting your code: Properly document your code using comments and Javadoc to make it easier for others (and yourself) to understand.

Practice Questions

  1. Write a Java class for a Rectangle with properties length, width, area, perimeter, and diagonal. Include methods to calculate the area, perimeter, and diagonal of the rectangle.
  2. Create a Java program that accepts user input for two integers, calculates their sum, and prints the result.
  3. Implement a Java method that finds the largest number in an array.
  4. Write a Java program that simulates a simple bank account with methods to deposit, withdraw, check balance, and print account statements.
  5. Create a Java class for a Circle with properties radius, diameter, area, circumference, and pi (as a constant). Include methods to calculate the area, circumference, and diameter of the circle.
  6. Write a Java program that implements a simple text-based game like "Hangman" or "Guess the Number."
  7. Implement a Java class for a Stack with push, pop, peek, and size methods. Test your implementation using various examples.
  8. Create a Java program that sorts an array of integers using bubble sort, selection sort, or insertion sort algorithms.
  9. Write a Java program that implements a simple web server using the Jetty framework.
  10. Implement a Java class for a LinkedList with methods to add, remove, and search elements in the list. Test your implementation using various examples.

FAQ

What is the difference between public, private, protected, and default access modifiers in Java?

  • Public: Accessible from any class within the same package or outside of it.
  • Private: Only accessible within the same class.
  • Protected: Accessible within the same package or subclasses of other packages.
  • Default (no modifier): Accessible only within the same package.

What is the purpose of a constructor in Java?

A constructor is a special method that is called when an object is created. It initializes the properties of the object and can perform additional setup tasks.

How do I declare a variable as constant in Java?

In Java, you can make a variable constant by declaring it as final and assigning it a value at the time of declaration. For example: final double PI = 3.14;.

What is the difference between == and .equals() in Java?

  • == compares the memory addresses of two objects, while .equals() compares their values (or reference values if comparing objects).

How do I create a multi-threaded program in Java?

To create a multi-threaded program in Java, you can use the Thread class or implement the Runnable interface. Each thread performs a specific task concurrently with other threads.

What is the difference between checked and unchecked exceptions in Java?

  • Checked exceptions are exceptions that must be handled by the code (e.g., IOException, SQLException). Unchecked exceptions are exceptions that do not need to be handled by the code (e.g., NullPointerException, ArrayIndexOutOfBoundsException).

How does garbage collection work in Java?

Java's garbage collector automatically frees up memory by identifying and removing objects that are no longer being used by the program.

What is the difference between an interface and an abstract class in Java?

  • An interface defines a contract for a set of methods that must be implemented by classes that implement the interface, whereas an abstract class can contain both method implementations and abstract methods that must be overridden by subclasses.

How do I create a static method in Java?

To create a static method in Java, use the static keyword before the return type of the method. Static methods can be called without creating an instance of the class.

What is the difference between an array and ArrayList in Java?

  • An array is a fixed-size data structure that stores elements of the same data type, while an ArrayList is a dynamic data structure that can store elements of any data type and resizes itself as needed.
JAVA | Java | XQA Learn