Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Java Program for Beginners

Last Updated on May 9, 2023 by Prepbytes

Java program examples are the most effective way to practice the Java programming language. This page contains basic Java practice program examples. It is suggested that you use the examples and try them on your own.

What is Java?

Java, a programming language and computing platform, was first introduced by Sun Microsystems in 1995. It has grown from humble beginnings to power a significant portion of today’s digital world by providing a solid foundation for the development of numerous services and applications. Java is still used in the development of cutting-edge goods and digital services for the future.

What is Java used for?

The following are some important Java applications:

  • It is used in the development of Android applications.
  • It enables you to create a wide range of mobile Java applications and enterprise software.
  • Scientific Computing Applications
  • Java Programming on Hardware Devices for Big Data Analytics
  • Server-side technologies such as GlassFish, JBoss, and Apache make use of it.

We’ve talked about the Java programming language so far, and we hope you’ve gotten a good understanding of it. Now, let’s get back to our main topic: simple Java programs for beginners to practice, which will help you get a good understanding of the Java programming language.

Simple Java Programs for Beginners

Interviewers frequently ask about Java programs. oops, array, string, and control statements can all be used to access these programs. Questions about the Fibonacci series, prime numbers, factorial numbers, and palindrome numbers are frequently asked in interviews and tests. Most of the simple Java programs for beginners are provided below. Take a look at the list of Java programs and their logic and solutions.

  1. Write a program to swap two numbers in Java.
    There are two ways to do this -with the third variable and without a third variable.

    public static void swapNumberswithtemp(int a, int b) { //using 3rd variable
    int temp = a;
    a = b;
    b = temp;
    }
    public static void swapNumberswithouttemp(int a, int b) {//without using 3rd variable
    b = b + a;
    a = b - a;
    b = b - a;
    }
    public static void main(String[] args) {
    int a = 10;
    int b = 20;
    swapNumbers(a, b);
    System.out.printf("%d %d", a, b); 
  2. Write a program to print all the elements of Fibonacci series.
    A Fibonacci series is given by Fib(n)=Fib(n-1)+Fib(n-2)

    public static int fibonacci(int number){
        if(number == 1 || number == 2){ //base case
            return 1;
        }
        return fibonacci(number-1) + fibonacci(number -2); 
    }  
    public static void main(String args[]) {
        int number = new Scanner(System.in).nextInt();
        for(int i=1; i<=number; i++){
            System.out.print(fibonacci2(i) +" ");
        }    
    }
  3. Check if a given number is palindrome or not.
    A palindrome is a number which is when reversed give the same number. We find the reverse and check whether it is equal to the given number or not.

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int length = str.length();         
        boolean isPalindrome = true;          
        for(int i = 0; i < length; i++)
        {
            if(str.charAt(i) != str.charAt(length-1-i)) {
                System.out.println("Snot a palindrome.");
                isPalindrome = false;
                break;
            }
        }          
        if(isPalindrome) {
            System.out.println("palindrome.");
        }
    }
  4. Write a program to find whether a number is an Armstrong number or not.
    Armstrong number – Sum of the cubes of its digit is equal to the number itself. E.g – 153

    public static void main(String[] args) 
    {
        int num = Integer.parseInt(args[0]);
        int temp = num;
        int count = 0;
        int sum = 0;
        while(num > 0)   
        {
            num = num / 10;
            count++;
        }
        num = temp;
        while (num > 0)
        {
            int rem = num % 10;
            int val = 1;
            for(int i = 1; i <= count; i++)
            {   
                val = val * rem;
            }
            num = num / 10;
            sum = sum + val;
        }   
        if(temp == sum)
            {
                System.out.println("Armstrong number");
            }
            else
            {
                System.out.println("Not an armstrong number");
            }   
    }
  5. Find the GCD of two numbers in logn time.
    The symbol gcd (a, b) represents the greatest common divisor of two integers, a and b. To determine the gcd of the numbers, we must first list all of their factors and then identify the most common factor among them. As a result, we can say that of the three numbers, 4 has the most in common.

    public static int gcd(int a, int b) {
    while (((a > 0) && (b > 0))) {
      if ((a > b)) {
        a = (a % b);
      } else {
        b = (b % a);
      }
    }
    if ((a == 0)) {
      return b;
    } else {
      return a;
    }
    }  
    public static void main(String[] args) {
    int a = new Scanner(System.in);
    int b = new Scanner(System.in);
    System.out.println(GCD.gcd(a, b));
    }
  6. Write a program to find the sum of n natural numbers
    The formula for the product of n natural numbers is [n(n+1)]/2. Natural numbers are those that begin at 1 and go all the way to infinity. Except for the number 0, natural numbers only contain whole integers.

    summation of i from 1 to n=n*(n+1)/2
    public static void main(String arg[]){
                  int n,sum=0;
                  Scanner sc=new Scanner(System.in);
                    sum = (n*(n+1))/2;
                   System.out.println(sum);                  
                }
  7. Write a program to find the lcm of two numbers.
    The lowest number that may be divided by both numbers is the LCM (Least Common Multiple) of two numbers. LCM of 15 and 20 is 60, for instance, while LCM of 5 and 7 is 35. Finding the union of all the elements contained in both numbers is a straightforward way to solve the problem.

    private static int getGCD(int num1, int num2) {
    while (num2 > 0) {
        int temp = num2;
        num2 = num1 % num2;
        num1 = temp;
    }
    return num1;
    }
    private static int getLCM(int num1, int num2) {
    return num1 * (num2 / getGCD(num1, num2));
    }
  8. Calculate the sum of digits of a given number.
    By adding a number’s digits without considering for place values, we may determine the amount of digits that make up the sum. Therefore, using the number 567 as a starting point, we may compute the digit total as 5 + 6 + 7 = 18.

    public static void main(String args[]){
     long number=-9999,input=-9999;
        try{    
           number=Long.parseLong(System.console().readLine());
           input=number;    
        }catch(NumberFormatException nfe){
           System.exit(1);    
          }
        long remainder=0,total=0;
        while(number > 0){
            remainder=number % 10;
            total+=remainder;
            number=number/10;
         }
        System.out.println(total);
    }
  9. Write a program to reverse a string.
    Reversing the characters in a string is possible using the built-in function reverse() of the StringBuilder or StringBuffer class. By using this technique, the characters are substituted in the opposite order. In Java, the static method with the necessary logic to reverse a string is called reverse.

    public static void main(String args[]) {
        String word = "HelloWorld";
        String reverse = new StringBuffer(word).reverse().toString();
        word = "thisisstring";
        reverse = new StringBuilder(word).reverse().toString();
        System.out.printf(reverse);
    }     
    public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }       
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }      
        return reverse;
    }
  10. Can you find the second highest number in given array?
    Running two loops is a simple way to find the second largest member of an array. The first loop will look for the largest member of the array. The second loop will then search the array for the largest member whose size is less than the first.

    public static void main(String[] args)
    {
        int arr[] = { 1,4,2,3,5};
        int largest = 0;
        int secondLargest = 0;
        for (int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i] + "\t");
        }
        for (int i = 0; i  largest)
            {
                secondLargest = largest;
                largest = arr[i];
            }
            else if (arr[i] > secondLargest)
            {
                secondLargest = arr[i];
            }
        }
        System.out.println(secondLargest);
    }
  11. Find the first repeating element In the array.
    The HashSet data structure is the usual method for locating duplicate entries in an array. If you recall, duplicates are not permitted with the Set abstract data type. This attribute may be used to filter out duplicate items.

    void firstrep(int a[], int n) 
    {
        Set set = new HashSet();
        int firstrepeating = -1;
        for (int i = 0; i < n; i++){            
            if (set.contains(a[i])) {
                majority = i;
            } else {
                set.add(a[i]);
            }
        }        
        System.out.println(a[firstrepeating]);
    }
    public static void main(String[] args) 
    {
        int arr[] = {1, 2, 5, 4, 5, 5, 1, 2};
        int n = arr.length;
        firstrep(arr,n);
    }
  12. Write a program to find two elements in the array whose sum is near to zero.
    Given below is the solution where we use a two pointer approach.

    public static void main (String[] args) 
    {
      int arr[] = {3, 2, -1, 9, -8, 6};
      int size = arr.length;
      int l, r, min_sum, sum, min_l_num, min_r_num;      
      min_l_num = 0;
      min_r_num = 1;
      min_sum = arr[0] + arr[1];      
      for(l = 0; l < size - 1; l++)   {
        for(r = l+1; r  Math.abs(sum))
          {
            min_sum = sum;
            min_l_num = l;
            min_r_num = r;
          }
        }
      }
      System.out.println(arr[min_l_num],arr[min_r_num]);
    }
  13. What is Singleton and write a program to describe it.
    Ans. Singleton class in Java has only one instance in the whole program. We can easily implement a singleton class with thread safe property. We can see the implementation below –

    public class Javasingleton
    {
    private static  volatile Javasingleton  singleinstance;
    private Javasingleton(){}
    public static   Javasingleton  getInstance()
    {
        if (singleinstance ==null )
        {
            synchronized(Javasingleton.class)
            {
                if (singleinstance ==null )
                {
                    singleinstance=new Javasingleton();
                }
            }
        }
        return singleinstance ;
    }
    }
  14. Write a code to print all the first n prime numbers, where n will be given as input.
    The formal definition of a prime number "n" is one that can only be divided by 1 and n. In other words, a number is considered prime if it cannot be divided by any integer between 2 and n-1.

    public static void main(String[] args) {
        int N = 200;
        int k;
        Scanner sc = new Scanner(System.in);
        k = sc.nextInt();
        int i = 0;
        for (int num = 2; num <= N; num++) {
            if (isPrimeNumber(num) && i!=k) {
                System.out.println(num);
                i++;
            }
        }
    }
    public static boolean isPrimeNumber(int num) {
        for (int i = 2; i 0)
          {
            RevNumber=(RevNumber*10)+(n%10);
            n=n/10;
          }
          return  (int) RevNumber;   
        }
  15. Can you write the Bubble Sort Algorithm?
    The idea is to bubble out the greater numbers to the right.

    public void sort(int[] numbers) {
    validateInput(numbers);
    int length = numbers.length;
    boolean swap = true;
    while (swap) {
      swap = false;
      for (int i = 0; i < length - 1; i++) {
        for (int j = 0; j  numbers[j + 1]) {
            swap(numbers, j, j + 1);
            swap = true;
          }
        }
      }
    }
    }
    }
  16. Implement the merge Sort algorithm.
    This is a Divide and conquer algorithm.

    public static void main(String[] args) {
        int[] list = {4,5,2,1,3};
        mergeSort(list, 0, list.length - 1);
    }
    public static void mergeSort(int[] a, int first, int last)
      {
        if(last - first == 0) 
        {
        }
        else if (last - first == 1) 
        {
            if(a[first] > a[last])
            {
                int temp = a[first];
                a[first] = a[last];
                a[last] = temp;
            }
        }
        else    
        {
            int mid = (first + last) / 2;
            mergeSort(a, first, mid);
            mergeSort(a, mid + 1, last);
            merge(a, first, mid, last);
        }
      }
    private static void merge(int[] a, int first, int mid, int last)
      {
        int[] temp = new int[last - first + 1];
        int i = first; int j = mid + 1;
        for(int k = first; k  mid || j > last)
            {
                if(i > mid && j <= last)
                {
                    System.out.println("a[j]: " + a[j]);
                    temp[k - first] = a[j];
                    j++;
                }
                else if(i  last)
                {
                    System.out.println("a[i]: " + a[i]);
                    temp[k - first] = a[i];
                    i++;
                }
                else
                {
                    break;
                }
            }
            else
            {
                if(a[i] < a[j])
                {
                    temp[k - first] = a[i];
                    i++;
                }
                else
                {
                    temp[k - first] = a[j];
                    j++;
                }
            }
        }
        for(int count = 0; count < temp.length; count++)
        {
            a[first + count] = temp[count];
        }
      }
  17. Write a program to get the sum of even and odd numbers in an array.
    Make an array of elements first. Next, define and initialize three variables with the values i evenSum, and oddSum to get the sum; Then, grab each member from the array individually using the "for loop" command.

    public static void main(String[] args) 
    {
        int n, sumeven= 0, sumodd = 0;
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
        {
            a[i] = s.nextInt();
        }
        for(int i = 0; i  0)
    {
    bin[i++] = n%2;
       n = n/2;
    }
    for(int j = i-1;j >= 0;j--)
    {
       System.out.print(bin[j]);
    }
    }
  18. Write a program to add two binary numbers.
    Begin adding from the right side, and when more than one is returned, store the carry for the next numbers.

    public static void main(String[] args)
    {     
    long b1, b2;
    int i = 0, carry = 0;
    int[] sum = new int[10];
    Scanner scanner = new Scanner(System.in);
    b1 = scanner.nextLong();
    b2 = scanner.nextLong();
    while (b1 != 0 || b2 != 0) 
    {
        sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
        carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
        b1 = b1 / 10;
        b2 = b2 / 10;
    }
    if (carry != 0) {
        sum[i++] = carry;
    }
    --i;
    while (i >= 0) {
        System.out.print(sum[i--]);
    }
    System.out.print("\n");  
    }

    Conclusion
    We discussed the must-practice simple Java programs for beginners in this article, as well as a brief introduction to Java. The Java programs for practice that are being discussed in this article are a must for a beginner.

Frequently Asked Questions (FAQs)

Q1. What is the basic program of Java?
Ans. Fibonacci series, prime numbers, factorial numbers, and palindrome numbers are examples of Java basic programs that are frequently asked in interviews and exams.

Q2. What is Java, for example?
Ans. Java is a programming language that focuses on objects. In Java, everything is associated with classes and objects, as well as their attributes and methods.

Q3. Is Java easy for beginners?
Ans. It is also considered to be one of the easiest coding languages to learn. Because many of the processes of this high-level language are automated, you won’t need to do as much research into how everything works as you would with a low-level language.

Q4. What are the two types of Java?
Ans. Java programming language types are classified into two sorts: basic types and reference types. The boolean and numeric types are the primitive types (4.2). The integral types are byte, short, int, long, and char, and the floating-point types are float and double.

Q5. What are 5 uses of Java?
Ans. Here are a few of the most common tasks for which Java is best suited:

  • Building and running mobile applications.
  • Building and scaling cloud applications.
  • Developing chatbots and other marketing tools.
  • Powering enterprise-level web applications.
  • Supporting artificial intelligence (AI) and internet of things (IoT) devices.

You May Also Like to Read

Calculator Program in Java
Java Program to Add Two Numbers
Java Program to Find the Factorial of a Number
Java Program to Check Prime Number
Menu Driven Program in Java
Caesar Cipher Program in Java
Anagram Program in Java
Fizzbuzz Program in Java
Package Program in Java
Java Program to search an element in a Linked List
Java Program to Reverse a Number
Stack Program in Java
Pyramid Program in Java
Multiple Inheritance Program in Java
Matrix Program in Java
Series program in java
Pattern Program in Java
Program to convert ArrayList to LinkedList in Java
Even Odd Program in Java
Number Pattern Program in Java
Binary Search Program in Java
Leap Year Program in Java
String Palindrome Program in Java
Inheritance Program in Java
Linear Search Program in Java
Interface Program in Java
JDBC Program in Java
Method Overloading Program in Java
Applet Program in Java
Constructor Program in Java
Recursion Program in Java
For Loop Program In Java
While Loop Program in Java
If else Program in Java
Java Program to Reverse a linked list
Quick Sort Program in Java
Hello World Program in Java
Star Program in Java
How to Run Java Program?
String Programs in Java
Multithreading Program in Java
Thread Program in JAVA
Switch Case Program in Java
Collection Programs in Java
Linked List Program in Java
Exception Handling Program in Java

One thought on “Java Program for Beginners

Leave a Reply

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