Are you new to Java programming and eager to learn its fundamentals? Understanding through example in java programming is the key to learn java clearly. Whether you’re aiming to build mobile apps or simply want to enhance your coding skills, mastering Java examples is your path to success.
In this article, we will learn Java programming with simple examples that will help you understand complex concepts. From basic syntax to object-oriented principles, each example is designed to build your confidence and understanding. So, Let’s move further into the world of Java programming and discover how these example in Java programming can help you learn in a better way.
What Is Java?
Java is a popular programming language known for its flexibility and reliability. It is used to create everything from mobile apps to large-scale enterprise systems. What makes Java unique is its “write once, run anywhere” principle, meaning code written in Java can run on any device that supports Java without needing to be rewritten. Java is object-oriented, which means it organizes code into reusable components called objects.Â
Beginners find Java appealing because of its simple syntax and extensive libraries that make it easier to write powerful programs. Mastering Java opens doors to a world of software development opportunities. Let us move further and understand it’s syntax with the help of example in Java Programming Language.
Example In Java Programming Language
Understanding Example in Java programming language is like learning from practical implementations. Instead of just reading about how Java works, examples show you exactly how to use its rules and instructions to build programs. Imagine each example as a step-by-step guide that teaches you how to write code to solve different problems. By seeing these example in Java programming, you can better understand how to apply Java’s tools and techniques in your own projects.Â
Below is the list of basic examples that we will cover in this article which will help you to understand java in a better way.
 Example In Java Programming Language |
Java Program to Print an Integer (Entered by the User) |
Java Program to Add Two Integers |
Java Program to Find the Largest Among Three Numbers |
Java Program to Check Leap Year |
Java Program to Check Whether a Number is Positive or Negative |
Java Program to Generate Multiplication Table |
Java Program to Reverse a Number |
Java Program to Make a Simple Calculator |
Java Program to Find The Largest Element of an Array |
Java Code To Create Pyramid and Pattern |
1. Java Program To Print An Integer
In this Java program, we will create a simple program that will ask the user to enter an integer, read that input, and then print it back to the user. Here’s how the program works:
- Asking for Input: The program will display a message asking the user to enter an integer.
- Reading Input: It will then read the integer input provided by the user.
- Printing Output: Finally, the program will display the entered integer back to the user.
import java.util.Scanner;
public class PrintIntegerExample {     public static void main(String[] args) {         // Create a Scanner object to read input from the user         Scanner scanner = new Scanner(System.in);                // Ask the user to enter an integer         System.out.print(“Enter an integer: “);                // Read the integer entered by the user         int number = scanner.nextInt();            // Print the entered integer         System.out.println(“You entered: ” + number);                // Close the scanner to release resources         scanner.close();     } } |
Output-Â
Enter an integer: 55 You entered: 55 |
2. Java Program To Add Two Integers
This Example In Java program, we’ll create a simple program that adds two integers entered by the user. Here’s how the program will work:
- First, we’ll use Java’s `Scanner` class to read input from the user.
- Next, we’ll ask the user to enter the first integer.
- After the user enters the first integer, we’ll repeat the process for the second integer.
- We’ll convert these input strings to integers using `Integer.parseInt()`.
- Then, we’ll add these two integers together.
- Finally, we’ll print out the result of the addition.
Example In Java Programming To Add Two Integer |
import java.util.Scanner;
public class AddTwoIntegers {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         //Ask user to enter first integer         System.out.print(“Enter the first integer: “);         int num1 = scanner.nextInt();         //Ask user to enter second integer         System.out.print(“Enter the second integer: “);         int num2 = scanner.nextInt();         // Perform addition         int sum = num1 + num2;         // Display the result         System.out.println(“The sum of ” + num1 + ” and ” + num2 + ” is: ” + sum);            // Close the scanner         scanner.close();     } } |
Output-
Enter the first integer: 30 Enter the second integer: 17 The sum of 30 and 17 is: 47 |
3. Java Program To Find The Largest Among Three Integers
In this Java program, we will determine the largest of three given integers. The program will take three integer inputs from the user and compare them using conditional statements. It will then output the largest integer. The logic involves comparing the first number with the second and third numbers to see if it is the largest. If it’s not, we then compare the second number with the third to determine the largest among the three.
Example In Java Programming To Find The Largest Among Three Integers |
import java.util.Scanner;
public class LargestOfThree {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         // Taking three integer inputs from the user         System.out.println(“Enter the first number: “);         int num1 = scanner.nextInt();         System.out.println(“Enter the second number: “);         int num2 = scanner.nextInt();         System.out.println(“Enter the third number: “);         int num3 = scanner.nextInt();         // Finding the largest number         int largest;         if (num1 >= num2 && num1 >= num3) {             largest = num1;         } else if (num2 >= num1 && num2 >= num3) {             largest = num2;         } else {             largest = num3;         }         // Displaying the largest number         System.out.println(“The largest number is: ” + largest);     } } |
Output-
Enter the first number: 5 Enter the second number: 8 Enter the third number: 3 The largest number is: 8 |
4. Java Program To Check Leap Year
In this program, we will create a Java application to check whether a given year is a leap year or not. A leap year is a year that is divisible by 4 but not by 100, except if it is also divisible by 400. This means that years like 2000 and 2024 are leap years, but 1900 and 2023 are not. The program will first ask the user to enter a year, and it will then use conditional statements to determine if the year meets the criteria for being a leap year or not. Finally, it will display the result to the user.
Example In Java Programming To Check Leap Year |
import java.util.Scanner;
public class LeapYearChecker {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);          // Taking year input from the user        System.out.print(“Enter a year: “);         int year = scanner.nextInt();         boolean isLeapYear;         if (year % 4 == 0) {             if (year % 100 == 0) {                 if (year % 400 == 0) {                     isLeapYear = true;                 } else {                     isLeapYear = false;                 }             } else {                 isLeapYear = true;             }         } else {             isLeapYear = false;         }         if (isLeapYear) {             System.out.println(year + ” is a leap year.”);         } else {             System.out.println(year + ” is not a leap year.”);         }         scanner.close();     } } |
Output-
Enter a year: 2024 2024 is a leap year. Enter a year: 2023 2023 is not a leap year. Enter a year: 2000 2000 is a leap year. Enter a year: 1900 1900 is not a leap year. |
5. Java Program to Check Whether a Number is Positive or Negative
In this Java program, we will check whether a given number is positive or negative. The program takes an input number from the user and uses a simple conditional statement to determine its nature. If the number is greater than zero, it is classified as positive. If it is less than zero, it is classified as negative. For a value of zero, the program can classify it as neither positive nor negative.
Example In Java Programming To Check Whether Number Is Positive Or Negative |
import java.util.Scanner;
public class PositiveNegativeCheck { Â Â Â Â public static void main(String[] args) { Â Â Â Â Â Â Â Â Scanner scanner = new Scanner(System.in); Â Â Â Â Â Â Â Â System.out.print(“Enter a number: “); Â Â Â Â Â Â Â Â double number = scanner.nextDouble();Â Â Â Â Â Â Â Â Â Â Â Â if (number > 0) { Â Â Â Â Â Â Â Â Â Â Â Â System.out.println(“The number is positive.”); Â Â Â Â Â Â Â Â } else if (number < 0) { Â Â Â Â Â Â Â Â Â Â Â Â System.out.println(“The number is negative.”); Â Â Â Â Â Â Â Â } else { Â Â Â Â Â Â Â Â Â Â Â Â System.out.println(“The number is zero.”); Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â scanner.close(); Â Â Â Â } } |
Output-Â
Enter a Number: 8 The Number is positive. Enter a Number: -5 The Number is Negative. |
6. Java Program to Generate Multiplication Table
In this Java program, we’ll generate a multiplication table for a specified number. The program will ask the user to enter a number, and then it will display the multiplication table for that number up to 10. For example, if the user inputs 8, the program will print the results of multiplying 8 by each number from 1 to 10. This helps in understanding how loops work in Java and how to perform repetitive tasks efficiently.
Example In Java Programming To Generate Multiplication Table |
import java.util.Scanner;
public class MultiplicationTable { Â Â Â Â public static void main(String[] args) { Â Â Â Â Â Â Â Â Scanner scanner = new Scanner(System.in); Â Â Â Â Â Â Â Â System.out.print(“Enter a number: “); Â Â Â Â Â Â Â Â int number = scanner.nextInt(); Â Â Â Â Â Â Â Â System.out.println(“Multiplication Table for ” + number + “:”); Â Â Â Â Â Â Â Â for (int i = 1; i <= 10; i++) { Â Â Â Â Â Â Â Â Â Â Â Â System.out.println(number + ” x ” + i + ” = ” + (number * i)); Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â scanner.close(); Â Â Â Â } } |
Output-
Enter a number: 8 Multiplication Table for 8: 8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64 8 x 9 = 72 8 x 10 = 80 |
7. Java Program To Reverse A Number
In this Java program, we will reverse a given number. The program takes an input number, breaks it down digit by digit, and reconstructs the number in reverse order. This is achieved by repeatedly extracting the last digit of the number using the modulo operator, constructing it to a new reversed number, and then removing the last digit from the original number. This process continues until the original number is reduced to zero. The result is the original number reversed.
Example In Java Programming To Reverse A Number |
import java.util.Scanner;
public class ReverseNumber { Â Â Â Â public static void main(String[] args) { Â Â Â Â Â Â Â Â Scanner scanner = new Scanner(System.in); Â Â Â Â Â Â Â Â System.out.print(“Enter a number: “); Â Â Â Â Â Â Â Â int number = scanner.nextInt(); Â Â Â Â Â Â Â Â int reversedNumber = 0; Â Â Â Â Â Â Â Â while (number != 0) { Â Â Â Â Â Â Â Â Â Â Â Â int digit = number % 10; Â Â Â Â Â Â Â Â Â Â Â Â reversedNumber = reversedNumber * 10 + digit; Â Â Â Â Â Â Â Â Â Â Â Â number /= 10; Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â System.out.println(“Reversed Number: ” + reversedNumber); Â Â Â Â } } |
Output-
Enter a number: 1234 Reversed Number: 4321 |
8. Java Program To Make A Simple Calculator
In this program, we will create a simple calculator in Java that can perform basic arithmetic operations like addition, subtraction, multiplication, and division. The program will ask the user to enter two numbers and choose an operation. Based on the user’s input, the calculator will perform the selected operation and display the result. This example will help beginners understand how to take user input, use conditional statements to determine the operation, and perform arithmetic calculations in Java.
Example In Java Programming To Make A Simple Calculator |
import java.util.Scanner;
public class SimpleCalculator {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         // Ask user to enter two numbers         System.out.print(“Enter first number: “);         double num1 = scanner.nextDouble();         System.out.print(“Enter second number: “);         double num2 = scanner.nextDouble();         // Ask user to choose an operation         System.out.println(“Choose an operation: +, -, *, /”);         char operation = scanner.next().charAt(0);         double result;         // Perform the chosen operation         switch (operation) {             case ‘+’:                 result = num1 + num2;                 break;             case ‘-‘:                 result = num1 – num2;                 break;             case ‘*’:                 result = num1 * num2;                 break;             case ‘/’:                 // Handle division by zero                 if (num2 != 0) {                     result = num1 / num2;                 } else {                     System.out.println(“Error! Division by zero is not allowed.”);                     return;                 }                 break;             default:                 System.out.println(“Error! Invalid operation.”);                 return;         }         // Display the result         System.out.println(“The result is: ” + result);     } } |
Output-
Enter first number: 10 Enter second number: 5 Choose an operation: +, -, *, / + The result is: 15.0 Enter first number: 10 Enter second number: 0 Choose an operation: +, -, *, / / Error! Division by zero is not allowed. Enter first number: 10 Enter second number: 5 Choose an operation: +, -, *, / % Error! Invalid operation. |
9. Java Program To Find The Largest Element Of An Array
In this program, we’ll write a Java code to find the largest element in an array. The program will first initialize an array with a set of numbers. It will then iterate through the array, comparing each element to find the largest one. We start by assuming the first element is the largest and then compare this with each subsequent element, updating our assumption whenever a larger element is found. By the end of the loop, the program will have identified and printed the largest element in the array.
Example In Java Programming To Find The Largest Element Of An Array |
public class LargestElement {
    public static void main(String[] args) {         // Initialize the array         int[] numbers = {25, 47, 3, 19, 8, 18};         // Assume the first element is the largest         int largest = numbers[0];         // Loop through the array         for (int i = 1; i < numbers.length; i++) {             // Compare current element with the largest so far             if (numbers[i] > largest) {                 largest = numbers[i];             }         }         // Print the largest element         System.out.println(“The largest element in the array is: ” + largest);     } } |
Output-Â
The largest element in the array is: 47 |
10. Java Code To Create Pyramid And Pattern
In this Java program, we will create a pyramid pattern using nested loops. The program will generate a series of rows with increasing numbers of stars (*) to form a pyramid shape. Each row will have a specific number of spaces before the stars to ensure the stars are centered, creating a visually appealing pyramid. By using nested loops, the outer loop will control the number of rows, while the inner loops will manage the spaces and stars for each row.
Example In Java Programming To Create Pyramid Pattern Using * |
public class PyramidPattern {
    public static void main(String[] args) {         int rows = 5; // Number of rows in the pyramid         for (int i = 1; i <= rows; i++) {             // Print spaces             for (int j = i; j < rows; j++) {                 System.out.print(” “);             }             // Print stars             for (int k = 1; k <= (2 * i – 1); k++) {                 System.out.print(“*”);             }             // Move to the next line             System.out.println();         }     } } |
Output-Â
    *    ***   *****  ******* ********* |
Learn Java Programming With PW Skills
Start your journey of learning Java programming with our exclusive PW Skills Java With DSA Course. This course is specially designed by experts after considering all the in-demand topics and making it beginner-friendly. The key features of this course that make it a standout choice among students include- Mentorship from expert industrialists, regular doubt-clearing sessions, daily practice sheets, in-demand course curriculum, placement assistance, PW alumni support, and much more.
So what are you waiting for, visit pwskills.com today and embark on your journey of becoming a professional Java Developer.Â
Example In Java Programming FAQs
What are Examples In Java Programming?
The basic examples in Java programming, that will help you to learn Java efficiently include
Java Program to Print an Integer Entered By User
Java Program to Add Two Integers
Java Program to Find the Largest Among Three Numbers
Java Program to Check Leap Year
Java Program to Check Whether a Number is Positive or Negative
Java Program to Generate Multiplication Table
Java Program to Reverse a Number
Java Program to Make a Simple Calculator
Java Program to Find The Largest Element of an Array
Java Code To Create Pyramid and Pattern
Where can I find basic examples in Java programming?
You can easily find basic examples in Java programming through online tutorials like PW Skills articles, Geeks for Geeks, etc. popular Java books, and online courses on platforms like PW Skills. These resources offer diverse examples to help you grasp Java fundamentals effectively.
What are Java's main features?
Key features of Java include object-oriented, platform independence, security, reliability, and multithreading capabilities.