Home » Learn to code » 10 Simple Java Programs for Beginners: Examples With Outputs

10 Simple Java Programs for Beginners: Examples With Outputs

Java is a versatile language that can be used for all sorts of purposes. Whether you’re creating a simple program to solve a problem or developing an intricate web application, Java has the potential to do the job.

If you’re just starting out with Java, however, it can be tough to know where to begin. That’s why we’ve put together this list of 10 fun and simple Java programs for beginners with examples and outputs.

What should I know about Java as a beginner?

If you’re new to Java, there are a few things you should know before getting started. First and foremost, Java is an object-oriented programming language. This means that it focuses on objects (rather than actions) and the relationships between them.

As a result, Java code can be more complex than code written in other languages. However, this also allows Java to be more flexible and powerful.

In addition, Java is a platform-independent language. This means that code written in Java can run on any platform that supports Java (such as Windows, Mac, or Linux). This is one of the reasons why Java is so popular—it can be used to create applications that can be run on any type of system.

Finally, Java is a statically typed language. This means that every variable must be declared with a specific data type (such as int or String). This can make Java code more verbose than code written in other languages, but it also helps to prevent errors.

How long does it take to learn Java?

How long it takes to learn Java depends on your previous experience with programming. If you’re starting from scratch, it will probably take a few months to get comfortable with the basics of Java.

However, if you already have some experience with another programming language, the learning process will be much faster.

In general, it takes most people about six months to a year to learn Java. To learn more about how long it takes to learn Java and what different stages you have to pass to achieve advanced level of Java expertise, see our article “How Long Does It Take To Learn Java? (And Where To Start)“.

three women sitting on sofa with MacBook programming simple Java programs for beginners with examples
Photo by Christina @ wocintechchat.com

How much should I practice Java as a beginner?

There is no set amount of time that you should spend practicing Java as a beginner. However, it is important to make sure that you are consistently practicing and learning new concepts.

A good rule of thumb is to set aside at least 30 minutes each day to work on coding projects or on reviewing Java concepts. In addition, it is also helpful to find a Java mentor or take a Java course so that you can get guidance and feedback on your progress.

See also  Why Is PHP Considered Bad: Critique and Alternatives

If you want to get proficient fast, you should try to solve at least one Java coding problem every day. This will help you to learn how to apply the concepts you’re learning and to identify areas where you need more practice. You can find our list of simple programs of Java for beginners (along with solutions) below.

10 fun and simple Java programs for beginners

Now that you know a little bit about Java, let’s take a look at some simple programs of Java you can write!

1. Hello, World!

Hello world is the first simple Java program for beginners
Photo by Clay Banks @ Unsplash

The first program any beginner should write is the “Hello, World!” program. This program simply prints the phrase “Hello, World!” to the screen. It’s a simple way to make sure that your Java development environment is set up correctly and that you’re able to write and run Java code.

To write the “Hello, World!” program, open your text editor and type the following:

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

Save the file as HelloWorld.java and compile.

If there are no errors, you should be able to run the program using the Java Virtual Machine.

You should see the output “Hello, World!” on the screen.

Congratulations—you’ve just written your first Java program!

2. FizzBuzz

FizzBuzz is an excellent simple Java program for beginners to write
Photo by yabayee @ Pixabay

FizzBuzz is one of the simple programs of Java that’s often used to teach basic programming concepts. The rules of FizzBuzz are simple:

For numbers 1 through 100,

  • If the number is divisible by 3, print “Fizz”
  • If the number is divisible by 5, print “Buzz”
  • If the number is divisible by both 3 and 5, print “FizzBuzz”
  • Otherwise, print the number

Writing a FizzBuzz program is a great way to practice basic Java syntax. It’s also a good opportunity to learn about the modulo operator (%). This operator returns the remainder of a division operation, which can be used to test whether a number is divisible by another number.

Try writing a FizzBuzz program on your own

Solution:

public class FizzBuzz {


  public static void main(String[] args) {

    for (int i=1; i <= 100; i++) {
      if (i % 3 == 0 && i % 5 == 0) {
        System.out.println("FizzBuzz");
        }
      else if (i % 3 == 0) {
        System.out.println("Fizz");
      }
      else if (i % 5 == 0) {
        System.out.println("Buzz");
      }
      else {
        System.out.println(i);
      }
    }
  }
} 

3. Even or Odd?

a pile of question marks
Photo by qimono @ Pixabay

This is another one of simple programs of Java that’s often used to teach basic Java syntax. The program should ask the user for a number, and then print “Even” if the number is even, or “Odd” if the number is odd.

Solution:

import java.util.Scanner;
public class EvenOrOdd {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter a number:");

  int num = input.nextInt();

  if (num % 2 == 0) {
    System.out.println("Even");
  }
  else {
    System.out.println("Odd");
  }
 }
}

4. Age Calculator Program

A cartoon of an office where a man is presenting to the team
Photo by GraphicMama-team @ Pixabay

This program calculates a person’s age based on their birth year. All you need to do is ask the user for their birth year and then print out their age.

Solution:

import java.util.Scanner;
public class AgeCalculator {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter your birth year:");

  int birthYear = input.nextInt();
  int age = 2022 - birthYear;
  System.out.println("You are " + age + " years old.");
 }
}

5. Temperature Converter Program

thermometer
Photo by Chillsoffear @ Pixabay

This program converts temperatures between Celsius and Fahrenheit. All you need to do is ask the user for a temperature in Celsius or Fahrenheit and then print out the converted temperature.

See also  Is JavaScript Still Used in 2023?

In order to convert Celsius to Fahrenheit, use the following formula:

Fahrenheit = (Celsius * 9/5) + 32

And to convert Fahrenheit to Celsius, use this formula:

Celsius = (Fahrenheit – 32) * 5/9

Solution:

import java.util.Scanner;
public class TemperatureConverter {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter a temperature in Celsius:");

  double celsius = input.nextDouble();
  double fahrenheit = (9 / 5) * celsius + 32;
  System.out.println(celsius + " degrees Celsius is equal to " + fahrenheit + " degrees Fahrenheit.");
 }
}

6. Weight on Mars Program

person walking on Mars
Photo by Nicolas Lobos @ Unsplash

Weight on Mars calculator is one of the fun and simple programs of Java to implement as a beginner. This program calculates a person’s weight on Mars based on their weight on Earth. All you need to do is ask the user for their weight on Earth and then print out their weight on Mars.

In order to convert weight on Earth to weight on Mars, use the coefficient of 0.38. This means that if someone weighs 100 pounds on Earth, they would weigh 38 pounds on Mars.

Solution:

import java.util.Scanner;
public class WeightOnMars {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter your weight on Earth:");
  double weight = input.nextDouble();
  double marsWeight = weight * 0.38;
  System.out.println("Your weight on Mars would be " + marsWeight + " pounds.");
 }
}

7. Distance Between Cities Program

compass
Photo by PublicDomainPictures @ Pixabay

This program calculates the distance between two cities based on their latitude and longitude coordinates. All you need to do is ask the user for the latitude and longitude of two cities and then print out the distance between them.

Use the formula:

Distance = 6371.01 * acos(sin(Lat1)*sin(Lat2) + cos(Lat1)*cos(Lat2)*cos(Lon1-Lon2))

where:

  • Lat1 and Lon1 are the coordinates of the first city
  • Lat2 and Lon2 are the coordinates of the second city
  • 6371.01 is the radius of the Earth in kilometers
  • acos is the inverse cosine function
  • sin and cos are the sine and cosine functions

Solution:

import java.util.Scanner;

public class DistanceBetweenCities {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);

  System.out.println("Enter the latitude of city A:");
  double latA = input.nextDouble();

  System.out.println("Enter the longitude of city A:");
  double lonA = input.nextDouble();

  System.out.println("Enter the latitude of city B:");
  double latB = input.nextDouble();

  System.out.println("Enter the longitude of city B:");
  double lonB = input.nextDouble();

  double distance = 6371.01 * Math.acos(Math.sin(latA) * Math.sin(latB) + Math.cos(latA) * Math.cos(latB) * Math.cos(lonB - lonA));
  System.out.println("The distance between city A and city B is " + distance + " km.");
 }
}

8. Compound Interest Program

compounding interest calculator is a simple Java program
Photo by PublicDomainPictures @ PIxabay

This program calculates the amount of interest earned on an investment over a period of time and is among simpler programs of Java for a starting Java developer. All you need to do is ask the user for the initial investment amount, the interest rate, and the number of years. Then print out the total amount of interest earned. Use Java exponentiation to calculate the compounding interest.

To calculate the total amount of interest earned, use the following formula:

Earned = Principal * (1 + Rate/100)^Years

where:

  • Principal is the initial investment amount
  • Rate is the interest rate
  • Years is the number of years

Solution:

import java.util.Scanner;

public class CompoundInterest {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);

  System.out.println("Enter the initial investment amount:");
  double amount = input.nextDouble();

  System.out.println("Enter the interest rate:");
  double rate = input.nextDouble();

  System.out.println("Enter the number of years:");
  int years = input.nextInt();

  double interest = amount * Math.pow((1 + rate), years);
  System.out.println("The total amount of interest earned would be " + interest + ".");
 }
}

9. Print a Diamond

6 diamonds on a reflective surface
Photo by Edgar Soto @ Unsplash

This program should print a diamond shape to the console. The user should specify the height of the diamond, which will always be an odd number. For example, if the user specifies a height of 5, the output should look like this:

    * 

   *** 

  ***** 

 ******* 

********* 

 ******* 

  ***** 

   *** 

    *

One way to approach this problem is to use nested for loops. The outer loop should iterate over the rows of the diamond, and the inner loop should print the correct number of asterisks for each row.

See also  Is Java a High-Level or Low-Level Programming Language?

Assuming that the user inputs the number of rows in the diamond, we can use the following code to generate the diamond:

for (int i = 0; i < numRows; i++) {
    for (int j = 0; j <= i; j++) {
        System.out.print("*");
    }
    System.out.println();
}
for (int i = numRows - 1; i > 0; i--) {
    for (int j = 0; j < i; j++) {
        System.out.print("*");
    }
    System.out.println();
}

This code will generate a diamond of asterisks with the specified number of rows. Note that we need to print the asterisks in reverse order for the second half of the diamond.

If you want to get really creative, you can use Java’s Unicode characters to generate diamonds made of other symbols.

10. Guess the Number (Binary Search)

cartoon of a man looking through binoculars
Photo by mohamed_hassan @ Pixabay

This program should generate a random number between 1 and 100, and then ask the user to guess the number. If the user’s guess is too high or too low, the program should give them a hint and let them try again. The program should keep track of how many guesses the user has made, and end when the user has guessed the number correctly.

Solution:

import java.util.Scanner;

public class GuessTheNumber {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);

  int numToGuess = (int)(Math.random() * 100) + 1;
  int numGuesses = 0;

  System.out.println("I'm thinking of a number between 1 and 100.");
  System.out.println("Can you guess what it is?");

  while (true) {
     System.out.print("Enter your guess: ");
     int guess = input.nextInt();
     numGuesses++;
     if (guess == numToGuess) {
        System.out.println("You got it! Congratulations!");
        System.out.println("It only took you " + numGuesses + " guesses.");
        break;
     }
     else if (guess < numToGuess) {
        System.out.println("Too low! Guess again.");
     }
     else { // guess > numToGuess
        System.out.println("Too high! Guess again.");
     }
  }
 }
}

Conclusion

Java is a versatile language that can be used for a variety of purposes. These 10 simple programs of Java for beginners are a great way to get started with Java, and you can apply the same principles to create your own programs.

If you are looking for more serious Java projects to put on your resume, check out our article “13 Java Project Ideas For Your Resume and Portfolio“. With a little effort, you’ll be writing Java like a pro in no time!