Introduction to Java Programming

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will explore the concept of high-level programming languages, their advantages, and how Java works. You will learn to write and run your first Java program, gaining hands-on experience with the basics of Java programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/classes_objects -.-> lab-178546{{"`Introduction to Java Programming`"}} java/class_methods -.-> lab-178546{{"`Introduction to Java Programming`"}} java/modifiers -.-> lab-178546{{"`Introduction to Java Programming`"}} java/oop -.-> lab-178546{{"`Introduction to Java Programming`"}} java/comments -.-> lab-178546{{"`Introduction to Java Programming`"}} java/output -.-> lab-178546{{"`Introduction to Java Programming`"}} java/strings -.-> lab-178546{{"`Introduction to Java Programming`"}} java/system_methods -.-> lab-178546{{"`Introduction to Java Programming`"}} end

Understanding Programming Languages

Programming languages are categorized into high-level and low-level languages. Low-level languages, such as machine language and assembly language, are directly executable by computers. High-level languages, on the other hand, need translation into low-level languages before execution.

High-level languages offer several advantages:

  1. Easier programming: The code is shorter, more readable, and less prone to errors.
  2. Portability: The same program can run on different machines with minimal modifications.

Due to these benefits, most programs are written in high-level languages, with low-level languages reserved for specific applications.

There are two methods to translate high-level languages into low-level languages:

  1. Interpretation: An interpreter reads and executes high-level language code line by line.
  2. Compilation: A compiler translates the entire high-level program into executable code at once.

Java employs a hybrid approach, using both compilation and interpretation:

  1. Java source code is first compiled into bytecode.
  2. The bytecode is then interpreted and executed by the Java Virtual Machine (JVM).

This approach combines the portability of interpreted languages with the performance benefits of compiled languages.

What is a Program?

A program is a sequence of instructions that specifies how to perform a computation. Whether mathematical or symbolic, all programs are composed of statements that perform these basic operations:

  1. Input: Receive data from various sources (keyboard, files, etc.).
  2. Output: Display or send data to various destinations (screen, files, etc.).
  3. Mathematics: Perform arithmetic operations.
  4. Testing: Check conditions and execute appropriate statements.
  5. Repetition: Execute operations repeatedly, often with variations.

Programming involves breaking down complex tasks into smaller subtasks until they can be implemented using these basic operations.

Writing Your First Java Program

Let's create your first Java program, traditionally known as the "Hello, World!" program. This simple program displays the text "Hello, World!" on the screen.

LabEx utilizes an online WebIDE, similar to VS Code, for writing and running Java programs.

alt text

First, we need to create a new file called Hello.java in the ~/project directory. Open your terminal and execute the following commands:

cd ~/project
touch Hello.java

Now, open the Hello.java file in a text editor and enter the following code:

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Let's break down this program:

  1. public class Hello: This line defines a class named Hello. In Java, every program must have at least one class.
  2. public static void main(String[] args): This is the main method. It's the entry point of your Java program. When you run a Java program, execution begins in the main method.
  3. System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console. System.out is an object that represents the standard output, and println is a method that prints a line of text.

Compiling and Running Your Java Program

Now that we have written our Java program, let's compile and run it. Java uses a two-step process:

  1. Compilation: Convert the human-readable Java code into bytecode.
  2. Execution: Run the bytecode using the Java Virtual Machine (JVM).

To compile your program, use the javac command followed by the name of your Java file:

javac Hello.java

This command will create a new file called Hello.class in the same directory. This file contains the bytecode version of your program.

alt text

To run your program, use the java command followed by the name of your class (without the .class extension):

java Hello

You should see the output:

Hello, World!
alt text

If you encounter any errors, double-check your code for typos and ensure you're in the correct directory (~/project).

Understanding Java Program Structure

Let's take a closer look at the structure of our Java program:

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  1. public class Hello: This line declares a public class named Hello. In Java, the class name must match the filename (excluding the .java extension).

  2. public static void main(String[] args): This is the main method declaration. It's the entry point of your Java program.

    • public: This keyword makes the method accessible from outside the class.
    • static: This keyword means the method belongs to the class itself, not to any specific instance of the class.
    • void: This indicates that the method doesn't return any value.
    • main: This is the name of the method. The Java runtime looks for this method to start executing the program.
    • String[] args: This declares a parameter that can accept command-line arguments.
  3. System.out.println("Hello, World!");: This line prints text to the console.

    • System is a class that provides access to system resources.
    • out is a static member of the System class, representing the standard output stream.
    • println is a method of the PrintStream class (which out is an instance of) that prints a line of text.

Modifying Your Java Program

Now that you understand the basic structure of a Java program, let's modify our "Hello, World!" program to make it more interactive. We'll create a program that asks for the user's name and then greets them.

First, let's create a new file called Greeting.java in the ~/project directory:

cd ~/project
touch Greeting.java

Now, open Greeting.java in a text editor and enter the following code:

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Hello, " + name + "! Welcome to Java programming.");

        scanner.close();
    }
}

Let's break down the new elements in this program:

  1. import java.util.Scanner;: This line imports the Scanner class, which we use to read user input.
  2. Scanner scanner = new Scanner(System.in);: This creates a new Scanner object that reads from the standard input (keyboard).
  3. System.out.print("Please enter your name: ");: This prints a prompt for the user without moving to a new line.
  4. String name = scanner.nextLine();: This reads a line of text entered by the user and stores it in the name variable.
  5. System.out.println("Hello, " + name + "! Welcome to Java programming.");: This prints a greeting that includes the user's name.
  6. scanner.close();: This closes the Scanner object to free up resources.

Now, compile and run your new program:

javac Greeting.java
java Greeting
alt text

When prompted, enter your name, and you should see a personalized greeting.

Summary

In this lab, you have taken your first steps into the world of Java programming. You've learned about high-level programming languages and their advantages, and how Java combines compilation and interpretation for efficient execution. You've written, compiled, and run your first Java program, the traditional "Hello, World!" application. You've also created a more interactive program that takes user input and provides a personalized greeting.

These fundamental concepts and skills form the foundation of Java programming. As you continue your journey, you'll build upon these basics to create more complex and powerful applications. Remember, programming is a skill that improves with practice, so don't hesitate to experiment with your code and try new things.

If you want to learn more about LabEx and how to use it, you can visit our Support Center. Or you can watch the video to learn more about LabEx.

Your journey in Java programming has just begun. Keep practicing, keep learning, and enjoy the process of becoming a proficient Java programmer!

Other Java Tutorials you may like