Hello, Java: Writing Your First Program

Java Introduction: Part II

Marcelo Domingues
devdomain
12 min readJun 29, 2024

--

Reference Image

Overview: Structure of a Java Program

Before you write your first Java program, it’s a good practice to understand how a Java program is structured. If you have not already read through Part I of the series for a detailed introduction to Java and the setup of the environment, please do so.

A typical Java program will contain at least the following components:

  1. Package Declaration (optional): It defines the package in which the class resides.
  2. Import Statements (optional): They can be used to import other Java classes or packages.
  3. Class Declaration: It is a class blueprint for objects.
  4. Main Method: The primary method is the entry point into any Java application. This is where program execution begins.

Below is the basic layout of a Java program:

package com.medium; // Package declaration

import java.util.*; // Import statements

public class Main { // Class declaration
public static void main(String[] args) { // Main method
// Code to be executed
}
}

Write and Run a Very Simple Program

Let’s create a simple Java program that will just print to the console “Hello, Java!”. Here’s how:

1. Create a New Project and Class:

  • Open your IDE (IntelliJ IDEA or Eclipse).
  • Create a new Java project.
  • Create a new Java class named Main.

2. Write the Code:

  • In the Main class, add the following code:
package com.medium;

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

3. Run the Program:

  • In IntelliJ IDEA, click the green Run button in the toolbar or right-click the file and select Run 'Main'.
  • In Eclipse, click the green Run button in the toolbar or right-click the file and select Run As -> Java Application.
Hello, Java!

Explanation of the Main Method and Basic Syntax

The Main Method

The main method is the entry point of any Java application. It has a specific signature that the Java Virtual Machine (JVM) recognizes to start execution.

Signature:

public static void main(String[] args)
  • public: The method is accessible from anywhere.
  • static: The method belongs to the class, not an instance of the class. This allows the JVM to call the method without creating an instance of the class.
  • void: The method does not return any value.
  • main: The name of the method. This is a special name that the JVM looks for as the starting point of the program.
  • String[] args: The parameter is an array of String objects. This allows the method to accept command-line arguments.

Basic Syntax

Understanding the basic syntax of Java is essential for writing and reading Java code. Here are some fundamental elements:

1. Classes and Objects:

In Java, classes are the blueprint or template to create objects. A class bundles data (attributes) and behavior (methods) into a single unit to make code organization easier and reusability possible.

Consider you are developing some software for managing a fleet of cars. Each of these cars can be visualized as an object containing specific attributes, for example, color or model, and behaviors like start or stop. The class Car describes the structure and how one can access the attributes and behaviors.

Example:

public class Car {
// Fields (attributes)
String color;
String model;

// Methods (behavior)
void start() {
System.out.println("Car started");
}
void stop() {
System.out.println("Car stopped");
}
public static void main(String[] args) {
Car myCar = new Car(); // Create an object of Car
myCar.color = "Red";
myCar.model = "Tesla Model 3";
System.out.println("Car color: " + myCar.color);
System.out.println("Car model: " + myCar.model);
myCar.start();
myCar.stop();
}
}

If you run the main, you will obtain in your console:

Car model: Tesla Model 3
Car started
Car stopped
  • Fields: color and model store the state (attributes) of the Car object.
  • Methods: start() and stop() define actions (behaviors) that a Car object can perform.
  • Object Creation: Car myCar = new Car(); initializes an instance (myCar) of the Car class.
  • Accessing Object Members: myCar.color and myCar.model access and modify object attributes.
  • Method Invocation: myCar.start() and myCar.stop() invoke object methods to perform actions.

By understanding classes and objects, beginners can structure their programs more intuitively, modeling real-world entities and their interactions effectively.

2. Variables:

In Java, the variables are containers of any data value. They must be declared with a data type precisely; in other words, the type of data that can be stored in that variable (such as integer, string).

Variables can thus be visualized as boxes that have labels to store things of different types. Each box has a label — that is, a name — and can hold specific types of items: that is, data.

Example:

public class Variables {
public static void main(String[] args) {
int number = 10; // Integer variable
String message = "Hello, Java!"; // String variable
System.out.println("Number: " + number);
System.out.println("Message: " + message);
}
}

If you run the main, you will obtain in your console:

Number: 10
Message: Hello, Java!
  • Variable Declaration: int number = 10; declares an integer variable number initialized to 10.
  • Data Type: int specifies the type of data the variable can hold (integer).
  • String Variable: String message = "Hello, Java!"; declares a string variable message initialized with a text value.
  • Printing Variables: System.out.println("Number: " + number); and System.out.println("Message: " + message); display variable values on the console.

Variables enable programmers to store and manipulate data dynamically within their programs, facilitating flexible and interactive applications.

3. Data Types:

Java, being a strongly typed language, every variable will have an associated data type that determines the size and type of values to be stored in a variable.

Examples of data types in Java include integers, floating-point numbers, characters, and boolean values. A data type identifies different kinds of data with which programs can operate. Each data type has specific characteristics and uses in the program.

Example:

public class DataTypes {
public static void main(String[] args) {
int num = 5; // Integer type
double price = 19.99; // Double type
char letter = 'A'; // Character type
boolean isJavaFun = true; // Boolean type
System.out.println("Integer: " + num);
System.out.println("Double: " + price);
System.out.println("Character: " + letter);
System.out.println("Boolean: " + isJavaFun);
}
}

If you run the main, you will obtain in your console:

Integer: 5
Double: 19.99
Character: A
Boolean: true
  • Integer: int num = 5; stores whole numbers without decimal points.
  • Double: double price = 19.99; stores floating-point numbers with decimal precision.
  • Character: char letter = 'A'; stores single characters enclosed in single quotes.
  • Boolean: boolean isJavaFun = true; stores true/false values for logical comparisons.

Understanding data types helps programmers choose appropriate storage for different kinds of data and ensures accurate computation and representation within programs.

4. Operators:

Java operators make operations with variables and values. They consist of arithmetic operators (+, -, *, /, %), assignment operators (=), comparison operators (==, !=, <, >, <=, >=), and logical operators (&&, ||, !).

Typically, operators are characters that manipulate values of some data in making some calculation, comparison, or logical decision in an application.

Example:

public class Operators {
public static void main(String[] args) {
int sum = 10 + 20; // Addition
int diff = 20 - 10; // Subtraction
int prod = 10 * 20; // Multiplication
int quotient = 20 / 10; // Division
int remainder = 20 % 3; // Modulus
System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
System.out.println("Product: " + prod);
System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);
}
}

If you run the main, you will obtain in your console:

Sum: 30
Difference: 10
Product: 200
Quotient: 2
Remainder: 2
  • Arithmetic Operators: +, -, *, /, % perform addition, subtraction, multiplication, division, and modulus operations respectively.
  • Assignment Operator: = assigns a value to a variable (sum = 10 + 20;).
  • Modulus Operator: % returns the remainder of a division (remainder = 20 % 3;).

Operators are fundamental for performing mathematical calculations, logical evaluations, and data manipulations in Java programs.

5. Control Flow Statements:

Control flow statements determine how and in what order the program’s instructions will be executed. These statements include decisions (if-else), loops (for, while, do-while), and branches (break, continue, return). Control statements determine the order of execution of instructions provided certain conditions, loops, and the structure of the program.

Example:

public class ControlFlow {
public static void main(String[] args) {

// If-Else statement
int age = 18;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Not an Adult");
}

// For Loop
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
// While Loop
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}

// Do-While Loop
int num = 0;
do {
System.out.println("Number: " + num);
num++;
} while (num < 5);
}
}

If you run the main, you will obtain in your console:

Adult
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
  • If-Else Statement: if (age >= 18) { ... } else { ... } checks a condition (age >= 18) and executes different code blocks based on whether it's true or false.
  • For Loop: for (int i = 0; i < 5; i++) { ... } iterates a block of code (System.out.println("Iteration: " + i);) a specified number of times.
  • While Loop: while (count < 5) { ... } repeats a block of code (System.out.println("Count: " + count);) while a condition (count < 5) is true.
  • Do-While Loop: do { ... } while (num < 5); executes a block of code (System.out.println("Number: " + num);) once, then repeats it while a condition (num < 5) remains true.

Control flow statements allow programmers to create flexible, interactive programs that respond dynamically to changing conditions and inputs.

6. Methods:

A Java method encloses code that performs a certain operation or task. It enhances modularity, reusability, and maintainability of the code, as it allows a complex task to be broken down into smaller, more manageable sub-tasks.

Methods allow programmers to define functionality once and use it in a program many times over, making the execution of that program efficient without redundancy.

Example:

public class Methods {
// Method to add two numbers
public int add(int a, int b) {
return a + b;
}

// Method to subtract two numbers
public int subtract(int a, int b) {
return a - b;
}
public static void main(String[] args) {
Methods calc = new Methods();
int sum = calc.add(10, 5);
int diff = calc.subtract(10, 5);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
}
}

If you run the main, you will obtain in your console:

Sum: 15
Difference: 5
  • Method Declaration: public int add(int a, int b) { ... } defines a method named add that takes two integer parameters (a and b) and returns their sum.
  • Method Invocation: int sum = calc.add(10, 5); and int diff = calc.subtract(10, 5); call the add and subtract methods respectively, passing arguments (10, 5) and storing the returned results (sum, diff).
  • Code Reusability: By defining methods (add, subtract), you can perform specific computations (addition, subtraction) repeatedly with different inputs.

Methods enhance code organization, readability, and maintenance, enabling programmers to build modular and scalable Java applications.

7. Arrays:

Arrays in Java are data structures with values of the same data type under one variable name. They provide a way for indexed access to elements and make handling collections of data very efficient.

The power of arrays is that they help the programmer hold similar data types in one group, thereby leading to easy manipulations with bulk data.

Example:

public class ArraysExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
String[] fruits = {"Apple", "Banana", "Cherry"}; // Array of strings
// Access elements in an array
System.out.println("First number: " + numbers[0]);
System.out.println("First fruit: " + fruits[0]);
// Loop through an array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Number: " + numbers[i]);
}
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}

If you run the main, you will obtain in your console:

First number: 1
First fruit: Apple
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Fruit: Apple
Fruit: Banana
Fruit: Cherry
  • Array Declaration: int[] numbers = {1, 2, 3, 4, 5}; and String[] fruits = {"Apple", "Banana", "Cherry"}; create arrays of integers (numbers) and strings (fruits) respectively, initializing them with specified values.
  • Index Access: numbers[0] and fruits[0] access the first elements (1 and "Apple").
  • Looping through Arrays: for (int i = 0; i < numbers.length; i++) { ... } iterates through the numbers array, printing each element (Number: 1, Number: 2, ...).
  • Enhanced for Loop: for (String fruit : fruits) { ... } iterates through the fruits array, printing each element (Fruit: Apple, Fruit: Banana, ...).

Arrays facilitate efficient storage, retrieval, and manipulation of data sets, providing essential capabilities for handling collections of values in Java programs.

8. Exception Handling:

Exception Handling in Java can handle runtime errors and other unexpected situations that might occur in a program during its execution. In simple words, it gives an approach in a program where the program can recover gracefully and continue with its normal flow even after it has been raised abnormally and does not terminate abnormally.

Suppose you are developing an application for computing mathematical operations, among which there is division. An exception raised by a division operation is a runtime exception caused by dividing by 0. Exception handling lets you anticipate such an error and take corrective steps regarding how the program should recover or respond intelligently to the mistake.

Example:

public class ExceptionHandling {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will cause an exception
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divide(int a, int b) {
return a / b;
}
}

If you run the main, you will obtain in your console:

Error: / by zero
  • try-catch Block: The try block encloses code that might throw an exception. If an exception occurs (e.g., division by zero), control transfers to the corresponding catch block.
  • Exception Handling: catch (ArithmeticException e) { ... } catches and handles the specific ArithmeticException that occurs during the division operation.
  • Exception Message: e.getMessage() retrieves the error message associated with the exception, allowing you to print or process it accordingly.

Exception handling ensures that your program can recover from unexpected errors gracefully, providing error messages or alternative paths of execution as needed.

Additional Examples

Using Loops to Process Arrays

This example demonstrates using loops to process array elements and calculate their sum.

Code:

public class ArrayProcessing {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
int sum = 0;

// For loop to calculate the sum of array elements
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("Sum of array elements: " + sum);
}
}

Output:

Sum of array elements: 15

Creating and Using Objects

This example shows how to create and use objects in Java.

Code:

class Dog {
String name;
String breed;

void bark() {
System.out.println(name + " is barking.");
}
}

public class ObjectExample {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create a Dog object
myDog.name = "Buddy";
myDog.breed = "Golden Retriever";

System.out.println("Dog's Name: " + myDog.name);
System.out.println("Dog's Breed: " + myDog.breed);
myDog.bark(); // Call the bark method
}
}

Output:

Dog's Name: Buddy
Dog's Breed: Golden Retriever
Buddy is barking.

Using Nested Loops

This example demonstrates the use of nested loops to print a multiplication table.

Code:

public class NestedLoops {
public static void main(String[] args) {
int rows = 5;

// Nested loops to generate a multiplication table
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}

Output:

1  2  3  4  5 
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Each of these additional examples showcases essential programming techniques and constructs in Java:

  • Array Processing: Demonstrates iterating through arrays and performing calculations.
  • Object Creation and Usage: Illustrates defining classes, creating objects, and invoking methods.
  • Nested Loops: Shows the use of nested loops to generate structured output (multiplication table).

Conclusion

Writing your first Java program is the best way to start the programming world. You will understand how a Java program is organized, how to write and run an elementary program, some basics of syntax, and the primary method. It is going to give you the basics needed to continue in the Java programming language. Examples within this document will demonstrate in practice the above-given concepts so that you can start developing your first Java programs.

Github

References

Explore More on Spring and Java Development:

Enhance your skills with our selection of articles:

  • Java Lambda Expressions: Techniques for Advanced Developers (Jun 19, 2024): Dive deep into advanced usage of lambda expressions in Java. Read More
  • Mastering Spring Security: Roles and Privileges (Jun 19, 2024): Learn the essentials of managing roles and privileges in Spring Security. Read More
  • Publishing Your Java Library to Maven Central: A Step-by-Step Tutorial (Mar 25, 2024): A comprehensive guide to making your Java library accessible to millions of developers worldwide. Read More
  • The Art of Unit Testing: Elevate Your Code with Effective Mocks (Mar 13, 2024): A complete guide to using mocks in unit testing, emphasizing the benefits of component isolation. Read More
  • Spring Beans Mastery (Dec 17, 2023): Unlock advanced application development techniques. Read More
  • JSON to Java Mapping (Dec 17, 2023): Streamline your data processing. Read More
  • Spring Rest Tools Deep Dive (Nov 15, 2023): Master client-side RESTful integration. Read More
  • Dependency Injection Insights (Nov 14, 2023): Forge better, maintainable code. Read More
  • Spring Security Migration (Sep 9, 2023): Secure your upgrade smoothly. Read More
  • Lambda DSL in Spring Security (Sep 9, 2023): Tighten security with elegance. Read More
  • Spring Framework Upgrade Guide (Sep 6, 2023): Navigate to cutting-edge performance. Read More

--

--

Marcelo Domingues
devdomain

🚀 Senior Software Engineer | Crafting Code & Words | Empowering Tech Enthusiasts ✨ 📲 LinkedIn: https://www.linkedin.com/in/marcelogdomingues/