Home Java Programming Language
Post
Cancel
Java Programming Language | SEG

Java Programming Language

This is part 2 of our Programming Languages series. This post focuses on Java Programming Language.

Getting Started with Java

Today, we’re zooming in on one of the most enduring and versatile programming languages out there, Java. Whether you’re looking to build Android apps, web services, or even just understand how software communicates with hardware, Java is an excellent place to begin.

What Makes Java Worth Learning?

Java’s longevity isn’t just luck—it’s built on strong fundamentals:

  • Cross-platform capabilities: Write once, run anywhere. Java’s high portability means your code can run on Windows, Linux, macOS, or even a Raspberry Pi without modifications.
  • Massive community and support: With tens of millions of developers worldwide, finding answers, libraries, or tutorials is never an issue.
  • Demand in the job market: Java consistently ranks as one of the most in-demand programming languages.
  • Robust performance and security: It’s fast, secure, and battle-tested.
  • Object-oriented design: This makes code modular, reusable, and easier to maintain.

Java is also a multi-paradigm language. While its core is object-oriented, it supports:

  • Functional programming
  • Concurrent and distributed computing
  • Generic and component-based design
  • Event-driven and reflective programming

This versatility lets developers tailor their approach to the problem at hand.

Let’s Talk IDEs: Your Coding Cockpit

An IDE (Integrated Development Environment) is like a command center for developers. With it, you get everything you need to write, compile, debug, and test your code in one place.

Popular choices include:

  • IntelliJ IDEA (our pick for today)
  • Eclipse
  • Visual Studio
  • Xcode

Why use an IDE? Speed. Structure. Sanity. A good IDE catches bugs as you type (at least some of them), offers code suggestions, and keeps everything organized.

Building Your First Java Project in IntelliJ IDEA

  1. Create a New Project: Launch IntelliJ and select New Project.
  2. Choose Java: Pick Java as your language and set up the Java Development Kit (JDK); we’re using Java 11.
  3. Project Name and Structure: Name it something like SimpleProject. This creates your working directory and essential folders.
  4. Create Your First Class: Inside the src folder, add a new Java class, e.g., Main.

Here’s the simplest program in Java:

1
2
3
4
5
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Hit Run. Voilà. Your first Java output.

Under the Hood: Compilation and Bytecode

Java compiles your code into bytecode, which runs on the Java Virtual Machine (JVM). This separation between human-readable code and machine-executable instructions gives Java its portability.

Java Syntax 101

Comments

Comments help describe code logic to developers. Single-line and multi-line comments are ignored by the compiler. Javadoc comments can generate HTML documentation using tools like javadoc.

1
2
3
4
5
6
7
8
9
10
11
// This is a single-line comment

/*
 This is a multi-line comment.
 It spans several lines.
*/

/**
 * This is a Javadoc comment.
 * It is used to generate external documentation.
 */

Variables & Types

In Java, variables are containers for storing data values. Every variable must be declared with a specific data type, which determines what kind of value it can hold. Java is a statically typed language, meaning types are checked at compile-time, not at runtime. This helps catch many bugs early.

Java offers two main categories of data types:

  • Primitive types – simple, built-in types for common data (e.g., numbers, booleans, characters).
  • Non-primitive types – more complex types built using classes (e.g., String, arrays, and custom objects).

By understanding the distinction between primitive and non-primitive types, and how to use each, you’ll be able to manage data more effectively in your Java applications.

Primitive Types:

Primitive types are the most basic kinds of data you can work with. They are not objects and don’t come with built-in methods. Here are the four most commonly used ones:

TypeDescriptionExample
intStores whole numbersint x = 5;
doubleStores decimal (floating point) numbersdouble pi = 3.14;
charStores a single characterchar a = 'A';
booleanStores true/false valuesboolean isJavaFun = true;

These types are highly memory-efficient and are often used when performance and memory usage matter.

Non-Primitive Types:

Non-primitive (or reference) types are built from classes. They can store multiple values or more complex structures and come with methods that can be called directly.

1. String
1
String greeting = "Hello";

A String is used to represent a sequence of characters. It comes with many handy methods like .length(), .toUpperCase(), and .substring().

2. Arrays
1
int[] numbers = {10, 20, 30, 40};

An array holds multiple values of the same data type. The size is fixed once created. You access elements using an index (starting at 0).

3. Objects and Custom Classes
1
Person p = new Person("Alice", 28);

You can define your own data structures using classes and create objects from them. These can encapsulate data and behavior, making your programs more organized and scalable.

Type Casting: Converting Between Types

In Java, type casting allows you to convert a variable from one data type to another. This is particularly useful when you’re working with mixed data types (like converting an int to a double, or vice versa), or when you need to optimize performance and memory usage.

There are two types of casting in Java:

1. Widening Casting (Automatic)

This happens automatically when you’re converting a smaller data type into a larger one. It’s safe because there’s no risk of losing information.

1
2
int num = 10;
double d = num; // Automatically converts int to double

Why it works: Java knows that a double can safely hold all possible int values, so it performs the conversion without needing extra instructions from the programmer.

2. Narrowing Casting (Manual)

This must be explicitly specified by the programmer, as you are converting from a larger data type to a smaller one. Since this can result in data loss, Java requires you to be deliberate about it.

1
2
double pi = 3.14;
int truncated = (int) pi; // Results in 3

Why it’s risky: When you convert 3.14 from a double to an int, the decimal portion is discarded. Java makes you use (int) to make it clear you understand and accept that loss.

When to Use Casting

  • Use widening when you want to maintain precision while promoting a value.
  • Use narrowing when precision isn’t critical or you’re dealing with system constraints (like embedded systems with limited memory).

By mastering type casting, you gain more control over how Java handles data—essential when optimizing performance, memory, or integrating different modules.

Operators: Arithmetic & Logic

In Java, operators are special symbols used to perform operations on variables and values. They are essential for performing basic calculations and for making decisions in your code.

This section focuses on arithmetic and logical operators, which are the most frequently used in everyday programming tasks.

Arithmetic Operators

These are used to perform mathematical calculations:

1
2
3
4
5
6
7
int a = 10, b = 3;

System.out.println(a + b); // 13
System.out.println(a - b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3
System.out.println(a % b); // 1
  • + adds two values.
  • - subtracts one value from another.
  • * multiplies two values.
  • / divides the first value by the second.
  • % (modulus) gives the remainder of a division.

Note on Integer Division: In Java, if both operands are integers, the division result is also an integer. So 10 / 3 gives 3, not 3.33. To get a decimal result, at least one operand must be a floating-point type (e.g., 10.0 / 3 or 10 / 3.0).

Logical and Comparison Operators

These operators compare values and return boolean results (true or false). They’re often used in control statements like if, while, and for.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
&&Logical AND (both true)a > 5 && b < 5
||Logical OR (at least one true)a > 5 || b < 5
!Logical NOT (inverts boolean)!(a > b)

Example:

1
2
3
4
System.out.println(a > b);      // true
System.out.println(a == 10);    // true
System.out.println(a > 5 && b < 5); // false
System.out.println(!(a == b));  // true

These operators are key to making decisions and controlling the flow of logic in your program.

Strings

In Java, a String is a widely used non-primitive data type that represents a sequence of characters. Unlike primitive types, String is a class, which means it comes packed with powerful methods for manipulating text.

You can create a string simply by enclosing characters in double quotes:

1
String text = "Java";

Once declared, you can use a wide range of methods to interact with and manipulate the string.

Common String Methods

1
2
3
4
5
6
String text = "Java";

System.out.println(text.length());         // 4
System.out.println(text.toUpperCase());    // JAVA
System.out.println(text.indexOf('a'));     // 1
System.out.println(text.concat(" Rocks")); // Java Rocks

Explanation:

  • .length() — Returns the number of characters in the string (4 in this case).
  • .toUpperCase() — Converts all characters to uppercase. It does not change the original string.
  • .indexOf('a') — Returns the position (index) of the first occurrence of 'a'. Indexing starts at 0.
  • .concat(" Rocks") — Appends the specified string to the original string and returns a new string.

Important Note: Strings in Java are immutable, meaning their content can’t be changed after they are created. Every method that seems to modify a string (like toUpperCase() or concat()) actually returns a new string with the changes applied.

Strings are essential in almost every Java application, from displaying messages to processing user input. Their immutability makes them thread-safe by default, which is particularly valuable in concurrent programming.

Math

Java includes a built-in Math class that provides a suite of utility methods for performing mathematical operations. This class is part of the java.lang package, so you don’t need to import anything to use it.

The Math class is static, meaning you can call its methods directly using the class name, without creating an object.

Common Math Methods

1
2
3
System.out.println(Math.max(10, 20));  // 20
System.out.println(Math.sqrt(16));     // 4.0
System.out.println(Math.random());     // Random between 0.0 and 1.0

Explanation:

  • Math.max(10, 20) — Returns the larger of the two values. Great for comparing values programmatically.
  • Math.sqrt(16) — Returns the square root of a number. The result is a double, even if the input is an integer.
  • Math.random() — Returns a pseudo-random double value between 0.0 (inclusive) and 1.0 (exclusive). This is often used for generating random behavior, such as in games or simulations.

More Useful Math Methods

Here are a few other helpful methods you might encounter:

1
2
3
4
Math.min(a, b);     // Returns the smaller of two numbers
Math.abs(-7);       // Returns the absolute value (7)
Math.pow(2, 3);     // Returns 2 raised to the power of 3 = 8.0
Math.round(2.6);    // Rounds to the nearest integer (3)

These functions are especially useful in tasks involving calculations, simulations, data analysis, or any scenario where numerical precision and operations are important.

Pro Tip: Since most Math methods return double values, you may need to cast them when working with integer variables.

Booleans

A boolean in Java is a data type that can hold one of two values: true or false. This simple yet powerful type is at the heart of decision-making in your programs. It’s most commonly used in conditions for if, while, and other control flow statements.

Declaring and Using a Boolean

1
2
3
4
boolean isLoggedIn = true;
if (isLoggedIn) {
    System.out.println("Welcome back!");
}

Explanation:

  • The variable isLoggedIn holds a boolean value (true).
  • The if statement checks this value.
  • If the condition is true, the code inside the block is executed — in this case, it prints a welcome message.

Tip: Boolean variables often use names that start with is, has, or can — e.g., isActive, hasAccess, canEdit — to clearly communicate the kind of question they answer.

Common Boolean Expressions

Booleans are often the result of comparison or logical expressions:

1
2
int age = 20;
boolean isAdult = age >= 18; // true
1
boolean isEligible = age >= 18 && age <= 65; // try to guess:)

These expressions return true or false, which can be directly used in control structures to drive program behavior.

If … Else

In Java, the if, else if, and else statements are used to control the flow of your program based on conditions. These are known as conditional statements, and they allow your program to make decisions, executing different blocks of code depending on whether a condition is true or false.

Basic Example

1
2
3
4
5
6
7
8
9
int score = 85;

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("Try harder");
}

Explanation:

  • The program checks the first condition: score >= 90. Since 85 is not greater than or equal to 90, it skips this block.
  • It then checks the next condition: score >= 80. This is true, so it executes that block and prints "B".
  • The final else is a fallback — it only runs if none of the above conditions are met.

When to Use

Use if ... else when:

  • You need to perform different actions based on different conditions.
  • Each condition is mutually exclusive, meaning only one block should run.

More Realistic Example

1
2
3
4
5
6
7
8
9
int temperature = 30;

if (temperature > 35) {
    System.out.println("It's very hot!");
} else if (temperature >= 20) {
    System.out.println("Nice weather.");
} else {
    System.out.println("It's cold outside.");
}

This example mimics real-world decision-making and shows how else if can create multiple branches in your logic.

Tip: You can nest if statements inside each other or use logical operators (&&, ||) to handle more complex conditions.

Switch

The switch statement in Java is a control flow structure that simplifies the process of choosing between multiple specific values of a single variable. It serves as a cleaner alternative to long chains of if-else statements when you’re checking for equality against constant values.

Example

1
2
3
4
5
6
7
8
int day = 3;

switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    case 3: System.out.println("Wednesday"); break;
    default: System.out.println("Other day");
}

Explanation:

  • The variable day is evaluated.
  • Java checks each case in order.
  • If a match is found (case 3), it executes that block — here, printing "Wednesday".
  • The break statement prevents fall-through, ensuring only the matching case runs.
  • The default block is like the else in if-else. It runs if no case matches.

When to Use switch

  • When comparing the same variable against discrete, known values like numbers, characters, or strings.
  • When you want simpler syntax than nested if-else blocks.

Real-World Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String role = "admin";

switch (role) {
    case "admin":
        System.out.println("Access to all features");
        break;
    case "editor":
        System.out.println("Can edit content");
        break;
    case "viewer":
        System.out.println("Read-only access");
        break;
    default:
        System.out.println("Unknown role");
}

Tip: In Java 7 and newer, switch also works with String, not just integers and characters.

While Loop

The while loop in Java is a control flow statement used to repeatedly execute a block of code as long as a specified condition remains true. It’s ideal for scenarios where you don’t know in advance how many times the loop should run.

Basic Example

1
2
3
4
5
int i = 0;
while (i < 3) {
    System.out.println("Count: " + i);
    i++;
}

Explanation:

  • The loop starts by evaluating the condition: i < 3.
  • If the condition is true, it enters the loop and executes the body — printing the count and incrementing i.
  • This repeats until the condition becomes false.
  • Once i reaches 3, the loop stops and the program moves on.

Key point: If the condition is false from the beginning, the code inside the loop never runs.

Use Cases

while loops are useful when:

  • The number of iterations is not known in advance.
  • You’re waiting for a user action, input, or a changing condition (e.g., sensor data or file status).

Real-World Example

1
2
3
4
5
6
7
Scanner scanner = new Scanner(System.in);
String input = "";

while (!input.equals("exit")) {
    System.out.print("Type 'exit' to quit: ");
    input = scanner.nextLine();
}

Explanation: This loop continues prompting the user until they type "exit". It’s a common pattern for reading input or running background tasks.

Be careful with infinite loops. If the condition never becomes false, the loop will run forever unless interrupted.

Do/While Loop

The do/while loop in Java is a variation of the while loop. The key difference is when the loop condition is checked. In a do/while loop, the block of code is guaranteed to run at least once, because the condition is evaluated after the loop body.

Basic Example

1
2
3
4
5
int j = 0;
do {
    System.out.println("Do count: " + j);
    j++;
} while (j < 3);

Explanation:

  • The code inside the do block runs first, before any condition is checked.
  • Then the condition j < 3 is evaluated.
  • If it’s true, the loop runs again; if it’s false, the loop stops.
  • In this case, j starts at 0 and the loop prints Do count: 0, Do count: 1, and Do count: 2 before stopping.

Why it matters: The do/while loop is especially useful when you need to ensure that the code executes at least once, regardless of the condition.

Use Cases

Use do/while when:

  • You must perform an action before validation (e.g., read input before checking its value).
  • You’re building a menu system, input loop, or prompt that should show up once no matter what.

Real-World Example

1
2
3
4
5
6
7
Scanner scanner = new Scanner(System.in);
String input;

do {
    System.out.print("Enter a number (or 'q' to quit): ");
    input = scanner.nextLine();
} while (!input.equals("q"));

Explanation: This loop will prompt the user for input at least once, and it will keep doing so until they enter "q".

Watch out for infinite loops. Make sure the condition will eventually become false, or provide a break statement inside the loop when appropriate.

For Loop

The for loop is one of the most commonly used control structures in Java. It’s ideal when you know exactly how many times you want to execute a block of code. Unlike while and do/while loops, the for loop conveniently groups the loop control logic, initialization, condition, and update, into a single line.

Basic Example

1
2
3
for (int i = 0; i < 3; i++) {
    System.out.println("For count: " + i);
}

Explanation:

  • int i = 0 → Initializes the loop variable i.
  • i < 3 → This is the condition; the loop continues as long as it’s true.
  • i++ → This updates the loop variable after each iteration (increments i by 1).
  • The loop prints For count: 0, 1, and 2.

Once i becomes 3, the condition i < 3 is no longer true, so the loop exits.

Structure Breakdown

1
2
3
for (initialization; condition; update) {
    // Loop body
}

This format makes it compact and easy to read, especially when working with index-based operations, like looping through arrays.

Use Cases

Use a for loop when:

  • You need to iterate a specific number of times.
  • You’re working with indexable data (arrays, strings, lists).
  • You want a clean, predictable iteration structure.

Real-World Example

1
2
3
for (int year = 2020; year <= 2025; year++) {
    System.out.println("Year: " + year);
}

This prints a list of years from 2020 through 2025, demonstrating how for loops handle ranges efficiently.

Pro Tip: Always ensure your loop’s end condition is reachable, or you could end up with an infinite loop.

For-Each Loop

The for-each loop (also known as the “enhanced for loop”) is a cleaner, more readable alternative to a traditional for loop when you want to iterate through all elements in an array or collection, and you don’t need to know the index.

Basic Example

1
2
3
4
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

Explanation:

  • String fruit — This declares a variable fruit to hold each item from the array.
  • : fruits — This means we are looping through every element in the fruits array.
  • On each iteration, fruit holds the value of the current item, and System.out.println(fruit) prints it.

This loop will print:

1
2
3
Apple
Banana
Cherry

Syntax Structure

1
2
3
for (type variable : collection) {
    // Code to execute
}
  • type matches the element type of the collection.
  • variable is a temporary placeholder for each item.
  • collection is the array or iterable structure.

When to Use

Use a for-each loop when:

  • You want to process every item in a list or array.
  • You don’t need to modify the items.
  • You don’t need to track the item’s position (index).

Real-World Example

1
2
3
4
5
6
7
int[] scores = {95, 87, 74, 66};

for (int score : scores) {
    if (score >= 90) {
        System.out.println("Excellent: " + score);
    }
}

This loops through an array of scores and prints only those that are 90 or above.

Limitation: You can’t modify the array elements directly using a for-each loop, for that, use a regular for loop with index access.

Break & Continue

In Java, the break and continue statements are powerful tools for controlling the behavior of loops. They allow you to modify the normal flow of execution inside for, while, or do/while loops based on certain conditions.

Example

1
2
3
4
5
for (int i = 0; i < 5; i++) {
    if (i == 2) continue; // Skip this iteration
    if (i == 4) break;    // Exit the loop completely
    System.out.println(i);
}

Explanation:

  • When i == 2, the continue statement is triggered — this causes the loop to skip printing the number 2 and move straight to the next iteration.
  • When i == 4, the break statement is triggered — this terminates the loop immediately, so the loop stops even though the condition i < 5 is still true.
  • As a result, the printed output will be:

    1
    2
    3
    
    0
    1
    3
    

How They Work

  • continue — Skips the rest of the loop body for the current iteration and jumps to the next iteration.
  • break — Immediately exits the loop, regardless of whether the loop condition is still true.

When to Use

  • Use continue when:
    • You want to ignore specific cases without exiting the loop.
    • You’re filtering or validating data and want to skip some items.
  • Use break when:
    • A certain condition makes further looping unnecessary or invalid.
    • You’ve found what you’re looking for and want to stop early.

Real-World Analogy

Imagine a line of people waiting to enter a room:

  • If someone forgot their ID (continue), they’re skipped but the line continues.
  • If the room hits full capacity (break), no one else is let in — the process stops.

Tip: Use these statements sparingly. Overuse can make your code harder to read or maintain. Always document the intent clearly when using them.

Arrays

An array in Java is a data structure that allows you to store multiple values of the same data type in a single variable. Instead of declaring individual variables (like int a = 1; int b = 2; int c = 3;), you can use an array to manage them as a group.

Basic Example

1
2
3
4
5
6
7
8
int[] numbers = {1, 2, 3};
System.out.println(numbers[1]); // 2

numbers[1] = 10;

for (int n : numbers) {
    System.out.println(n);
}

Explanation:

  • int[] numbers = {1, 2, 3}; creates an array of three integers.
  • numbers[1] accesses the second element (remember: array indexing starts at 0), which originally holds the value 2.
  • numbers[1] = 10; updates the second element to hold 10 instead.
  • The for-each loop iterates over the array and prints each value: 1, 10, and 3.

Array Characteristics

  • Fixed size: Once created, the size of an array cannot be changed.
  • Zero-based indexing: The first element is at index 0, the second at index 1, and so on.
  • Homogeneous: All elements in an array must be of the same data type.

Accessing and Modifying Arrays

1
2
3
4
int[] scores = new int[4]; // creates an array with 4 elements
scores[0] = 95;
scores[1] = 88;
System.out.println(scores[0]); // prints 95

Here, you create an array with a set size and assign values later. This is useful when you know the size but not the values in advance.

Looping Through Arrays

  • Standard for loop (for when you need index access):
1
2
3
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Index " + i + ": " + numbers[i]);
}
  • Enhanced for-each loop (for simple iteration):
1
2
3
for (int value : numbers) {
    System.out.println(value);
}

Note: You cannot change array elements using a for-each loop — use a standard loop if modification is needed.

When to Use Arrays

Arrays are perfect for:

  • Storing a fixed collection of values.
  • Working with lists of numbers, strings, or objects.
  • Performing repetitive operations on similar data types (like calculating totals or averages).

The IDE Advantage

We can’t stress this enough: using an IDE like IntelliJ makes Java development drastically more efficient. Syntax highlighting, auto-completion, quick access to documentation, and error detection—these are more than conveniences, they’re essential tools.

Conclusion

Java may have been around since 1995, but it continues to be a foundational skill for developers around the world. Its rich ecosystem, platform independence, and structured approach make it ideal for beginners and professionals alike.

Starting with a good understanding of Java’s syntax, data types, and development tools like IntelliJ IDEA can pave the way for building powerful software solutions.

Whether you’re exploring Java as your first language or as a stepping stone into software engineering, the skills you gain here are highly transferable. Dive in, experiment, and most importantly — keep building!

This post is licensed under CC BY 4.0 by the author.