Author: admin

  • Java Program to Find the Second Largest Number in an Array

    This is a tutorial on how to write a java program to display the second largest element in an array.

    Find the second-largest element in an array:

    In the below program, we take the user input for How many elements does a user wants in an array and what are the elements with the help of the Scanner class. And then declare an integer variable named “Highest” and “secondHighest” which are set to zero.

    Now using for loop and if-else if statement, we check for the highest and the second-highest. That is when the 0th index is greater than the largest, we assigned highest to secondHighest and the element at the 0th index to highest. But if the 0th index is larger than the secondHighest then we assigned the 0th index element to secondHighest.

    The for loop iteration will keep repeating until the length of an array (that is the number of elements). After the end of for loop, we display the result for the highest and second-highest by printing it.


    Java Program for the second-highest element in java with output:

    import java.util.Scanner;
    
    public class SecondHighestelements 
    {
      public static void main(String[] args) 
      {
        int num;
        int Highest = 0;
        int secondHighest = 0;
    
        Scanner elem = new Scanner(System.in);
        Scanner sc = new Scanner(System.in);
        
        //Number of elements for an Array
        System.out.println("Enter the number of elements you want:");
        num = elem.nextInt();
        
        int[] arr = new int[num];
         
        //User Input for elements 
        System.out.println("Enter the elements in an array:");
      
        for (int i=0; i < num; i++)
        {
          arr[i] = sc.nextInt();
        }
        
         for (int i = 0; i < arr.length; i++) 
          {
            if (arr[i] > Highest) 
            {
                secondHighest = Highest;
                Highest = arr[i];
            } 
            else if (arr[i] > secondHighest) 
            {
                secondHighest = arr[i];
            }
          }
        
          //Display Result
          System.out.println("\nSecond largest number in an entered Array: " + secondHighest);
          System.out.println("Largest Number in an entered Array: " + Highest);
        }
    }

    The Output of the second largest element in an array in java:

    java

  • Java Program to Count the Number of Words present in a String using HashMap

    Counting words in java using HashMap:

    This program demonstrates the use of HashMap in java to count the number of words.
    First, we take the string from user input using Scanner class and store it in a string “str“. After then, using the java split() function for spaces(” “) we separate the words from spaces to count the words.

    Then we declare the HashMap(which is a part of java’s collection that stores data in (Key, value) pairs). The Key in this program is String and the Value in an Integer. Then we iterate using for loop and inside for loop, we have if-else statement and if HashMap (Hmap) contains a key we add the object to the Hmap. And the count is set to the current position and with the increment by 1. Under Else, the counter is set to 1.

    The for loop will continue until the length of the split() – 1.
    Then we display the count of a number of words stored in an Hmap.


    Java Program to Count the Number of Words present in a String using HashMap.

    import java.util.Scanner;
    import java.util.HashMap;
    
    public class FinalCountWords 
    {
    
     public static void main(String[] args) 
     {
        Scanner in = new Scanner(System.in);
        String str;
    	
        System.out.println("Enter a string: ");
        str= in.nextLine();
       
        String[] splitFn = str.split(" ");
    	
        HashMap<String,Integer> Hmap = new HashMap<String,Integer>();
    	
        for (int i=0; i < splitFn.length-1; i++)
        {
          if (Hmap.containsKey(splitFn[i])) 
          {
    	int count = Hmap.get(splitFn[i]);
    	Hmap.put(splitFn[i], count+1);
          }
          else 
          {
            Hmap.put(splitFn[i], 1);
          }
        }
       System.out.println(Hmap);
     }
    }

    The Output of counting the words using HashMap in java:

    count words using hashmap in java

  • Java Program to find the Square Root of a Number

    This post shows how to find a square root of a number in java. We will learn two methods to find the square root one by an in-built math method called Math.sqrt() and the other by using do-while loop.
    let’s begin.


    1. Program to find square root using Math.sqrt() in java

    This is a simple and easy method we only need to use Math.sqrt() which returns the square root value when an argument of double is passed to it. For positive or negative zero arguments, it returns the same value as that of the argument.

    Program:

    import java.util.Scanner;
    
    public class SquareRootjava
    {
      public static void main(String args[])
      {
        Scanner sc = new Scanner(System.in);
    
        //user input
        System.out.println("Enter the number");
        double number = sc.nextDouble();
    
        //using method to get square root
        double squareRoot = Math.sqrt(number);
    
        //Display
        System.out.print("Square root of " + number + " is " + squareRoot);
      }
    }

    The output for the square root using Math.Sqrt:

    square root

    2. Program to find square root using do-while in java

    This is another method to find the square root without using Math.sqrt() in java. Here we used the so-while loop. We take the user input passed to squareRootResult() method and run the do-while loop. After the calculation, we return the result back and display it as shown in the program below.

    Program:

    import java.util.Scanner;
    public class SquareRoot
    {
    
      public static double squareRootResult(int n)
      {
        double temp;
    
        double returnResult = n / 2;
    
        do {
          temp = returnResult;
          returnResult = (temp + (n / temp)) / 2;
        } while ((temp - returnResult) != 0);
    
        return returnResult;
      }
    
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the number");
        int number = sc.nextInt();
    
        System.out.print("Square root of " + number + " is: " + squareRootResult(number));
        sc.close();
      }
    }

    Output:

    square root

  • Java Program to Remove all White Spaces from a String

    White Space removal program in java:
    In this post, we will learn how to remove white spaces from a string in java. We will learn the two ways to remove white spaces in java.

    First by using in-built methods called replaceAll() and second without the use of in-built methods (for loop).


    1. Java program to remove white spaces in a string using replaceAll().

    This is the easiest method to remove spaces from a string in java. replaceAll() takes in two parameters, one is the string to be replaced and another one is the string to be replaced with.

    In this example, we will take the string from the user input with the help of a scanner class and as a parameter, we pass “\\s” that will be replaced with “”.

    Example Program:

    import java.util.Scanner;
    
    public class WhiteSpaceRemoval
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the string with spaces");
    
        String str1 = sc.nextLine();
    
        //relaceAll()
        String str2 = str1.replaceAll("\\s", "");
    
        System.out.println(str2);
      }
    }

    The output of removing spaces from a string in java:


    2. Java program to remove white spaces in a string using for loop

    This is another method to remove white spaces. Although the above approach is recommended when it comes to creating a real-time application. This is mostly for interview programs asked.

    In this method, we take the user input for string and convert them to character Array(charArray) and check those characters for white spaces by running it into the iteration. for loop will iterate until the length of the entered string.

    Example Program:

    import java.util.Scanner;
    
    public class WhiteSpaceRemoval
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the string with spaces");
        String inputString = sc.nextLine();
    
        char[] charArray = inputString.toCharArray();
    
        String resultString = "";
    
        for (int i = 0; i < charArray.length; i++)
        {
          if ((charArray[i] != ' ') && (charArray[i] != '\t'))
          {
            resultString = resultString + charArray[i];
          }
        }
    
        System.out.println("Result String without spaces: " + stringWithoutSpaces);
    
        sc.close();
      }
    }

    The output of removing spaces from a string in java without replaceAll():


  • Java Program to find the Duplicate Characters in a String

    We write a program to find duplicate characters in a string in java. For example, consider a string “nut cutter“, duplicate characters in it are : u: 2, t : 3.

    Program Approach:

    First, we created a string variable and take the user input for a string to compare with. And initialize a variable num to keep the number of counts. Then we convert the string variable to characters by creating a character array. Then with iteration(for loop), we compare the two characters and if the character of the compared index is matched, then we display that character with the increase of num with each iteration.

    The for loop will continue till the length of the entered string is finished.


    Java program of string to check duplicate characters.

    import java.util.Scanner;
    
    public class FindDuplicateCharacters 
    {
      public static void main(String[] args) 
      {
        String str;
        int num = 0;
        Scanner in = new Scanner(System.in);
      
        //Get input String
        System.out.println("Enter a string: ");
        str = in.nextLine();
         
        /*//if you want to define the string in a program
        //follow the below code and remove above
        String str = new String("simple2code.com");*/
          
          
        char[] chars = str.toCharArray();
          
        System.out.println("Duplicate characters are:");
          
        for (int i=0; i<str.length();i++) 
        {
          for(int j=i+1; j<str.length();j++) 
          {
             if (chars[i] == chars[j]) 
             {
                System.out.println(chars[j]);
                num++;
                break;
              }
          }
         }
       }
    }

    The output of duplicate characters in java

    Enter a string:
    simple2code.com
    Duplicate characters are:
    m
    e
    c
    o


  • Java Program to Remove Duplicates from ArrayList

    In this tutorial, we will learn to write a Java program to remove duplicates from an ArrayList, we will learn to remove duplicate elements by various approaches.

    ArrayList is a collection type used mostly in java. It is the list interface from Java’s collection framework that allows duplicates in its list. It provides insertion order, flexibility in the program, and duplicates in a list.

    We will see two ways to remove duplicates in java ArrayList

    • Using HashSet
    • Using LinkedHashSet

    1. Remove duplicate elements using HashSet in ArrayList in java

    HashSet is one of the methods to remove elements from ArrayList. It does not follow insertion order which is the disadvantage of using it because once the duplicates elements are removed, the elements will not be in an insertion order inside ArrayList.

    Program:

    import java.util.ArrayList;
    import java.util.HashSet;
     
    public class HashSetDuplicates
    {
        public static void main(String[] args)
        {
            //ArrayList
            ArrayList<String> ListwithDuplicates = new ArrayList<String>();
        /*
         Duplicate elements in the following ArrayList
         Rick, Dayrl, Glenn
        */
            ListwithDuplicates.add("Rick");
            ListwithDuplicates.add("Glenn");
            ListwithDuplicates.add("Dayrl");
            ListwithDuplicates.add("Carol");
            ListwithDuplicates.add("Rick");
            ListwithDuplicates.add("Dayrl");
            ListwithDuplicates.add("Maggie");
            ListwithDuplicates.add("Glenn");
     
            //Constructing HashSet
            HashSet<String> set = new HashSet<String>(ListwithDuplicates);
     
            //List with no duplicate elementsusing set
            ArrayList<String> listWithNoDuplicates = new ArrayList<String>(set);
     
            //Display list With No Duplicate Elements in ArrayList
            System.out.println("After removal of Duplicates ");
            System.out.println(listWithNoDuplicates);
        }
    }

    The output of removing duplicate elements using HashSet:

    After removal of Duplicates
    [Rick, Dayrl, Glenn, Carol, Maggie]


    2. Remove duplicate elements using LinkedHashSet in ArrayList in java

    LinkedHashSet is also one of the other methods to remove elements from ArrayList. The advantage of using LinkedHashSet is that it does not allow duplicates and also maintains insertion order. It is the useful property of LinkedHashSet that is used in removing Duplicates elements from ArrayList.

    Program:

    import java.util.ArrayList;
    import java.util.LinkedHashSet;
     
    public class LinkedHashSetDuplicates
    {
        public static void main(String[] args)
        {
            //ArrayList
            ArrayList<String> ListwithDuplicates = new ArrayList<String>();
        /*
         Duplicate elements in the following ArrayList
         Rick, Dayrl, Glenn
        */
            ListwithDuplicates.add("Rick");
            ListwithDuplicates.add("Glenn");
            ListwithDuplicates.add("Dayrl");
            ListwithDuplicates.add("Carol");
            ListwithDuplicates.add("Rick");
            ListwithDuplicates.add("Dayrl");
            ListwithDuplicates.add("Maggie");
            ListwithDuplicates.add("Glenn");
     
            //Constructing HashSet
            LinkedHashSet<String> set = new LinkedHashSet<String>(ListwithDuplicates);
     
            //List with no duplicate elementsusing set
            ArrayList<String> listWithNoDuplicates = new ArrayList<String>(set);
     
            //Display list With No Duplicate Elements in ArrayList
            System.out.println("After removal of Duplicates ");
            System.out.println(listWithNoDuplicates);
        }
    }

    Output:

    After removal of Duplicates
    [Rick, Glenn, Dayrl, Carol, Maggie]


  • Java Program to Check Whether Two Strings are Anagram Or Not

    This article on Anagram Program in java is to check for the two strings for Anagrams.
    Let start by understanding What is Anagram?

    What is Anagram?

    Two strings are said to be in an anagram if they contain the same set of characters but in a different order.

    For example: “Keep – peek”, “School Master – The Classroom”, “Debit Card – Bad Credit” etc.


    Java Program to check whether two Strings are Anagram Or Not

    import java.util.Arrays;
    
    public class Main
    {
      static void isAnagram(String str1, String str2)
      {
        String string1 = str1.replaceAll("\\s", "");
        String string2 = str2.replaceAll("\\s", "");
    
        boolean checkState = true;
    
        if (string1.length() != string2.length())
        {
          checkState = false;
        }
        else
        {
          char[] ArrayStr1 = string1.toLowerCase().toCharArray();
          char[] ArrayStr2 = string2.toLowerCase().toCharArray();
          Arrays.sort(ArrayStr1);
          Arrays.sort(ArrayStr2);
          checkState = Arrays.equals(ArrayStr1, ArrayStr2);
        }
    
        if (checkState)
        {
          System.out.println(string1 + " and " + string2 + " are anagrams");
        }
        else
        {
          System.out.println(string1 + " and " + string2 + " are not anagrams");
        }
      }
    
      public static void main(String[] args)
      {
        isAnagram("Keep", "Peek");
        isAnagram("The Classroom", "School Master");
        isAnagram("Debit Card", "Bad Credit");
        isAnagram("Mate", "Ate");
      }
    }

    The output of Java Program to check whether two Strings are Anagram Or Not

    Keep and Peek are anagrams
    TheClassroom and SchoolMaster are anagrams
    DebitCard and BadCredit are anagrams
    Mate and Ate are not anagrams


  • Java Program to Check whether the Number is Palindrome or not using While loop

    What is a palindrome number?

    A number is said to be a Palindrome number if it remains the same when its digits are reversed or are the same as forward. It is also applied to the word, phrase, or other sequences of symbols.

    For example: 14141, 777, 272 are palindrome numbers as they remain the same even if reversed. If we take the example of ‘mam’ or ‘madam’, these are also palindrome words.


    Java Program to Check whether the Number is Palindrome or not using While loop

    //check the number for Palindrome using while loop(user inputs) in java 
    
     import java.util.Scanner;
    
     public class PalindromeCheck 
     {
       public static void main(String[] args) 
       {
         int n, rev = 0, remainder, originalNumber;
        
         Scanner sc = new Scanner(System.in);
         
         System.out.print("Enter an integer: ");
         n = sc.nextInt();
             
         originalNumber = n;
             
         // reversing 
         while( n!= 0 )
         {
           remainder = n % 10;
           rev = rev  * 10 + remainder;
           n /= 10;
         }
             
         // Displaying
         if (originalNumber == rev )
             System.out.println(originalNumber + " is a palindrome.");
         else
               System.out.println(originalNumber + " is not a palindrome.");
        }
     }

    Output:

    Enter an integer: 1991
    1991 is a palindrome.


  • Java Program to Check the String for Palindrome

    Palindrome: A string is said to be in a Palindrome if it remains the same when its elements are reversed or are the same as forward.

    For example: 14141, 777, 272 are palindrome numbers as they remain the same even if reversed. If we take the example of ‘mam’ or ‘madam’, these are also palindrome words.


    Java program to check String is palindrome or not

     //check for the string Palindrome 
    
     import java.util.Scanner;
    
     public class StringPalindrome
     {
        public static void main(String args[])
        {
          String str1, str2= "";
          Scanner sc = new Scanner(System.in);
          
          System.out.print("Enter the String: ");
          str1 = sc.nextLine();
          
          for(int i = str1.length() - 1; i >= 0; i--)
          {
            str2 += str1.charAt(i);
          }
          
          //equalsIgnoreCase = This method returns true if the argument is not null and 
          //it represents an equivalent String ignoring case, else false
          if(str1.equalsIgnoreCase(str2))
          {
            System.out.println("The entered string is palindrome.");
          }
          else
          {
            System.out.println("The entered  string is not palindrome.");
          }
        }
     }

    Output:

    Enter the String: Madam
    The entered string is palindrome.


    Using StringBuilder’s reverse() function:

    Java program to check String is palindrome or not using the StringBuilder reverse() function. This function takes the string and reversed it or takes each of the elements from backward.

    import java.util.Scanner;
     
    public class Main {
     
     public static void main(String[] args) 
     {
       Scanner scanner = new Scanner(System.in);
       
       System.out.print("Enter the sstring to be check : ");
       String str = scanner.nextLine();
       
       StringBuilder strBdr = new StringBuilder(str);
       
       //reversing       
       strBdr.reverse();
       
       //Display      
       if(str.equals(strBdr.toString()))
       {
         System.out.println("Entered String is palindrome");
       } 
       else 
       {
         System.out.println("Entered String is not palindrome");
       }
     }
    }

    Output:

    Enter the sstring to be check : Madam
    Entered String is palindrome


  • Java Program to check whether the Number is Palindrome or not

    In this tutorial on Java Program to check whether the number is Palindrome or not, we will learn what is palindrome number is and its programming implementation with an explanation.

    What is a palindrome number?

    A number is said to be a Palindrome number if it remains the same when its digits are reversed or are the same as forward. It is also applied to the word, phrase or other sequences of symbols.

    For example: 14141, 777, 272 are palindrome numbers as they remain the same even if reversed. If we take an example of ‘mam’ or ‘madam’, these are also palindrome words.


    Explanation:
    To check the palindrome number we use the logic to create a program. With the help of a while loop and arithmetic operators such as the remainder operator(%) and the division operator(/), we create a java program to check for palindrome numbers.

    First, take the user input and run the while loop until the entered number(n) is not zero. Inside while loop, we take the remainder that returns the remainder in a division of n/10 that is remainder = n % 10;. Then inside rev variable put the following rev = rev * 10 + remainder;. At last, n is divided by 10 and returns the quotient.

    After the end of the while loop, we check if the original number is equal to the reversed number. If true print accordingly as shown in the program.


    Java Program to check whether the number is palindrome or not

     //check the number for palindrome
    
     import java.util.Scanner;
    
     public class PalindromeCheck 
     {
       public static void main(String[] args) 
       {
         int n, rev = 0, remainder, originalNumber;
        
         Scanner sc = new Scanner(System.in);
        
         System.out.print("Enter an integer: ");
         n = sc.nextInt();
            
         originalNumber = n;
            
         // reversing 
         while( n!= 0 )
         {
           remainder = n % 10;
           rev = rev  * 10 + remainder;
           n /= 10;
         }
            
         // Displaying
         if (originalNumber == rev )
            System.out.println(originalNumber + " is a palindrome.");
         else
            System.out.println(originalNumber + " is not a palindrome.");
       }
     }

    Output:

    Enter an integer: 383
    383 is a palindrome.