Java for Beginners: Platform Independent Programming (JVM)

Java for Beginners: Coding Console
Exploring Java basics with Coding Console

That pocket-sized computer you call a phone? It’s running on an operating system powered by Java, along with 2.5 billion other Android devices worldwide.

Minecraft–that blocky virtual world where you and 140 million monthly players sculpt your imagination? Yep, that’s Java flexing its muscles too.

But hold onto your hat, because Java’s reach extends far beyond your daily screen time.

Ever withdrawn cash from an ATM? Watched a movie on a smart TV? Popped in a Blu-ray disc? You’ve been shaking hands with Java and didn’t even know it.

If you’re an Astro-enthusiast! know that Java—the same programming language powering your everyday apps—is also steering Mars Rover’s tireless journey across the rusty Martian terrain.

Now, you might be wondering, “What sorcery is this? How can one language be so versatile?” Buckle up, in a short while you’ll be knowing a lot about java  – a language so pervasive, you’ve probably used it a hundred times today without even realizing it.

What is Java?

Java is a high-level, Object Oriented Programming language known for its cross-platform capabilities. Originally designed by James Gosling and his team at Sun Microsystems in 1991, its name was set to “Oak” a name inspired by a sturdy oak tree standing sentinel outside James’ office. 

Oak, a symbol of strength and endurance seemed fitting for a language built to withstand the test of the time. The team soon discovered that the name “Oak” was already trademarked by Oak Technologies. 

Gosling and his colleagues again embarked on a lively brainstorming session. But it was during a coffee break that inspiration struck.

Sipping on a cup of Java, a type of Indonesian coffee known for its rich flavor, Gosling had his eureka moment. “Java” – unique, short and with a kick. 

Java wasn’t just named thoughtfully; it was built meticulously. The language was founded on principles of robustness, portability, and platform independence. It promised high performance and embraced multi-threading, setting the stage for a revolution in programming.  

What is Java used for?

Java is a fast, secure, and reliable programming language widely used for developing mobile apps, enterprise software, big data applications and server-side technologies, making it a trusted choice for developers globally.

Java’s key feature, platform independence, allows programs written in Java to run on any operating system(OS) with a Java Virtual Machine (JVM) installed. This “write once, run anywhere” philosophy has made Java a favorite among developers working on diverse platforms. 

According to Distant Jobs, there were 9.4 Million Java developers globally as of May 2023. Java is taught in over 1,000 universities worldwide and Oracle alone has issued over 1 million Java Developer Certifications to this day.

With over 2.5 billion active devices running on Java-based Android OS and used by 90% of Fortune 500 companies, has spellbound the programming community with its impeccable performance. StackShare claims that notable companies use Java including following: 

  1. Google: Powers parts of its search algorithm and Android OS  
  2. Amazon: Utilizes Java for its e-commerce platform and AWS  
  3. Netflix: Uses Java for backend services  
  4. Uber: Employs Java in core ride-sharing applications  
  5. Airbnb: Uses Java for backend systems  
  6. Spotify: Relies on Java for its music streaming service  
  7. LinkedIn: Utilizes Java for its social networking platform  
  8. NASA: Employs Java in space exploration projects  
  9. Twitter: Uses Java in core infrastructure  
  10. Intel: Leverages Java in software development projects
Java for Beginners: Coding Console

Java’s Revolutionary Journey: Key Milestones and Their Impact

 
  • 1995 – Java’s Birth: Write Once, Run Anywhere

    Java introduced platform independence, allowing code to run on any device with a Java Virtual Machine. This breakthrough eliminated the need for platform-specific versions, significantly reducing development time and costs. It positioned Java as a versatile language suitable for diverse computing environments.

  • 1996 – Java Applets: Dynamic Web Content

    Java Applets brought interactivity to web browsers, transforming static web pages into dynamic experiences. This innovation allowed developers to create rich, responsive web applications, enhancing user engagement. Applets paved the way for modern web technologies and showcased Java’s potential beyond traditional software.

  • 1998 – Java 2 Platform: Enhanced Desktop Development

    Java 2 introduced the Swing framework, enabling creation of sophisticated graphical interfaces across platforms. The new Collections framework simplified data handling, making Java more efficient for complex applications. These additions made Java a strong contender in desktop application development, competing with established languages like C++.

  • 2002 – J2EE: Conquering Enterprise Software

    Java 2 Enterprise Edition provided tools for building large-scale, distributed systems. It introduced standardized components for server-side development, simplifying creation of robust business applications. J2EE established Java as the go-to language for enterprise software, outpacing competitors in reliability and scalability.

  • 2006 – Open Source Java: Community-Driven Innovation

    Sun Microsystems released Java as open-source, allowing global developer contributions. This move fostered rapid innovation and expansion of Java’s capabilities through community involvement. Open-sourcing led to an explosion of third-party libraries and frameworks, greatly expanding Java’s ecosystem.

  • 2010 – Oracle Acquisition: Corporate Backing

    Oracle’s acquisition of Sun Microsystems brought strong corporate support to Java. This transition ensured continued development and support for the language. Oracle’s resources and business focus drove Java’s evolution towards more enterprise-friendly features and regular updates.

  • 2014 – Java 8: Embracing Functional Programming

    Java 8 introduced lambda expressions and the Stream API, bringing functional programming to Java. These features allowed for more concise, readable code and efficient data processing. This update modernized Java, helping it compete with newer languages that emphasized functional programming.

  • 2017 – Java 9: Modular Programming

    The Java Platform Module System improved application scalability and security. It allowed developers to create more maintainable, efficient applications by breaking them into modules. This feature positioned Java as a more robust option for large-scale application development.

  • 2018 – Rapid Release Cycle: Keeping Pace with Change

    Java adopted a six-month release cycle, enabling faster introduction of new features. This agile approach allowed Java to adapt to emerging technologies and developer needs quickly. The new model kept Java competitive with rapidly evolving languages like Python and JavaScript.

  • 2021 – Java 17: Balancing Innovation and Stability

    Java 17 introduced modern features like sealed classes while maintaining long-term support. This release showcased Java’s ability to innovate while ensuring stability for enterprise users. It reinforced Java’s position as a reliable yet forward-thinking language in the ever-changing tech landscape.

Key Concepts in Java for Beginners

1. Variables and Data Types

Variables are containers for storing data values.. In Java a variable’s data type must be declared before using it. The general format is: 

type variableName = value;

				
					//Example
//1.Declare an integer variable called myNum with the value 15
int myNum = 15;

//2. Declare a String variable called name with the value "John"
String name = "John"; 
				
			

Data Types in Java are classified into 2, primitive and reference type.

Primitive Data Types:

  • Primitive data types are the fundamental building blocks in Java. They hold simple values directly in memory. They are:
Integers
  • byte holds small integers (-128 to 127)
  • short stores a bit wider range of integers (32768 to 32767)
  • int stores whole numbers (-2147483648 to 2147483647)
  • long has got your back when dealing with large numeric values (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) 

Floating-Point Numbers:

  • float data type is 32-bit floating-point number providing 6-7 decimal digits of precision.
  • double data type in Java is a 64-bit floating-point number providing 15-16 decimal digits of precision. 
Characters:
  • char represents a single Unicode character including letters, digits, special symbols and even escape sequences.
Boolean:
  • boolean has only two possible values: true or false, mainly used for logical conditions and control flow.

Reference Data Types:
Reference data types (also called non-primitive data types) don’t hold actual data but act as pointers to memory locations where objects reside. 
Think of them as “addresses” to objects in memory. 

  • Class: Describes the content of an object. User-defined classes fall into this category.
  • Array: Fixed-size data structure storing elements of the same type (e.g., int[], String[]).
  • Annotations: Associate metadata with program elements (e.g., @Override).
  • Interface: Implemented by Java classes (e.g., Runnable, Serializable).
  • Enumeration: Special class for type-safe constants (e.g., days of the week).
It should be noticed that the data types like int, double, boolean don’t start with capital letters but String does. Because String is not a primitive data type; it is a derived data type. Specifically, it’s a class present in the java.lang package.

Understanding variables and data types is crucial as they form the foundation of any Java program.

Here’s a simple example demonstrating variables and data types:

				
					//Example
public class VariablesExample {
    public static void main(String[] args) {
        // Declaring and initializing variables
        int age = 25;
        double height = 5.9;
        boolean isStudent = true;
        String name = "John Doe";

        // Printing variable values
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height + " feet");
        System.out.println("Is a student: " + isStudent);
    }
}
				
			

Name: John Doe

Age: 25

Height: 5.9 feet

Is a student: true

2. Control Flow Statements

Control flow statements allow you to control the flow of your program’s execution. They include if-else statements for decision making and loops for repetitive tasks.

The if-else statement executes different code blocks based on whether a condition is true or false. Loops like for and while repeat a block of code multiple times.

These statements are essential for creating dynamic and responsive programs.

Let’s look at an example using both if-else and a for loop:

				
					//Example
public class ControlFlowExample {
    public static void main(String[] args) {
        int number = 10;
        // If-else statement
        if (number > 0) {
            System.out.println(number + " is positive");
        } else if (number < 0) {
            System.out.println(number + " is negative");
        } else {
            System.out.println(number + " is zero");
        }
        // For loop
        System.out.println("Counting from 1 to 5:");
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);}
    }
}
				
			

10 is positive
Counting from 1 to 5:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

3. Arrays in Java

An array is a container that holds a fixed number of values of a single type. It’s useful for storing multiple items of the same kind, like a list of numbers or names.

You can access array elements using their index, which starts at 0 for the first element. Arrays have a fixed size that’s set when they’re created.

Understanding arrays is crucial for managing collections of data efficiently.

Here’s an example showing how to work with arrays:

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

        // Accessing array elements
        System.out.println("First number: " + numbers[0]);
        System.out.println("Third number: " + numbers[2]);

        // Modifying an array element
        numbers[4] = 10;
        System.out.println("Modified fifth number: " + numbers[4]);

        // Looping through an array
        System.out.println("All numbers in the array:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}
				
			

First number: 1
Third number: 3
Modified fifth number: 10
All numbers in the array:
1
2
3
4
10

4. Methods in Java

A method is a reusable block of code that performs a specific task. It encapsulates functionality and promotes code organization. To define a method, use the following syntax:

returnType methodName(parameters) {}

Calling Methods in Java
To call a method, use its name followed by parentheses(), with or without arguments.

				
					//Example
int result = addNumbers(5, 3); 
// Calling a method named "addNumbers"

				
			
Returning Values in Java

If a method returns a value, specify the return type (other than void). Like in the code below, return type for the method addNumbers is specified as intUse the return keyword to send a value back.

The return keyword in a method serves two essential purposes:

  1. Value Transmission
    It sends a value back from the method to the caller. The value being sent back can be of any data type e.g., int,float,char or a String class.
  2. Termination Signal
    When return is encountered, it immediately exists the method, skipping any subsequent code. Useful for control flow and ensuring the method completes its task. Remember, the return keyword is like a messenger—it delivers a value and signals when it’s done!
				
					//Example
int addNumbers(int a, int b) {
    return a + b;
}

				
			
Passing Parameters in Java

Methods can take parameters (inputs) to perform their tasks. Parameters allow methods to receive input values and are specified within the parentheses. 

In others words parameters act as placeholders for data that the method needs to work with.

				
					//Example
void greetUser(String name) {
    System.out.println("Hello, " + name + "!");
}

				
			

Below example shows how to define and call methods with different return types and parameters.

				
					//Example
public class MethodExample {
    public static void main(String[] args) {
        // Calling a method that doesn't return a value
        greet("John");

        // Calling a method that returns a value
        int sum = add(5, 3);
        System.out.println("Sum: " + sum);

        // Calling a method with multiple parameters
        double average = calculateAverage(80, 90, 75);
        System.out.println("Average: " + average);
    }

    // Method with no return value (void)
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Method that returns an int
    public static int add(int a, int b) {
        return a + b;
    }

    // Method with multiple parameters
    public static double calculateAverage(double num1, double num2, double num3) {
        return (num1 + num2 + num3) / 3;
    }
}
				
			
  1. Calling greet(“John”):
    The greet method is called with the argument “John”.
    It prints: Hello, John!
  2. Calling add(5, 3) and Assigning to sum:
    The add method is called with arguments 5 and 3.
    It returns the sum of these numbers (which is 8).
    The value 8 is assigned to the variable sum.
    It prints: Sum: 8
  3. Calling calculateAverage(80, 90, 75) and Assigning to average:
    The calculateAverage method is called with three arguments: 80, 90, and 75.
    It calculates the average of these numbers (which is (80 + 90 + 75) / 3 = 81.67).
    The value 81.67 (rounded to two decimal places) is assigned to the variable average.
    It prints: Average: 81.67

 So the complete output will be:
Hello, John!
Sum: 8
Average: 81.67

5. Object-Oriented Programming Basics 

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”. In Java, almost everything is an object.

The main ideas behind OOP are classes (blueprints for objects) and objects (instances of classes). Classes define the properties (attributes) and behaviors (methods) that their objects will have.This process can be implicit or explicit, and it occurs in various scenarios to maintain the flexibility and functionality of the language.

Here’s a simple example demonstrating basic OOP concepts:

				
					//Example
// Define a class
class Car {
    // Attributes
    String brand;
    String color;
    // Constructor
    public Car(String brand, String color) {
        this.brand = brand;
        this.color = color;}
        // Method
    public void displayInfo() {
        System.out.println("This is a " + color + " " + brand + " car.");}
}
public class OOPExample {
    public static void main(String[] args) {
        // Create objects of the Car class
        Car car1 = new Car("Toyota", "red");
        Car car2 = new Car("Honda", "blue");
        // Call methods on the objects
        car1.displayInfo();
        car2.displayInfo();   }
}
				
			

Two Car objects are created:

  • car1 with brand “Toyota” and color “red”.
  • car2 with brand “Honda” and color “blue”.

Calling displayInfo() Method:

  • For each car object, the displayInfo() method is called.
  • The method prints the car’s color and brand.
Java Code Output:
This is a red Toyota car.
This is a blue Honda car.

 

6. Exception Handling Basics

Exception handling is a way to deal with errors or unexpected situations in your program. It helps your program continue running even when something goes wrong.

Java uses try, catch, and finally blocks for exception handling. The try block contains code that might cause an error, the catch block handles the error, and the finally block runs regardless of whether an error occurred.

Understanding basic exception handling is crucial for writing robust programs that can handle unexpected situations gracefully.

Here’s a simple example of exception handling:

				
					//Example
public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // Code that might cause an exception
            int result = divideNumbers(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Handle the exception
            System.out.println("Error: Cannot divide by zero");
        } finally {
            // This block always executes
            System.out.println("Execution completed");
        }
    }

    public static int divideNumbers(int a, int b) {
        return a / b;
    }
}
				
			

try Block

  • Inside the try block, we attempt to divide 10 by 0 using the divideNumbers(10, 0) method.
  • However, dividing by zero is not allowed in mathematics, so it will throw an ArithmeticException.
 catch Block
  •  The catch block catches the exception (specifically, an ArithmeticException).
  • It prints: “Error: Cannot divide by zero”.
finally Block
  • The finally block always executes, regardless of whether an exception occurred or not.
  • It prints: “Execution completed”.

So the complete Java Code Output will be:

Error: Cannot divide by zero
Execution completed

Future-Proofing Your Java Skills

Java’s role in future technologies looks promising and multifaceted. Its stability and performance make it ideal for developing AI systems and quantum simulations. As these fields advance, Java is likely to evolve, offering more specialized tools and libraries.

The integration of Java with quantum computing may lead to new programming paradigms. Developers proficient in Java and quantum concepts will be well-positioned for future innovations. This intersection of classical and quantum computing opens up exciting possibilities for software development.

Embracing Java’s potential means staying curious and adaptable. The language’s journey from traditional applications to cutting-edge technologies is ongoing. By continually exploring and learning, developers can ride the wave of innovation that Java continues to surf

Conclusion

Java’s enduring presence in the tech world is a testament to its adaptability and robust feature set. It continues to evolve, addressing modern development challenges while maintaining its core strengths.

The Java ecosystem offers a wealth of opportunities for continuous learning and growth. Engaging with the community through forums, open-source projects, and events enriches one’s journey in Java development.

 

By embracing Java’s potential and staying curious about its advancements, developers position themselves at the forefront of innovation in software engineering.

 

Review Points

Key Review Points for Java Beginners:

  1. Java is object-oriented and platform-independent, allowing code to run on any device with a Java Virtual Machine.

  2. Understanding the ‘main‘ method is crucial, as it serves as the entry point for Java applications.

  3. Object-oriented programming in Java revolves around classes and objects, emphasizing encapsulation, inheritance, and polymorphism.

  4. Java’s automatic memory management through garbage collection helps prevent memory leaks and simplifies development.

  5. The ‘static‘ keyword in Java defines class-level members, shared across all instances of a class

  6. Java’s robust standard library provides a wide range of built-in functionality, reducing the need for external dependencies.

  7. Exception handling in Java allows for graceful error management, improving application reliability and user experience.

Related Articles