View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Code, Compile, and Run Java Projects: A Beginner’s Guide

By Rohan Vats

Updated on Apr 09, 2025 | 9 min read | 11.0k views

Share:

The demand for skilled Java developers continues to grow as businesses worldwide shift towards Java programming to make their programs and software more reliable and efficient. The programming language allows you to create applications across multiple devices, including desktops, servers, and smartphones. Currently, Java ranks 7th among the most commonly used programming languages, with 30.3% of professionals using it regularly. To meet this growing demand, professionals need to learn how to code, compile, and run Java projects.

If you plan to start learning and leveraging this language, the following guide is for you. Here, we’ll go over how to run Java projects effectively to improve execution, optimize performance, and build reliable applications.

1. Setting Up Your Java Development Environment 

Java is among the top programming languages of the future for implementing projects. Anyone who wants to start programming in Java must set up a proper Java development environment. This involves installing the software and configuring the system to support Java development efficiently. Sometimes, you may also consider attending a Java programming tutorial to learn more about the setup process. 

The following section will guide you through the main steps for installing the latest Java Development Kit (JDK) and configuring your environment variables. This also involves selecting Java Integrated Development Environments (IDEs) that meet your professional requirements. You also learn how to Code, Compile, and Run Java Projects after setting up the entire environment. 

Install the Latest Java Development Kit (JDK) 

To start programming in Java, you'll first need to download and install the latest version of the Java Development Kit (JDK). Refer to a JDK in Java tutorial for a clear overview of what the JDK includes, such as the Java Runtime Environment (JRE), development tools, and libraries.

Follow the steps below to install the JDK and begin coding, compiling, and running your Java projects. You can also check a How to Install Java in Windows 10 tutorial for easy, step-by-step help.

  • Download the JDK: Go to the official Oracle JDK download page or the OpenJDK page. Choose the JDK version that suits your operating system, whether Windows, macOS, or Linux. Select the latest stable version of Java (e.g., JDK 11 or JDK 17). Click on the download link for your operating system and accept the license agreement.
  • Install the JDK in Windows:
    • After downloading the .exe installer file, double-click to run it.
    • Choose the destination folder where you want to install the JDK (the default is usually fine).
    • Click “Next” and follow the on-screen instructions to complete the installation.
  • Install the JDK in Mac:
    • Open the .dmg file after downloading it.
    • Drag the JDK package to the Applications folder to install it.
  • Install the JDK in Linux: Open a terminal window and use the following commands:

    sudo apt update
    sudo apt install openjdk-11-jdk
  • Verify Installation: After installation, open the Command Prompt (Windows) or Terminal (macOS/Linux). Type java -version and javac -version. This should display the installed Java version, confirming the successful installation.

Configure Environment Variables 

You need to set up your environment variables after installing the JDK and learning how to code, compile, and run Java projects. This step allows your system to recognize Java commands, like javac and java, globally. Here’s how you can configure the environment variables:

  • Set JAVA_HOME in Windows:
    • Right-click on This PC or My Computer and select Properties.
    • Click on Advanced system settings, then click Environment Variables.
    • In the System Variables section, click New.
    • Set the variable name to JAVA_HOME and the variable value to the path where the JDK is installed (e.g., C:\Program Files\Java\jdk-17).
    • Click OK.
  • Set JAVA_HOME in Mac:
    • Open a terminal and find the JDK path by running:

      /usr/libexec/java_home
    • Open your shell profile file (.bashrc, .zshrc, etc.) and add the following line:

      export JAVA_HOME=$(/usr/libexec/java_home)
    • Save and close the file, then run:

      source ~/.bashrc   # or source ~/.zshrc
  • Update Path Variable in Windows:
    • Go back to System Properties > Environment Variables.
    • In the System variables section, find and select the Path variable, then click Edit.
    • Click New and add the path to the JDK’s bin directory (e.g., C:\Program Files\Java\jdk-17\bin).
    • Click OK to save the changes.
  • Update Path Variable in MacOS.Linux:
    • Open your shell profile file (.bashrc, .zshrc, etc.) and add the following line:

      export PATH=$PATH:$JAVA_HOME/bin
    • Save and close the file, then run:

      source ~/.bashrc   # or source ~/.zshrc
  • Verify Environment Variables:  Open a new terminal/command prompt and type java -version and javac -version to confirm that the environment is correctly set up.

Choose an Integrated Development Environment (IDE) 

An Integrated Development Environment (IDE) plays a key role in writing and managing your Java code efficiently. It provides tools like code completion, debugging, and project management to streamline development.

Here are some popular IDEs for Java and the steps to install them:

  • IntelliJ IDEA: Offers smart code completion, refactoring, powerful debugging tools, built-in Git support, and more.
    • Installation steps:
      • Visit the official IntelliJ IDEA download page.
      • Select your operating system (Windows, macOS, or Linux).
      • Download the Community Edition (free) or Ultimate Edition (paid).
      • Run the installer and follow the on-screen steps for installation.
      • Launch IntelliJ IDEA, and you’ll be ready to start coding in Java.
  • Eclipse: Provides plugin support, cross-platform compatibility, powerful debugging tools, and more. If you need help setting it up, check out a How to Install Eclipse IDE for Java? tutorial for clear steps.
    • Installation Steps:
      • Visit the Eclipse Downloads page.
      • Choose Eclipse IDE for Java Developers and download the installer for your operating system.
      • Run the installer and select the folder where you want to install Eclipse.
      • Follow the on-screen instructions to complete the Java project setup.
      • Launch Eclipse and begin creating Java projects.
  • Visual Studio Code: A lightweight, customizable IDE suitable for developers who prefer minimalism and flexibility. It supports extensions for Java.
    • Installation Steps:
      • Visit the official VS Code download page.
      • Choose your operating system (Windows, macOS, or Linux) and download the installer.
      • Run the installer and follow the instructions to complete the installation.
      • Open VS Code and install the Java Extension Pack from the Extensions view.
      • Once installed, you can easily start coding in Java.

Check out upGrad’s Advanced Certification in DevOps

Read: Java Developer Salary in India

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

2. Writing Your First Java Program 

Once you’ve set up your Java development environment, you can start writing your first Java program. A Java program is a set of instructions written in the Java programming language that directs a computer to perform specific tasks. 

Java tutorial can guide you through creating a basic Java application. Now, let’s go over the core structure and gradually build your first program while understanding how to code, compile, and run Java projects. There are several Java project ideas for beginners to start with, such as creating a simple calculator, a to-do list application, or a basic student management system.

Understand the Java Project Structure 

You should understand how a project is organized before getting started with Java coding best practices. Here’s an overview of some components of a Java project structure:

  1. src (Source Folder): Contains all your Java source files (i.e., files with a .java extension). Each Java class is typically placed in a separate file. Example:
  • HelloWorld.java
  • SumCalculator.java
  1. bin (Binary Folder): Stores compiled .class files, which are generated when you compile your .java files. You don't need to manually create this folder since most IDEs or build tools automatically place compiled files here.
  2. lib (Libraries Folder): Holds external libraries or dependencies if your program uses them.
  3. README.txt: A simple text file that provides a summary or instructions related to the project. It also assists in documenting your code.

Create a New Java Class 

Every Java application starts with a class that contains a main method, which serves as the entry point of the program. Below are the steps to define a new class:

  • Create a New Java File: In your IDE, right-click the src folder and select New > Java Class (or manually create a .java file). Name the file (e.g., HelloWorld).
  • Define the Class: In Java, a class is defined using the class keyword followed by its name. By convention, class names start with an uppercase letter.
  • Add the Main Method: Every Java application starts execution from the main method. This is the entry point of your program. The main method should be defined as:
    • public static void main(String[] args)
  • Write a Basic Statement: Start by printing a simple message to the console inside the main method.

Here’s an example of a simple HelloWorld program:

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

Read More: Java Classes and Objects Tutorial

Implement Core Logic 

This section focuses on taking user input and performing basic operations, such as addition. Here, you will use the Scanner class to interact with the user, allowing you to accept input from the console.

Here’s how you can write a program that takes two numbers from the user and calculates their sum:

  • Import the Scanner class. This class is part of the Java util package and gathers user input.
  • Create a Scanner object: Instantiate the Scanner class to receive input.
  • Perform operations: In this example, two numbers are taken as input, and their sum is calculated.
  • Display the result: Finally, print the sum to the console.

Here is the full code for a simple sum calculator:

import java.util.Scanner; // Importing the Scanner class
public class SumCalculator {
    public static void main(String[] args) {
        // Create a Scanner object to read user input
        Scanner scanner = new Scanner(System.in);
        // Ask the user to input the first number
        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt(); // Read the first number
        // Ask the user to input the second number
        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt(); // Read the second number
        // Perform the addition
        int sum = num1 + num2;
        // Display the result
        System.out.println("Sum: " + sum);
        // Close the scanner to avoid memory leaks
        scanner.close();
    }
}

Want to learn more about writing Java programs? Enroll in upGrad’s free Core Java Basics program

3. Compiling Java Code 

Compiling Java code converts human-readable source code into bytecode that the Java Virtual Machine (JVM) can execute. This step transforms your Java program into a runnable application.

This section covers how to compile your code using the command line, within an IDE and how to address common compilation errors.

Must Read: Exploring Java Architecture: A Guide to Java's Core, JVM and JDK Architecture

Compile Using the Command Line 

To compile Java code using the command line, navigate to the project directory and use the Javac command. Here are the steps:

  1. Open a Terminal/Command Prompt
    • On Windows, open Command Prompt or PowerShell. 
    • On macOS/Linux, open the Terminal.
  2. Navigate to the Project Directory: Use the cd command to navigate to the folder where your .java file is located. 

Here’s an example:

cd path/to/your/project/directory
  1. Compile the Java Code: Once you're in the correct directory, run the javac command followed by the filename of the Java class you want to compile. 

Example:

javac HelloWorld.java
  1. Verify Compilation: After running the javac command, if there are no errors, a compiled .class file (bytecode) will be created in the same directory.

Here’s an example: 

ls

HelloWorld.class

Compile Within an IDE 

Compiling Java code within an IDE simplifies the process by handling much of the complexity for you. Here’s how to compile code using the most popular IDEs:

  • In IntelliJ IDEA: Go to Build > Build Project, then press Ctrl + F9 (Windows/Linux) or Cmd + F9 (macOS) to compile the project.
  • In Eclipse: Go to Project > Build Project or enable Build Automatically. Press Ctrl + B (Windows/Linux) to build the project.
  • In Visual Studio Code: Use Terminal > Run Build Task to compile the code. Press Ctrl + Shift + B (Windows/Linux) or Cmd + Shift + B (macOS) to start the build.

Address Compilation Errors 

Compilation errors are common, especially for beginners. Learning how to troubleshoot and fix them will improve your coding skills. Here are some best practices for resolving compilation errors in Java:

  • Missing Semicolons: One of the most common errors is forgetting to end a statement with a semicolon (;). This triggers a syntax error. The solution is to ensure every statement ends with a semicolon.
  • Incorrect Class Names: Java is case-sensitive, so an incorrect class name will cause a compilation error. Ensure the filename matches the class name and follows Java naming conventions (uppercase for class names).
  • Unresolved References: Errors related to calling undefined methods or variables usually indicate that you’re trying to use something that isn’t declared. Double-check that all variables and methods are properly declared before use.
  • Mismatched Parentheses or Braces: Missing or extra parentheses or braces can confuse the compiler. Carefully check all parentheses () and braces {} to ensure they match.
  • Classpath Issues: If your project includes external libraries, you may encounter errors related to the classpath. Ensure all required libraries are included in your project and referenced correctly in your build path.

To understand the difference between errors and exceptions you can refer to an Error vs. Exception in Java tutorial.

Want to learn more about Java compilations? Pursue upGrad’s AI-powered Full Stack Development course

4. Running Java Applications 

Depending on the development environment and requirements, Java applications can be executed in different ways. Understanding how they execute can improve efficiency and troubleshooting when running them from the command line or within an Integrated Development Environment (IDE).

Execute from the Command Line 

Once a Java program is compiled into bytecode (.class file), it can be executed using the Java Runtime Environment (JRE). The Java command-line compilation method is useful for quick execution, debugging, and automation.

Here are the steps to execute Java programs from the command line:

  1. Compile the Java Program: Use the Javac compiler to compile the Java file into a .class file. For example:

    javac HelloWorld.java
  2. Run the Compiled Bytecode: Use the Java command followed by the class name (without .class).
    For example:

    java HelloWorld
  3. Common Issues & Troubleshooting: Ensure that Java is installed and configured correctly (java -version and javac -version to verify). Check that the classpath is set correctly if dependencies are involved. If you encounter NoClassDefFoundError, ensure that the compiled .class file exists in the correct directory.

Run Within an IDE 

Most developers prefer running Java applications within an Integrated Development Environment (IDE) for enhanced debugging, code completion, and project management. IDEs like IntelliJ IDEA, Eclipse, and NetBeans provide built-in execution and debugging tools.

Here are the steps to run a Java program in an IDE:

  1. Open or Create a Java Project: Use the IDE’s new project wizard to create or open an existing Java project.
  2. Write or Import Code: Write the Java code in the editor or import an existing .java file. You can always learn more about what is coding by enrolling in courses. 
  3. Set Up Run Configurations: Specify the main class to execute. Configure VM arguments if necessary.
  4. Run the Application: Click the Run or Play button in the IDE. Alternatively, use shortcut keys:
    • IntelliJ IDEA: Shift + F10
    • Eclipse: Ctrl + F11
    • NetBeans: F6
  5. Debugging Features: Set breakpoints to inspect code execution. Use Java debugging techniques to monitor variable values in real-time.

Understand the Java Virtual Machine (JVM) 

The Java Virtual Machine (JVM) is an essential component of the Java platform. It executes Java bytecode and manages runtime environments.

Here are the key functions of a JVM:

  • Bytecode Execution: Converts compiled Java bytecode into machine-specific instructions and uses Just-In-Time (JIT) compilation to optimize performance.
  • Memory Management: This handles automatic memory allocation and garbage collection and uses the heap and stack memory structures to manage objects and function calls.
  • Platform Independence: Allows Java programs to run on any device with a compatible JVM, ensuring portability across different operating systems.
  • Security and Exception Handling: Provides a secure execution environment and uses exception handling to manage runtime errors efficiently.

Want to learn how to run Java applications efficiently? Enroll in upGrad’s Professional Certificate Program in Cloud Computing and DevOps now.

5. Managing Larger Java Projects 

Effective project management prevents Java projects from becoming more complex over time. Proper project organization, automation, and version control practices improve scalability, maintainability, and collaboration. This section explores strategies for managing larger Java projects efficiently.

Organize Code into Packages 

Packages in Java organize classes and interfaces in a systematic way, preventing naming conflicts and improving code maintainability.

The benefits of using packages include:

  • Namespace Management: Avoids class name conflicts by grouping related classes.
  • Improved Code Readability: Helps structure the codebase logically.
  • Access Control: Restricts visibility using package-private access modifiers.

Utilize Build Automation Tools 

Java build automation tools streamline compiling, testing, packaging, and deployment processes. The best Java courses help you learn more about these tools that eliminate manual errors and improve efficiency.

Here are some of the most popular Java build automation tools:

  • Apache Ant: Uses XML-based scripts for automation and provides a flexible and extensible build system.
  • Maven: Manages dependencies using a standardized project structure and relies on pom.xml for configuration and lifecycle management.
  • Gradle: Uses Groovy/Kotlin DSL for build scripting and offers incremental builds for better performance in multi-project builds.

Implement Version Control 

Version control tracks code changes, enables collaboration, and manages releases efficiently. Additional benefits include:

  • Code History Tracking: Enables rollback to previous versions.
  • Collaboration: Supports multiple developers working on the same project.
  • Branching and Merging: Facilitates feature development and code reviews.

Here are some of the most popular version control systems: 

  • Git: Works with platforms like GitHub, GitLab, and Bitbucket and supports distributed version control for offline commits.
  • Subversion (SVN): Centralized version control with strict access controls.
  • Mercurial: A simpler alternative to Git, known for ease of use and reliability.

Not sure how to run larger Java projects? Enroll in upGrad’s job-ready Full Stack Developer bootcamp now. 

6. Debugging and Testing 

Debugging and testing are key steps in software development, and they improve code reliability, maintainability, and functionality. Knowing the difference between testing and debugging ensures you apply the right techniques and tools at each stage.

The following points highlight how to code, compile, and run Java projects with debugging and testing:

Use Debugging Tools in IDEs 

Modern IDEs offer powerful debugging tools that help developers identify and fix issues efficiently. Key debugging features include:

  • Breakpoints: Pause code execution at specific points for inspection.
  • Step Execution: Step through code line by line to track variable changes.
  • Variable Inspection: View and modify variable values during runtime.
  • Call Stack Analysis: Trace method calls leading to an issue.

The table below showcases the top debugging features of popular IDEs:

IDE Debugging Features
IntelliJ IDEA
  • Smart breakpoints, variable tracking, and inline debugging
Eclipse
  • Step filtering, thread analysis, and conditional breakpoints
NetBeans
  • Visual debugging and heap analysis

Write Unit Tests 

Unit testing is a key aspect of learning how to code, compile, and run Java projects. It verifies that individual program components function as expected. JUnit is a popular framework for writing and running unit tests in Java. 

Here are the benefits of writing unit tests when running Java projects:

  • Code Reliability: Detects bugs early in the development cycle.
  • Refactoring Confidence: Helps maintain stability when modifying code.
  • Automation: Enables continuous integration (CI) workflows.

Here is an example of a simple JUnit test:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
    @Test
    void testAddition() {
        int sum = 5 + 3;
        assertEquals(8, sum, "Sum calculation should be correct");
    }
}

Handle Exceptions Gracefully 

Proper exception handling ensures that applications run smoothly and provide meaningful error messages when issues arise. Here are some best practices to follow when handling exceptions:

  • Use Specific Exception Types: Catch only relevant exceptions instead of using generic Exception.
  • Provide Informative Messages: Log meaningful error messages for easier debugging.
  • Avoid Empty Catch Blocks: Always handle exceptions properly to prevent silent failures.
  • Use Finally Blocks: Ensure resource cleanup, such as closing file streams.

Here is an example of exception handling in Java:

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed.");
        }
    }
}

Must Read: Comprehensive Guide to Exception Handling in Java: Best Practices and Examples

Want to learn more about Java programming skills? Pursue upGrad’s AI-powered Full Stack Development course

How upGrad Can Help You Master Java?

upGrad offers structured programs to help you develop industry-relevant Java skills. The online platform is known for providing comprehensive courses and expert mentorship. It also helps you learn how to make a successful career in Java. Moreover, upGrad bridges the gap between academic learning and professional success in the following ways:

Industry-Aligned Certification Programs 

upGrad’s certification programs help you meet industry requirements and enhance employability. Their benefits include:

  • Skill Enhancement: Learn core Java concepts, frameworks, and best practices.
  • Hands-on Projects: Gain practical experience by working on real-world applications.
  • Industry Recognition: Certifications add credibility to resumes and boost job prospects.

Mentorship and Networking Opportunities 

upGrad provides access to experienced mentors and a strong alumni network, allowing you to build valuable connections and seek assistance from peers when coding, compiling, and running Java projects.

Key networking benefits include:

  • Guidance from Industry Experts: Receive mentorship from professionals in top tech firms.
  • Peer Networking: Interact with fellow learners, alumni, and hiring managers.
  • Career Growth Support: Learn negotiation skills and job placement strategies.

Career Transition Support 

upGrad helps professionals transition into Java-based roles through extensive career services. These services provide relevant industry expertise and hands-on experience to those who want to learn more about Java projects and their applications across systems.

Here’s a look at how upGrad’s services provide extensive support to professionals: 

  • Resume-Building Workshops: Create compelling resumes that highlight Java expertise.
  • Mock Interviews: Prepare for industry-specific technical and HR interviews.
  • Placement Partnerships: Access job opportunities with leading tech companies.

Wrapping Up 

Following the correct compilation steps and working with class files is necessary when learning how to code, compile, and run Java projects. This involves executing commands in Java and completing a series of steps until the pre-written project runs successfully.

A strong foundation in Java programming is also required to get started. If you’re interested in learning more, consider enrolling in upGrad’s Core Java courses. These programs cover fundamental Java concepts and their application in real-world projects. If you’re unsure which course best suits your professional needs, contact our experts now. 

Explore the following courses from upGrad to enhance your knowledge:

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. What are the OOP concepts in Java?

2. What do you mean by an object in Java?

3. What is meant by garbage collection in Java?

4. Is Java relevant for IT jobs worldwide?

5. Can Java developers transition into roles associated with AI or ML?

6. Is Spring Boot mandatory to learn for Java developers?

7. Compare Java and Python in terms of career opportunities.

8. What skills should I focus on to get a Java developer’s job?

9. Are remote jobs available for Java developers?

10. Is it possible for a Java developer to switch to mobile applications?

11. What is the most distinguished characteristic of Java?

Rohan Vats

408 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad KnowledgeHut

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks