Java Program to find HCF and LCM

In this Java programming tutorial, we are providing java source code to calculate the HCF and LCM of two given numbers entered by the user.

Source Code of Java Program to find HCF and LCM

import java.util.*;
class HCFNLCM {
        public static void main(String Args[]) {
                System.out.println("Enter 2 numbers");
                Scanner sc = new Scanner(System.in);
                int m = sc.nextInt();
                int n = sc.nextInt();
                int h = 1;
                int p = m * n;
                for (int i = 2; i < p; i++) {
                        if ((m % i == 0) && (n % i == 0)) {
                                h = i;
                        }
                }
                int l = p / h;
                System.out.println("HCF=" + h + " and LCM=" + l);

        }
}

Output of Java Program for finding HCF and LCM

Read More...

Java Program to Compare two Strings

The source code of java program to compare the lengths of any two strings entered by the user is given below. In this program, firstly user will be asked to enter the first string and after that he/she will be asked to enter the second string in the program. After that, the below java program code will compare the entered two strings and give the result of comparing of program in the output window.

Source Code of Java Program for Comparing the length of two Strings

import java.util.Scanner;
class CompareStrings
{
   public static void main(String args[])
   {
      String s1, s2;
      Scanner in = new Scanner(System.in);
      System.out.println("Enter the first string");
      s1 = in.nextLine();
      System.out.println("Enter the second string");
      s2 = in.nextLine();
      if ( s1.compareTo(s2) > 0 )
         System.out.println("First string is greater than second.");
      else if ( s1.compareTo(s2) < 0 )
         System.out.println("First string is smaller than second.");
      else
         System.out.println("Both strings are equal.");
   }
}

Output of the Java Program of Comparing the length of Strings

Read More...

Binary Search Java Program

Binary Search is a searching algorithm which takes less time than linear searching, due to the fact that binary search divides the well arranged sorted elements into two parts and then further checks whether the element which need to be searched comes under lower part that is less or comes under upper part. that's why the binary search algorithm executes in O(log N) time.
The source code for binary search program in Java programming language is given below with the output :

Java Program Source Code of Binary Search

import java.util.*;
public class BinarySearch
{
  public static void main(String[] args)
{
       int[] intArray = new int[10];
       int searchValue = 0, index;
       System.out.println("Enter 10 numbers");
       Scanner input = new Scanner(System.in);
       for (int i = 0; i<intArray.length; i++)
       {
               intArray[i] = input.nextInt();
       }
       System.out.print("Enter a number to search for: ");
       searchValue = input.nextInt();
       index = binarySearch(intArray, searchValue);
       if (index != -1)
       {
               System.out.println("Found at index: " + index);
       }
       else
       {
               System.out.println("Not Found");
       }
  }
           static int binarySearch(int[] search, int find)
           {
           int start, end, midPt;
           start = 0;
           end = search.length - 1;
           while (start <= end)
           {
                   midPt = (start + end) / 2;
                   if (search[midPt] == find)
                   {
                           return midPt;
                   }
                    else if (search[midPt] < find)
                    {
                           start = midPt + 1;
                    }
                   else
                    {
                           end = midPt - 1;
                    }
           }
                    return -1;
           }
}

Output of Java Program Source Code of Binary Searching

Read More...

Linear Searching Java Program

Linear searching is a technique for searching any elements by comparing all the elements of array, until that particular element is found.
In below Java programming tutorial, I have given the source code with output for Linear searching technique.

Java Program Source code of Linear Search

import java.util.Scanner;

class LinearSearch
{
  public static void main(String args[])
  {
    int c, n, search, array[];

    Scanner in = new Scanner(System.in);
    System.out.printf("Enter number of elements:");
    n = in.nextInt();
    array = new int[n];

    System.out.println("Enter " + n + " integers :");

    for (c = 0; c < n; c++)
      array[c] = in.nextInt();

    System.out.printf("Enter value to find:");
    search = in.nextInt();

    for (c = 0; c < n; c++)
    {
      if (array[c] == search)     // Searching element is present
      {
         System.out.println(search + " is present at location " + (c + 1) + ".");
          break;
      }
   }
   if (c == n)  // Searching element is absent
      System.out.println(search + " is not present in array.");
  }
}

Output of Linear Searching Java Program

Read More...

Java Program to Find SubStrings in a String

This Java program is to find out and display the sub strings from any  strings which the user enters in the program. The source code in Java programming language of finding the substrings from a given string is given below :

Java Program Source Code to Find Sub string

import java.util.Scanner;

class SubstringsOfAString
{
   public static void main(String args[])
   {
      String string, sub;
      int i, c, length;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter a string to print it's all substrings");
      string  = in.nextLine();

      length = string.length();

      System.out.println("Substrings of \""+string+"\" are :-");

      for( c = 0 ; c < length ; c++ )
      {
         for( i = 1 ; i <= length - c ; i++ )
         {
            sub = string.substring(c, c+i);
            System.out.println(sub);
         }
      }
   }
}

Output of Java Program for finding Sub Strings

Read More...

Java Program to Reverse a String

In the below JAVA programming tutorial, we will make a Java program to reverse any string entered by the user. For example, if user has entered "xyz" in the program, then it will produce an output of "zyx" after reversing the string. In this Java program, we will use charAt() function to reverse the given string.

Java Program Code to Reverse any String

import java.util.*;

class ReverseString
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);

      System.out.println("Enter a string to reverse");
      original = in.nextLine();

      int length = original.length();

      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);

      System.out.println("Reverse of entered string is: "+reverse);
   }
}

Output of Java Program for reversing any given String

Read More...

Java Program to Calculate Area of Circle

In this Java programming tutorial, we will make a Java program to calculate the area of a circle, if any users enters the radius of that circle. It is a very simple and basic Java problem, in which we will take radius as a input from the user and after that just simply apply the mathematical formula to calculate radius in the program code, which is  π * r² that is pi times the square of the radius of circle.

Java Program to Calculate Area of Circle

/*
Program to find the area of any circle by Codext
*/
import java.util.Scanner;
 // using Scanner class to get input from user
public class CalculateCircleArea {

        public static void main(String[] args) {

		System.out.println("Enter the radius of circle:");
		Scanner num = new Scanner(System.in);
        int radius = num.nextInt();
        System.out.println("The radius of the circle is " + radius);

        double area = Math.PI * radius * radius;

        System.out.println("Area of a circle is " + area);
        }
}

            /*
            Area of a circle is pi * r * r where r is a radius of a circle.
            */

            // NOTE :We have used Math.PI constant to get value of pi

Output of Java Program for Calculating Area of Circle

In Output firstly, we have compiled the Java program by "javac" command in cmd, after the successful compilation of our source code, we have run it through "java" command, and as you can see in the screen shot of program, here it asks for the radius of the circle, after entering the radius our java program displays the correct area of circle.
Read More...

Java Program for Kruskal's Algorithm


In this Java programming tutorial, we are going to learn how to implement Kruskal's algorithm for finding minimum spanning tree.

Source Code of Java Program for the implementation of Kruskal's Algorithm

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class Kruskal {

   static int path[];
   static int n, m, mincost, i, j;

   public static void main (String args[]) throws Exception {

     InputStreamReader isr;
     isr = new InputStreamReader(System.in);
     BufferedReader in = new BufferedReader(isr);

     // Creating graph of 'n' vertices & 'm' edges
     System.out.print("Enter the number of vertices in the graph: ");
     n = Integer.parseInt(in.readLine());

     System.out.print("Enter the number of edges in the graph: ");
     m = Integer.parseInt(in.readLine());

     path = new int[n+1];

     Edge e[] = new Edge[m];
     Edge t = new Edge();

     for (i=0; i<m; i++) {
       e[i] = new Edge();
       System.out.println("Enter 2 vertices and weight of edge: ");
       System.out.print("First vertex: ");
       e[i].u = Integer.parseInt(in.readLine());
       System.out.print("Second vertex: ");
       e[i].v = Integer.parseInt(in.readLine());
       System.out.print("Weight: ");
       e[i].wt = Integer.parseInt(in.readLine());
     }

     // Sorting the edges in ascending order of weights
     for (i=0; i<=m-1; i++) {
       for (j=0; j<m-i-1; j++) {
         if (e[j].wt > e[j+1].wt) {
           t = e[j];
           e[j] = e[j+1];
           e[j+1] = t;
         }
       }
     }

     // Initializing the path array
     for (i=1; i<=n; i++) {
       path[i] = 0;
     }

     // Counts the number of edges selected in the tree
     i = 0;

     // Counts the number of edges selected or discarded
     j = 0;

     mincost = 0;
     System.out.println();
     while ((i!=n-1) && (j!=m)) {
       System.out.print("Edge ("
       + e[j].u + ", " + e[j].v + ") "
       + "with weight " + e[j].wt + " ");
       if (checkCycle(e[j])) {
         mincost = mincost + e[j].wt;
         i++;
         System.out.println("is selected");
       } else {
         System.out.println("is discarded");
       }
       j++;
     }
     if (i!=n-1) {
       System.out.println("Minimum spanning tree cannot be formed ");
     }

   }

   public static boolean checkCycle(Edge e) {
     int u = e.u, v = e.v;

     while (path[u] > 0)
       u = path[u];

     while (path[v] > 0)
       v = path[v];

     if (u != v) {
       path[u] = v;
       return true;
     }
     return false;
   }

   static class Edge {
     int u, v, wt;
   }
}

What is Kruskal's Algorithm?

Kruskal's Algorithm is an algorithm to find a minimum spanning tree for a connected weighted graph. Kruskal's algorithm finds a safe edge to add to the growing forest by finding, of all the edges that connect any two trees in the forest. 

Output of Java Program for Kruskal's Algorithm

Read More...

Java Program to remove Vowels from a String

Source code of Java Program to remove vowels from a given string

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class RemoveVowels {

   public static void main(String args[]) throws IOException
   {
     BufferedReader in = new BufferedReader
         (new InputStreamReader(System.in));

     System.out.println("Program to remove vowels ");
     System.out.println("from a given string \n");

     System.out.print("Enter a string: ");
     String s = in.readLine();

     System.out.println("\n"+"String with vowels removed: ");
     String r = removeVowels(s);
     System.out.println(r);
   }

   private static String removeVowels(String s)
   {
     String finalString = "";

     for (int i=0; i<s.length(); i++)
     {
       if (!isVowel
           (Character.toLowerCase
               (s.charAt(i))))
       {
         finalString += s.charAt(i);
       }
     }
     return finalString;
   }

   private static boolean isVowel(char c) {

     String vowels = "aeiou";
     for (int i=0; i<5; i++)
     {
       if (c == vowels.charAt(i))
         return true;
     }
     return false;
   }
}

Output of Java Program for removing Vowels from a string

Read More...

Java Program to generate Multiplication Table

In this java programming tutorial,we will learn how to create or generate a multiplication table of any number using command line argument. So, if you want to generate the multiplication table of any number, then just copy this java source code into your editor and compile it after that just run the java program and enter the number in command line whose multiplication table you want to generate as shown in the screenshot below.

Source Code of Java Program to generate the Multiplication Table

/* Program to Display Multiplication Table in Java programming language using command line argument */

class MultiplicationTable{

      public static void main(String args[]){

      int num = Integer.parseInt(args[0]);

      System.out.println("*****MULTIPLICATION TABLE*****");

      for(int i=1;i<=num;i++){

         for(int j=1;j<=num;j++){

            System.out.print(" "+i*j+" ");

         }

         System.out.print("\n");

      }

  }

}

Output of the Multiplication Table generation Java Program

Read More...