BLOG POSTS
How to Write Your First Program in Java

How to Write Your First Program in Java

Java has been powering enterprise applications and server-side development for decades, making it one of the most essential programming languages for developers and system administrators to understand. Whether you’re managing server environments, building web applications, or diving into enterprise development, knowing how to write Java programs is crucial for your technical toolkit. This guide will walk you through creating your first Java program, covering everything from setup and compilation to running your code and troubleshooting common issues that trip up beginners.

How Java Works: Understanding the Technical Foundation

Java operates on a “write once, run anywhere” principle through its unique compilation and execution model. When you write Java code, it gets compiled into bytecode rather than native machine code. This bytecode runs on the Java Virtual Machine (JVM), which handles the translation to platform-specific instructions.

The process flows like this: Java source code (.java files) → Java compiler (javac) → Bytecode (.class files) → JVM → Platform-specific execution. This architecture makes Java particularly valuable for server environments where you might deploy the same application across different operating systems.

The JVM also provides automatic memory management through garbage collection, which is why Java remains popular for long-running server applications. Unlike languages like C++ where you manually manage memory, Java handles allocation and deallocation automatically, reducing memory leaks that can crash server processes.

Setting Up Your Java Development Environment

Before writing your first program, you need the Java Development Kit (JDK) installed. The JDK includes the compiler (javac), runtime environment (JRE), and essential development tools.

For Linux-based systems (common in server environments), install OpenJDK:

# Ubuntu/Debian
sudo apt update
sudo apt install openjdk-11-jdk

# CentOS/RHEL
sudo yum install java-11-openjdk-devel

# Verify installation
java -version
javac -version

For Windows or macOS development environments, download the JDK from the official Oracle website or use OpenJDK distributions.

Set up your JAVA_HOME environment variable, which many server applications and build tools require:

# Linux/macOS - add to ~/.bashrc or ~/.zshrc
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export PATH=$PATH:$JAVA_HOME/bin

# Windows
set JAVA_HOME=C:\Program Files\Java\jdk-11.0.x
set PATH=%PATH%;%JAVA_HOME%\bin

Writing Your First Java Program

Let’s create a classic “Hello World” program, but we’ll make it more practical by including command-line arguments and basic error handling that you’d see in real server applications.

Create a file named HelloWorld.java:

public class HelloWorld {
    public static void main(String[] args) {
        // Check if command line arguments were provided
        if (args.length > 0) {
            System.out.println("Hello, " + args[0] + "!");
            System.out.println("Program executed with " + args.length + " arguments");
        } else {
            System.out.println("Hello, World!");
            System.out.println("Try running with: java HelloWorld YourName");
        }
        
        // Display system information (useful for server diagnostics)
        System.out.println("Java version: " + System.getProperty("java.version"));
        System.out.println("Operating System: " + System.getProperty("os.name"));
        System.out.println("Available processors: " + Runtime.getRuntime().availableProcessors());
        System.out.println("Max memory: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + " MB");
    }
}

Key points about this code structure:

  • Class name must match the filename exactly (case-sensitive)
  • The public static void main(String[] args) method is the entry point
  • Command-line arguments come through the args array
  • System.out.println() sends output to standard output (stdout)
  • System.getProperty() accesses JVM and system information

Compiling and Running Your Program

Java requires a two-step process: compilation and execution. Navigate to your source file directory and run these commands:

# Compile the Java source code
javac HelloWorld.java

# This creates HelloWorld.class file
ls -la *.class

# Run the compiled program
java HelloWorld

# Run with command-line arguments
java HelloWorld "Server Admin"

The compilation step catches syntax errors and type mismatches before runtime. If compilation fails, you’ll see error messages with line numbers pointing to issues in your code.

Common compilation flags you’ll use in server environments:

# Compile with specific Java version compatibility
javac -source 11 -target 11 HelloWorld.java

# Include external libraries (classpath)
javac -cp "/path/to/libraries/*" HelloWorld.java

# Enable all warnings
javac -Xlint:all HelloWorld.java

Real-World Example: Server Status Checker

Let’s build something more practical – a simple server status checker that demonstrates file I/O, exception handling, and network operations:

import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ServerStatusChecker {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java ServerStatusChecker  ");
            System.exit(1);
        }
        
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        
        checkServerStatus(hostname, port);
        logStatus(hostname, port, isServerReachable(hostname, port));
    }
    
    public static boolean isServerReachable(String hostname, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(hostname, port), 5000);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    
    public static void checkServerStatus(String hostname, int port) {
        System.out.println("Checking server status...");
        System.out.println("Target: " + hostname + ":" + port);
        
        long startTime = System.currentTimeMillis();
        boolean isReachable = isServerReachable(hostname, port);
        long responseTime = System.currentTimeMillis() - startTime;
        
        if (isReachable) {
            System.out.println("✓ Server is reachable");
            System.out.println("Response time: " + responseTime + "ms");
        } else {
            System.out.println("✗ Server is not reachable");
        }
    }
    
    public static void logStatus(String hostname, int port, boolean status) {
        try (FileWriter writer = new FileWriter("server_status.log", true)) {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            String logEntry = String.format("%s - %s:%d - %s%n", 
                timestamp, hostname, port, status ? "UP" : "DOWN");
            writer.write(logEntry);
            System.out.println("Status logged to server_status.log");
        } catch (IOException e) {
            System.err.println("Failed to write log: " + e.getMessage());
        }
    }
}

This example demonstrates several important Java concepts:

  • Import statements for external packages
  • Exception handling with try-catch blocks
  • Resource management with try-with-resources
  • Network programming basics
  • File I/O operations
  • String formatting and date/time handling

Compile and run this program:

javac ServerStatusChecker.java
java ServerStatusChecker google.com 80
java ServerStatusChecker localhost 22

Java vs Alternative Languages for Server Development

Language Startup Time Memory Usage Development Speed Enterprise Support Best Use Case
Java Slow High Medium Excellent Enterprise applications, long-running services
Python Fast Medium Fast Good Scripting, data processing, rapid prototyping
Go Very Fast Low Fast Growing Microservices, system utilities
C++ Very Fast Low Slow Good High-performance systems, embedded
Node.js Fast Medium Fast Good Web APIs, real-time applications

Java excels in environments where you need reliable, long-running processes with strong typing and extensive library ecosystems. It’s particularly valuable when deploying on robust server infrastructure like dedicated servers where the higher memory usage is acceptable in exchange for stability and performance.

Common Issues and Troubleshooting

Here are the most frequent problems beginners encounter and their solutions:

ClassNotFoundException or NoClassDefFoundError:

# Wrong - running from wrong directory
java src/HelloWorld

# Correct - run from directory containing .class file
cd src
java HelloWorld

javac command not found:

# Check if Java is installed
which java
which javac

# If only java exists, install JDK (not just JRE)
sudo apt install openjdk-11-jdk

Class name doesn’t match filename:

Java is strict about this. If your class is named public class MyProgram, the file must be MyProgram.java exactly.

OutOfMemoryError in server environments:

# Increase heap size when running
java -Xmx2g -Xms1g HelloWorld

# For production servers, tune garbage collection
java -Xmx4g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 MyServerApp

Permission denied errors:

# Make sure files are readable
chmod 644 *.java
chmod 755 .

# For executable JAR files
chmod +x myprogram.jar

Best Practices for Java Development

Following these practices will save you time and prevent issues in production environments:

  • Use meaningful variable names: Instead of String s, use String serverHostname
  • Handle exceptions properly: Don’t catch exceptions and ignore them; log them or handle gracefully
  • Close resources: Always close files, network connections, and database connections
  • Use try-with-resources: Automatically manages resource cleanup
  • Validate input: Check command-line arguments and user input before processing
  • Follow naming conventions: Classes use PascalCase, methods and variables use camelCase

For server deployments on VPS environments, consider these additional practices:

  • Configure logging: Use java.util.logging or frameworks like Logback for production logging
  • Monitor memory usage: Profile your applications to understand memory patterns
  • Use environment variables: Store configuration outside your code for different deployment environments
  • Implement health checks: Build endpoints or utilities to monitor application health

Next Steps and Advanced Topics

Once you’re comfortable with basic Java programs, explore these areas relevant to server development:

  • Build tools: Learn Maven or Gradle for dependency management and project building
  • Web frameworks: Spring Boot for REST APIs and web applications
  • Database connectivity: JDBC for database operations
  • Concurrency: Multithreading for handling multiple requests
  • Testing: JUnit for automated testing
  • Containerization: Docker for packaging Java applications

Java’s extensive ecosystem and mature tooling make it an excellent choice for server-side development. The strong typing system catches many errors at compile time, and the JVM’s optimization capabilities mean your applications will perform well under load. While the initial learning curve might seem steep compared to scripting languages, the investment pays off in maintainable, scalable server applications.

For comprehensive Java documentation and tutorials, refer to the official Oracle Java documentation and the OpenJDK project for open-source implementations.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked