DEV Community

Cover image for Java for Beginners
kiraaziz
kiraaziz

Posted on

Java for Beginners

Java is a versatile and widely-used programming language known for its portability and platform independence. In this Markdown document, we will explore various Java concepts with a plethora of real-world examples to help you understand the language better.

Table of Contents

  1. Hello, World!
  2. Variables and Data Types
  3. Conditional Statements
  4. Loops
  5. Arrays
  6. Functions (Methods)
  7. Object-Oriented Programming
  8. File Handling

Hello, World!

public class HelloWorld {
    public static void main(String[] args) {
        // This is a simple Java program that prints "Hello, World!" to the console.
        System.out.println("Hello, World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a Java program that consists of a class named HelloWorld. The main method is the entry point for the program, and it prints "Hello, World!" to the console using System.out.println.

Variables and Data Types

public class VariablesExample {
    public static void main(String[] args) {
        // Declare and initialize variables
        int age = 25;
        double salary = 50000.50;
        String name = "John Doe";

        // Print variable values
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we declare and initialize variables of different data types (int, double, and String). Then, we print the values of these variables to the console.

Conditional Statements (If-Else Statement)

public class IfElseExample {
    public static void main(String[] args) {
        // Define an age
        int age = 18;

        // Check if the age is greater than or equal to 18
        if (age >= 18) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are not yet an adult.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we use an if-else statement to check whether a person is an adult based on their age. If the age is greater than or equal to 18, it prints "You are an adult"; otherwise, it prints "You are not yet an adult."

Loops (For Loop)

public class ForLoopExample {
    public static void main(String[] args) {
        // Use a for loop to count from 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This example demonstrates a for loop that counts from 1 to 5 and prints the count at each iteration. The loop initializes i to 1, continues as long as i is less than or equal to 5, and increments i by 1 in each iteration.

Loops (While Loop)

public class WhileLoopExample {
    public static void main(String[] args) {
        // Use a while loop to count from 1 to 5
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This example uses a while loop to achieve the same counting from 1 to 5 as the previous example. It initializes i to 1, and the loop continues as long as i is less than or equal to 5. In each iteration, it prints the count and increments i.

Arrays

public class ArrayExample {
    public static void main(String[] args) {
        // Declare and initialize an integer array
        int[] numbers = {1, 2, 3, 4, 5};

        // Access and print array elements
        System.out.println("Element at index 0: " + numbers[0]);
        System.out.println("Element at index 2: " + numbers[2]);

        // Calculate and print the length of the array
        int length = numbers.length;
        System.out.println("Array length: " + length);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we declare and initialize an integer array called numbers. We access and print specific elements of the array using their indices (e.g., numbers[0] and numbers[2]). We also calculate and print the length of the array using numbers.length.

Functions (Methods)

public class MethodsExample {
    // Define a method to calculate the sum of two numbers
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        // Call the 'add' method and print the result
        int result = add(5, 3);
        System.out.println("Sum: " + result);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we define a method (add) that takes two integer parameters and returns their sum. In the main method, we call the add method with values 5 and 3, and then we print the result.

Object-Oriented Programming (Classes and Objects)

// Define a class named 'Person'
class Person {
    String name;
    int age;

    // Constructor to initialize 'name' and 'age'
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display person information
    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class OOPExample {
    public static void main(String[] args) {
        // Create objects of the 'Person' class
        Person person1 = new Person("Alice", 25);
        Person person2 = new Person("Bob", 30);

        // Call the 'displayInfo' method for each person
        person1.displayInfo();
        person2.displayInfo();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we define a class called Person with attributes (name and age) and a constructor to initialize them. We also define a method (displayInfo) to display the person's information. In the main method, we create two Person objects, set their attributes, and call the displayInfo method for each object.

File Handling (Reading and Writing)

import java.io.*;
public class FileHandlingExample {
    public static void main(String[] args) {
        try {
            // Create a FileWriter to write to a file
            FileWriter writer = new FileWriter("sample.txt");
            writer.write("Hello, File Handling!");
            writer.close();

            // Create a FileReader to read from the file
            FileReader reader = new FileReader("sample.txt");
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we demonstrate basic file handling in Java. We use a FileWriter to write the string "Hello, File Handling!" to a file named "sample.txt" and a FileReader to read and print the contents of the same file.

These additional examples cover arrays, methods, object-oriented programming (classes and objects), and file handling in Java. If you have any specific questions or if you'd like to see more examples related to a particular topic, please feel free to ask.

Top comments (3)

Collapse
 
sf2apk profile image
shadow fight

🙌 Thank you, Java for Beginners! 📚 Your course made learning Java feel like a fun game 🎮. It's like you turned coding into a captivating puzzle 🧩, and I couldn't be more grateful 🙏. Cheers to unlocking the world of programming! 🚀 #JavaRocks #GameOn 🤩👏

Collapse
 
kiraaziz profile image
kiraaziz

thx a lot dude that realy mean a lot to me ❤️✨

Collapse
 
artydev profile image
artydev

Thank you