Blog

  • Java Program to Copy one Array to another

    In this java program tutorial, we will write a program to copy the array in java. Before that, you may go through the following topic in java.

    We will look at two programs:

    • Using loop
    • Using System.arraycopy()

    Explanation: In this program, we will copy the elements of one array to another and display the copied array. We will iterate the array using one of the lops in java and copy each element at every iteration.

    Array 1  
    1  2  3  4  

    Copied Array
    1  2  3  4

    Deep Copy Array Java

    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr1 = new int[]
        { 10, 20, 30, 40, 50 };
        int arr2[] = new int[arr1.length];
    
        for (int i = 0; i < arr1.length; i++)
          arr2[i] = arr1[i];
    
        System.out.print("Original Array: ");
        for (int i = 0; i < arr1.length; i++)
        {
          System.out.print(arr1[i] + " ");
        }
    
        System.out.print("\nCopied Array: ");
        for (int i = 0; i < arr2.length; i++)
        {
          System.out.print(arr2[i] + " ");
        }
      }
    }

    Output:

    Original Array: 10 20 30 40 50
    Copied Array: 10 20 30 40 50


    Copy Array to another array in java using System.arraycopy()

    Syntax of the arraycopy() method:

    System.arraycopy(Object src, int srcPos, Object dest, int destPos,int length);

    • src: Source of copying array.
    • srcPos: Starting position of the source array.
    • dest: Destination, where the array is to copied.
    • destPos: Position of the destination array.
    • length: Number of elements to be copied.

    Program source:

    import java.util.Arrays;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr1 = new int[]
        { 10, 20, 30, 40, 50 };
        int arr2[] = new int[arr1.length];
    
        System.arraycopy(arr1, 0, arr2, 0, arr1.length);
    
        System.out.println("Original Array = " + Arrays.toString(arr1));
        System.out.println("Copied Array = " + Arrays.toString(arr2));
    
      }
    }

    Output: It will produce the same output as the above program.


  • Perfect Square Program in Java

    In this tutorial, we will write a java program to check if a given number is a perfect square or not. Before that, you should have knowledge of the following topic in Java.

    We will look at two java perfect square programs:

    1. With sqrt() function
    2. Without sqrt() funciton

    Both of the programs below take the number as user input and process it. The first program uses the math function sqrt() to check for perfect square and the second program uses if..else statement to check.

    In this java program, both programs have a user-defined boolean function that returns true or false to the main function.


    Using sqrt() function

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int num;
        boolean result = false;
    
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the number: ");
        num = scan.nextInt();
    
    
        result = isPerfectSquare(num);
    
        // check the returned result
        if (result)
          System.out.println(num + " is a Perfect Square");
        else
          System.out.println(num + " is NOT a Perfect Square");
      }
    
      //user-defined function
      public static boolean isPerfectSquare(int num)
      {
        double root = Math.sqrt(num);
        return (root - Math.floor(root) == 0);
      }
    }

    Output:

    Enter the number: 16
    16 is a Perfect Square


    Java Program to check for Perfect Square without using sqrt

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int num;
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the number: ");
        num = scan.nextInt();
    
        // check the result with condition
        if (isPerfectSquare(num))
          System.out.println(num + " is a Perfect Square");
        else
          System.out.println(num + " is NOT a Perfect Square");
      }
    
     //user-defined function
      public static boolean isPerfectSquare(int num)
      {
        for (int i = 1; i * i <= num; i++)
        {
          if ((num % i == 0) && (num / i == i))
            return true;
        }
    
        return false;
      }
    }

    Output:

    Enter the number: 25
    25 is a Perfect Square

    Enter the number: 21
    21 is NOT a Perfect Square


  • Java Program to Find the Distance between Two Points

    In this tutorial, we will write a program to find the distance between two given points in java. Before that, you should have knowledge of the following topic in Java.

    Distance Formula:

    The distance between two coordinates or points is calculated using the following formula.

    First point: (x1, y1)
    Second point: (x2, y2)
    Distance (MN): √((x2 – x1)2 + (y2 -y1)2)

    Here x1, y1 are the coordinates of the first point and x2, y2 are the coordinates of the second point. These points indicate the x-axis and y-axis values.

    Example:

    First Points: (4, 8)
    Seecond Points: (12, 14)
    Then distance between them √((12-4)2 + (14-8)2) = √(64 + 36) = √(100) = 10


    Java Program to Find the Distance between Two Points

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        Scanner scan = new Scanner(System.in);
    
        int x1, x2, y1, y2, x, y;
        double distance;
    
        System.out.println("Enter first coordinates (x1, y1): ");
        x1 = scan.nextInt();
        y1 = scan.nextInt();
    
        System.out.println("Enter second coordinates (x2, y2): ");
        x2 = scan.nextInt();
        y2 = scan.nextInt();
    
        //calculation
        x = x2 - x1;
        y = y2 - y1;
        distance = Math.sqrt(x * x + y * y);
    
        System.out.println("Distance between the two coordinates: " + distance);
      }
    }

    Output:

    Enter first coordinates (x1, y1):
    5
    3
    Enter second coordinates (x2, y2):
    2
    3
    Distance between the two coordinates: 3.0


  • C Program to Read the First Line From a File

    In this tutorial, we will write a program to read the first line of the file in C. Before that, you should have knowledge on the following topic in C.

    To read from a text file in C, you will need to open a file stream using the fopen() function. And then check if the file exists or not. Then read the file.


    C Programming Read First line of File

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      char c[1000];
      FILE * fptr;
    
      fptr = fopen("test.txt", "r");
    
      if (fptr == NULL)
      {
        printf("Error occured!");
        exit(1);
      }
    
      // read the first line
      fscanf(fptr, "%[^\n]", c);
      printf("First line of the file:\n%s", c);
    
      fclose(fptr);
      return 0;
    }

    Output:

    The file test.txt contains the following information.

    This is simple2code.com.
    This is a programming website to learn programming languages.

    After successful execution of the above program, the following output will be displayed.

    First line of the file:
    This is simple2code.com.


  • Bouncy Number Program in Java

    In his tutorial, we will learn how to write a java program to check bouncy number. Before we code, let us understand what is a bouncy number.

    Bouncy Number

    A number is said to be a bouncy number if the digits of that number are in random order that is not sorted. Example: 121575, 521634, etc.

    In other words, a number that is neither an increasing number nor a decreasing number is called a bouncy number.

    • Increasing number: The number whose current digit is greater than or equal to the previous digit is called an increasing number. Example: 12345, 45678, etc.
    • Decreasing number: The number whose current digit is less than the previous digit is called an decreasing number. Example: 54321, 98765, etc.

    Bouncy Number Program in Java

    import java.util.*;
    
    public class Main
    {
      public static void main(String args[])
      {
        int num;
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the number: ");
        num = scan.nextInt();
    
        //calling function and checking condition
        if (isIncreasing(num) || isDecreasing(num) || num < 101)
          System.out.println(num + " is NOT a Bouncy number");
        else
          System.out.println(num + " is a Bouncy number");
      }
    
      //user-defined function to check for incresing number
      public static boolean isIncreasing(int num)
      {
        String str = Integer.toString(num);
        char digit;
        boolean flag = true;
    
        for (int i = 0; i < str.length() - 1; i++)
        {
          digit = str.charAt(i);
          if (digit > str.charAt(i + 1))
          {
            flag = false;
            break;
          }
        }
    
        return flag;
      }
    
      //user-defined function to check for decreasing number
      public static boolean isDecreasing(int num)
      {
        String str = Integer.toString(num);
        char digit;
        boolean flag = true;
        for (int i = 0; i < str.length() - 1; i++)
        {
          digit = str.charAt(i);
          if (digit < str.charAt(i + 1))
          {
            flag = false;
            break;
          }
        }
    
        return flag;
      }
    }

    Output:

    //Run 1
    Enter the number: 12345
    12345 is NOT a Bouncy number

    //Run2
    Enter the number: 23561
    23561 is a Bouncy number


  • Three Dimensional Array Program in Java

    Let us go through a three dimensional array in java language. Before that, you may go through the following topic in java.

    Three Dimensional (3D) Array program

    3D arrays are the multidimensional array in java. They are quite complicated as they run on three loops. In order to initialize or display the array, we need three loops. The inner loop is for one dimensional array, the second one is for the two dimensions and the outer loop makes the third dimensional array.

    The program below is an example of 3d array in java. We will initialize the 3D array and display the output on the screen.


    Three Dimensional Array Program in Java

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int i, j, k, index_1, index_2, index_3;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the Index 1 for Array: ");
        index_1 = sc.nextInt();
        System.out.print("Enter the Index 2 for Array: ");
        index_2 = sc.nextInt();
        System.out.print("Enter the Index 3 for Array: ");
        index_3 = sc.nextInt();
    
        int arr[][][] = new int[index_1][index_2][index_3];
    
        System.out.print("\nEnter the elements: \n");
        for (i = 0; i < index_1; i++)
        {
          for (j = 0; j < index_2; j++)
          {
            for (k = 0; k < index_3; k++)
            {
              System.out.print("arr[" + i + "][" + j + "][" + k + "]: ");
              arr[i][j][k] = sc.nextInt();
            }
          }
        }
    
        //Display the elements
        System.out.print("\nThe enetered elements are: \n");
        for (i = 0; i < index_1; i++)
        {
          for (j = 0; j < index_2; j++)
          {
            for (k = 0; k < index_3; k++)
              System.out.print("arr[" + i + "][" + j + "][" + k + "]: " + arr[i][j][k] + "\n");
          }
        }
      }
    }

    Output:

    Enter the Index 1 for Array: 2
    Enter the Index 2 for Array: 2
    Enter the Index 3 for Array:

    Enter the elements:
    arr[0][0][0]: 1
    arr[0][0][1]: 2
    arr[0][1][0]: 3
    arr[0][1][1]: 4
    arr[1][0][0]: 5
    arr[1][0][1]: 6
    arr[1][1][0]: 7
    arr[1][1][1]: 8

    The enetered elements are:
    arr[0][0][0]: 1
    arr[0][0][1]: 2
    arr[0][1][0]: 3
    arr[0][1][1]: 4
    arr[1][0][0]: 5
    arr[1][0][1]: 6
    arr[1][1][0]: 7
    arr[1][1][1]: 8


  • Square Number Pattern in Java: 1

    Square Number Pattern in Java: 1

    In this tutorial, we will go through the square number pattern program in java. Before that, you may go through the following topic in java.


    Number Square Pattern Programs in Java

    The programs below take the user input for the number of rows to be displayed in the pattern. We have used a for loop to iterate.

    Pattern 1:

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
    
        for (i = 1; i <= rows; i++)
        {
          for (j = 1; j < i; j++)
            System.out.print("0 ");
    
          System.out.print(i + " ");
    
          for (j = i; j < rows; j++)
            System.out.print("0 ");
    
          System.out.println();
        }
      }
    }

    Output:

    Enter the no. of rows: 5
    1 0 0 0 0
    0 2 0 0 0
    0 0 3 0 0
    0 0 0 4 0
    0 0 0 0 5


  • 2 Different Alphabet Patterns in Java (sideways triangle)

    2 Different Alphabet Patterns in Java (sideways triangle)

    In this tutorial, we will go through two different alphabet pattern programs in java programming. Before that, you may go through the following topic in java.


    2 different Alphabet pattern program in Java

    Both of the programs below take the number of rows as the user input and using for loop it prints the desired output.

    The patterns include the sideways triangle or the pyramid with different alphabet patterns, also the half hourglass patterns containing different patterns.

    Pattern 1:

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
    
        for (i = 0; i <= rows; i++)
        {
          int ch = 65;
          for (j = 0; j <= i; j++)
            System.out.print((char)(ch + j) + " ");
    
          System.out.println();
        }
        for (i = rows; i >= 0; i--)
        {
          int ch = 65;
          for (j = 0; j <= i - 1; j++)
            System.out.print((char)(ch + j) + " ");
    
          System.out.println();
        }
      }
    }

    Output:

    Enter the no. of rows: 5
    A
    A B
    A B C
    A B C D
    A B C D E
    A B C D E F
    A B C D E
    A B C D
    A B C
    A B
    A


    Pattern 2:

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j;
        int character = 65;
        int count = 1;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
    
        for (i = 1; i <= rows / 2 + 1; i++)
        {
          for (j = 1; j <= i; j++)
            System.out.print((char)(character + (count *j) - 1) + " ");
    
          System.out.println();
          count++;
        }
    
        for (i = 1; i <= rows / 2; i++)
        {
          for (j = 1; j <= rows / 2 + 1 - i; j++)
            System.out.print((char)(character + (count *j) - 1) + " ");
    
          System.out.println();
          count++;
        }
      }
    }

    Output:

    Enter the no. of rows: 9
    A
    B D
    C F I
    D H L P
    E J O T Y
    F L R X
    G N U
    H P
    I


  • Alphabet Pattern Programs in Java (Diamond Shape)

    Alphabet Pattern Programs in Java (Diamond Shape)

    In this tutorial, we will go through different alphabet patterns in java. Before that, you may go through the following topic in java.

    Both of the programs below take the user input for the number of rows to be printed for the alphabet pattern in java for the diamond shape.


    Alphabet diamond pattern in java

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j, k;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
    
        System.out.print("Diamond Shape Pattern: \n\n");
        for (i = 0; i <= rows; i++)
        {
          int ch = 65;
          for (j = rows; j >= i; j--)
          {
            System.out.print(" ");
          }
          for (k = 0; k <= i; k++)
          {
            System.out.print((char)(ch + k) + " ");
          }
          System.out.println();
        }
    
        for (i = 0; i <= rows; i++)
        {
          int ch = 65;
          for (j = -1; j <= i; j++)
          {
            System.out.print(" ");
          }
          for (k = 0; k <= (rows - 1) - i; k++)
          {
            System.out.print((char)(ch + k) + " ");
          }
          System.out.println();
        }
      }
    }

    Output:

    Alphabet diamond pattern in java

    Hollow Diamond Alphabet Pattern in java

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j;
        int ch = 65;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
    
        System.out.print("Diamond Shape Pattern: \n\n");
    
        //Upper part of diamond
        for (i = 1; i <= rows; i++)
        {
          for (j = rows; j > i; j--)
            System.out.print(" ");
    
          System.out.print((char) ch++);
    
          for (j = 1; j < (i - 1) *2; j++)
            System.out.print(" ");
    
          if (i == 1)
            System.out.print("\n");
          else
            System.out.print((char) ch++ + "\n");
        }
    
        //lower part of diamond
        ch = 65;
        for (i = rows - 1; i >= 1; i--)
        {
          for (j = rows; j > i; j--)
            System.out.print(" ");
    
          System.out.print((char) ch++);
    
          for (j = 1; j < (i - 1) *2; j++)
            System.out.print(" ");
    
          if (i == 1)
            System.out.print("\n");
          else
            System.out.print((char) ch++ + "\n");
        }
      }
    }

    Output:

    Hollow Diamond Alphabet Pattern in java

  • Java Program to print Hollow Rectangle or Square star patterns

    Java Program to print Hollow Rectangle or Square star patterns

    In this tutorial, we will write a program to display a hollow pattern of stars in java. We will write code for two different shapes patterns. Before that, you may go through the following topic in java.

    Hollow rectangle star pattern in java

    The program takes a user input for the number of rows and columns for the hollow rectangle. Then using two for loops it will print the star rectangular pattern in java.

    Example:

    Inputs:
          Rows: 6
          Columns:10
    Output:
    **********
    *        *
    *        *
    *        *
    *        *
    **********

    Java Program to print Hollow Rectangle Star Pattern.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, columns, i, j;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
        System.out.print("Enter the no. of columns: ");
        columns = sc.nextInt();
    
        System.out.print("Rectangular star Pattern: \n\n");
        for (i = 1; i <= rows; i++)
        {
          for (j = 1; j <= columns; j++)
          {
            if (i == 1 || i == rows || j == 1 || j == columns)
              System.out.print("*");
            else
              System.out.print(" ");
          }
    
          System.out.println();
        }
      }
    }

    Output:

    Hollow rectangle star pattern in java

    Hollow square star pattern in java

    As the square contains only sides and both length and breadth are equal so the program only takes user input for a number of rows and prints the same number of rows and columns.

    Example:

    Inputs:
       Rows: 7
    Output:
    *******
    *     *
    *     *
    *     *
    *     *
    *     *
    *******

    Java program to print hollow square pattern of stars

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int rows, i, j;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the number of rows: ");
        rows = sc.nextInt();
    
        for (i = 1; i <= rows; i++)
        {
          for (j = 1; j <= rows; j++)
          {
            if (i == 1 || i == rows ||
              j == 1 || j == rows)
              System.out.print("*");
            else
              System.out.print(" ");
          }
          System.out.println();
        }
      }
    }

    Output:

    Hollow square star pattern in java