DEV Community

Cover image for Hello, world!
Bellamer
Bellamer

Posted on

Hello, world!

Your First Java Program - "Hello, World!"

Introduction

Welcome back! Now that you've set up your Java development environment, it's time to write your first Java program. The classic "Hello, World!" program is often the first step in learning any programming language. It’s simple yet powerful because it introduces you to the basic structure of a Java application.

Getting Started: Creating a Java Class

In Java, everything revolves around classes and objects. Your first step in writing a Java program is creating a class. Think of a class as a blueprint for creating objects.

Before we dive into the code, let’s discuss the naming conventions in Java:

  • Classes: Class names should be nouns and start with an uppercase letter. If the name consists of multiple words, capitalize the first letter of each word (e.g., HelloWorld, MyFirstProgram).
  • Methods: Method names should be verbs and start with a lowercase letter. If the name consists of multiple words, capitalize the first letter of each subsequent word (e.g., printMessage, calculateSum).

Now, let’s create your first class and method following these conventions.

  1. Open your IDE: Start by opening the IDE you set up in the last post (Eclipse, IntelliJ IDEA, or NetBeans).
  2. Create a new project: Go to File > New > Java Project. Name your project FirstJavaProgram and click Finish.
  3. Create a new class: Right-click on the src folder in your project, select New > Class, and name the class HelloWorld. Check the box that says "public static void main(String[] args)" to include the main method and click Finish.

Writing the "Hello, World!" Program

Now that your class is ready, it's time to write the code. The main method is the entry point of any Java application. Here’s what your first Java code should look like:

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

Breaking Down the Code:

  • public class HelloWorld: This line declares a class named HelloWorld. In Java, every application must have at least one class, and the name should match the filename. Notice that the class name starts with an uppercase letter, following the naming convention.
  • public static void main(String[] args): This line defines the main method, where your program begins execution. The main method is required in every Java program and follows the naming convention for methods, starting with a lowercase letter.
  • System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console. System.out is used to output text, and println adds a new line after printing.

Compiling and Running Your Program

Java is a compiled language, meaning that the source code you write must be converted into bytecode by the Java compiler before it can run on the Java Virtual Machine (JVM).

Here’s how to compile and run your program:

  1. Save your file: Make sure your file is saved as HelloWorld.java.
  2. Compile: In most IDEs, you don’t need to compile manually, but if you're using a command line, navigate to the directory containing your HelloWorld.java file and type:
   javac HelloWorld.java
Enter fullscreen mode Exit fullscreen mode

This will create a HelloWorld.class file, which contains the bytecode.

  1. Run: To run the compiled program, type:
   java HelloWorld
Enter fullscreen mode Exit fullscreen mode

You should see "Hello, World!" printed in the console.

Understanding Data Types and Variables

In Java, a variable is a container that holds data that can be used and manipulated throughout your program. Every variable in Java has a data type that determines what kind of data it can store.

Declaring a Variable

To declare a variable in Java, you need to specify its data type followed by the variable name. Initially, this variable will have a default value (depending on the data type) or be null for reference types. You can assign a specific value to this variable using the equal sign =.

Syntax:

dataType variableName;    // Declaration
variableName = value;     // Assignment
Enter fullscreen mode Exit fullscreen mode

Or, you can declare and assign a value in one step:

dataType variableName = value;
Enter fullscreen mode Exit fullscreen mode

Here are some basic data types in Java:

int: Stores whole numbers (e.g., 5, -10).
double: Stores decimal numbers (e.g., 5.99, -10.5).
char: Stores a single character (e.g., 'A', 'z').
boolean: Stores true or false.
Example: Declaring and Assigning Variables

int age;           // Declaration
age = 25;          // Assignment
double price = 19.99;  // Declaration and assignment in one step
char grade;        // Declaration
grade = 'A';       // Assignment
boolean isJavaFun = true;  // Declaration and assignment in one step
Enter fullscreen mode Exit fullscreen mode

Explanation:
int age; declares a variable named age of type int. Initially, age holds a default value of 0. Then, age = 25; assigns the value 25 to the age variable.
double price = 19.99; declares a double variable named price and immediately assigns it the value 19.99.
char grade; declares a variable named grade of type char, which can hold a single character. Then, grade = 'A'; assigns the character 'A' to grade.
boolean isJavaFun = true; declares a boolean variable and assigns it the value true.
This clear distinction between declaration and assignment is important for understanding how Java handles variables.

Basic Operations in Java

Java supports various operations that you can perform on variables. These include arithmetic operations like addition, subtraction, multiplication, and division.

Example: Arithmetic Operations

int a = 10;
int b = 5;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;

System.out.println("Sum: " + sum);            // Prints: Sum: 15
System.out.println("Difference: " + difference); // Prints: Difference: 5
System.out.println("Product: " + product);    // Prints: Product: 50
System.out.println("Quotient: " + quotient);  // Prints: Quotient: 2
Enter fullscreen mode Exit fullscreen mode

Common Errors and Troubleshooting

When learning to code, encountering errors is common. Here are some typical errors you might see while writing your first Java program and how to fix them:

  • Class not found: Ensure your file name matches your class name, and you’re in the correct directory when running your code.
  • Syntax errors: Ensure all brackets {}, parentheses (), and semicolons ; are correctly placed.
  • Unresolved compilation problem: Double-check for typos in your code, such as missing a semicolon or using incorrect capitalization.

Summary

Congratulations! You've just written your first Java program. Along the way, you’ve learned about Java's basic structure, naming conventions, how to print to the console, and how to work with variables and simple operations.

Beginner Challenge

  • Challenge: Modify the "Hello, World!" program to print your name instead. Then, declare variables for your age, favorite letter, and whether or not you like programming. Print these values to the console using System.out.println().

Next Steps

In the next post, we'll explore control flow statements like if-else and loops to make your programs more dynamic and interactive.

Tags:

#Java #Beginner #HelloWorld #Programming #FirstProgram

Top comments (2)

Collapse
 
samiekblad profile image
Sami Ekblad

As shortcut to web development in Java check out vaadin.com/flow. There is even a visual editor, but it is all Java. Here is HelloWorld web app:

@Route("/")
public class HelloWorld extends VerticalLayout {
    public HelloWorld() {
        add(new Text("Hello World"));
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
be11amer profile image
Bellamer

I found it cool and will definitely try it out.