Java Programs for Beginners: Code Examples & Output

Introduction

Java is one of the most widely used programming languages for learning programming concepts and developing real-world software. However, simply reading Java syntax is not enough to become a good programmer. The best way to strengthen your Java skills is to write, run, understand, and modify Java programs regularly.

Simple Definition of a Java Program

A Java program is a set of instructions written in the Java programming language that tells a computer how to perform a particular task. These tasks can be very simple, such as displaying a message or adding two numbers, or more complex.

In this tutorial, we have compiled the most important Java programs from basic programming problems to more advanced problem-solving.

You will start with core fundamentals like variables, operators, control flow, methods, numbers, and pattern logic. From there, you will advance to arrays, strings, object-oriented design, collections, file handling, and algorithmic problem-solving.

Note: All examples in this tutorial are verified and tested against modern LTS releases (JDK 21+) using standard Java clean-code conventions.

Basic Java Programs for Beginners

Here is a curated list of essential Java programs that beginners must practice to build and strengthen core programming fundamentals.

  1. Print Hello World
  2. Display Student Information
  3. Print Student Details Using User Input
  4. Display Employee Details
  5. Update Variables in Java (Employee Profile Example)
  6. Add Two Numbers
  7. Subtract Two Numbers
  8. Multiply Two Numbers
  9. Divide Two Numbers
  10. Swap Two Numbers in Java With and Without a Third Variable
  11. Find Area and Perimeter of a Square

Java Programs Using Operators

  1. Swap Two Numbers Using Bitwise XOR Operator

Best Practices for Writing Java Programs

You should follow these best practices when writing Java programs:

  1. Choose descriptive names: Use meaningful names for variables, classes, and methods. For example, use calculateTotalSalary() instead of vague names such as calc() or x.
  2. Follow Java naming conventions: Use camelCase for variables and methods, PascalCase for classes and interfaces, and UPPER_SNAKE_CASE for constants. Package names are conventionally written in lowercase.
  3. Give methods a clear responsibility: Declare a method to perform one task. This makes the code easier to understand, test, debug, and reuse.
  4. Avoid unnecessary code duplication (DRY principle): If the same logic is repeated in multiple places, consider extracting it into an appropriate reusable method.
  5. Validate input early: When a program accepts user input or data from external sources, validate it before using it in calculations or business logic. This helps prevent invalid data from propagating through the program.
  6. Handle exceptions gracefully: Catch specific exceptions rather than generic exceptions, and avoid empty catch blocks that swallow runtime errors.
  7. Write meaningful code comments: Explain the why behind complex logic rather than stating the obvious what. Self-explanatory, clean code should serve as its own documentation, while inline comments clarify edge cases, business rules, or non-obvious algorithms.

Common Errors While Writing Java Programs

When writing Java programs, beginners frequently encounter compilation and runtime errors because of incorrect syntax, data types, input handling, logic, or runtime conditions. Understanding these common errors helps you identify and fix problems more quickly.

  • Class Name and File Name Mismatch: In Java, a public class must match the source file name exactly, including case sensitivity (e.g., public class Solution must be saved as Solution.java).
  • Missing Semicolons: Forgetting the terminating semicolon (;) at the end of statements causes immediate compilation failure.
  • Incorrect main Method Signature: Beginners sometimes make spelling or syntax mistakes in the main method declaration. The JVM does not locate the application entry point for the program execution.
  • Using Uninitialized Local Variables: Java does not assign default values to local variables inside methods; accessing them before initialization triggers a compiler error.
  • Type Mismatch: Assigning a larger data type (like double) to a smaller type (like int) without explicit casting causes a “lossy conversion” error.
  • Array Index Out of Bounds: Attempting to access an index outside the valid range (0 to array.length – 1) throws a runtime ArrayIndexOutOfBoundsException.
  • Case Sensitivity Mistakes: Java is strictly case-sensitive; naming a variable count and calling it Count or typing system.out.println instead of System.out.println results in unresolved symbols.
  • Using = Instead of == in Conditional Statements: Using a single assignment operator (=) inside an if condition instead of the equality comparison operator (==).
  • InputMismatchException: When reading user input with the Scanner class, the entered value must match the expected data type. For example, calling scanner.nextInt() when a user enters a string (like “hello”) or a decimal (like 12.5) throws an InputMismatchException at runtime.

How to Troubleshoot Java Errors

When you encounter an error in a Java program, follow this systematic debugging process:

  1. Read the error message carefully to understand the type of issue reported by the compiler or JVM.
  2. Determine whether it is a compilation error (syntax), runtime exception (crash), or logic error (wrong output).
  3. Locate the reported line number and check the exact line where the exception or compiler flag occurred.
  4. Inspect the surrounding code to verify scope, missing braces, or previous unclosed statements.
  5. Verify variable types and values to ensure proper data type compatibility and initialization.
  6. Check conditions and loop boundaries.
  7. Test the program with simple input.
  8. Use print statements (System.out.println) or an IDE debugger (breakpoints) to inspect variable states step-by-step.
  9. Test edge cases like empty strings, null values, negative numbers, or maximum/minimum integers.
  10. Fix one problem at a time and run the program again to verify the resolution before making additional changes.

How to Practice Java Programs Systematically

Learning Java programming is not about memorizing hundreds of programs. The goal is to build computational thinking: understanding a problem, designing an algorithm, writing clean code, and debugging edge cases.

You should use the following approach to practice programs in Java effectively.

  • Learn the fundamentals first: Start with basic Java syntax, data types, operators, input/output, and control flow before attempting complex data structures or algorithms.
  • Understand the problem completely: Clearly identify the expected input, output, constraints, requirements, and important edge cases before writing code.
  • Write an algorithm: Create a step-by-step procedure in plain language before writing Java code. This helps you focus on the problem-solving logic rather than Java syntax.
  • Code from scratch: Once you understand the logic, try to implement the solution independently without looking at a reference solution.
  • Debug before checking the solution: If you get stuck, review the underlying concept or trace the program manually instead of copying a ready-made solution.
  • Test with multiple test cases: Test your program using different inputs, including normal values, boundary values, negative numbers, zero, empty input, or null values where applicable.
  • Try different approaches: After solving a problem, attempt to solve it using another suitable approach.
  • Refactor your code: Once the program works correctly, improve its readability, structure, naming, and maintainability.
  • Track your progress: Maintain a GitHub repository or digital notes of the problems you have solved. Review previous programs and solutions to identify concepts that need more practice.
  • Compare solutions after solving the problem: First attempt the problem independently. Then compare your approach with another reliable solution to understand different techniques and identify possible improvements.
  • Keep a record of difficult problems: Maintain a list of problems that you found difficult and revisit them later. This helps identify weak areas and measure your improvement.
DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.