List of most important & commonly asked Java programs in interviews Basic Java Programs - Part 2


1. Program to count vowels, consonants, digits and space

public class Count {

    public static void main(String[] args) {

        String line = "This website is aw3som3.";

        int vowels = 0, consonants = 0, digits = 0, spaces = 0;

        line = line.toLowerCase();

        for(int i = 0; i < line.length(); ++i)

        {

            char ch = line.charAt(i);

            if(ch == 'a' || ch == 'e' || ch == 'i'

                || ch == 'o' || ch == 'u') {

                ++vowels;

            }

            else if((ch >= 'a'&& ch <= 'z')) {

                ++consonants;

            }

            else if( ch >= '0' && ch <= '9')

            {

                ++digits;

            }

            else if (ch ==' ')

            {

                ++spaces;

            }

        }

        System.out.println("Vowels: " + vowels);

        System.out.println("Consonants: " + consonants);

        System.out.println("Digits: " + digits);

        System.out.println("White spaces: " + spaces);

    }

} 

Output :

Vowels : 6
Consonants : 11
Digits : 3
White spaces:  3
 One more

public class Countvowels {

     public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter SOme String :");

        String str = sc.nextLine();

        char[] cha = str.toCharArray();

        int count = 0;

        for (char ch : cha) {

            switch (ch) {

                case 'a':

                case 'e':

                case 'i':

                case 'o':

                case 'u':

                    count++;

                    break;

            }

        }

        System.out.println("Number of Vovels in String " + count);

    }

}


Output :

Enter Some String :

Chaudhari Rahul

Number of Vovels in String 6

2. Count the characters in each word in a given Sentence

public class CountCharacterInEachWords {

      static void count(String str)

    {

        // Create an char array of given String

        char[] ch = str.toCharArray();

        for (int i = 0; i < ch.length; i++) {

              // Declare an String with empty initialization

            String s = "";

              // When the character is not space

            while (i < ch.length && ch[i] != ' ') {

                 // concat with the declared String

                s = s + ch[i];

                i++;

            }

              if (s.length() > 0) 

                System.out.println(s + " : " + s.length());            

        }

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        count(str);

    }

}


Output :
Chaudhari : 9
Rahul : 5
Navinbhai : 9

3. Remove duplicates from a given string

 import java.util.LinkedHashSet;

import java.util.Set;

 public class RemoveDuplicate {

     public static void main(String[] args) {

        String string = "Chaudhari Rahul";

        char[] chars = string.toCharArray();

        Set<Character> charSet = new LinkedHashSet<Character>();

        for (char c : chars) {

            charSet.add(c);

        }

        StringBuilder sb = new StringBuilder();

        for (Character character : charSet) {

            sb.append(character);

        }

        System.out.println(sb.toString());

    }

}

Output :

Chaudri Rl


4. Java program to find second largest number in an array 

public class SecondLargest {

     public static void main(String[] args) {

        int arr[] = {14, 46, 47, 86, 92, 52, 48, 36, 66, 85};

        int largest = arr[0];

        int secondLargest = arr[0];

        System.out.println("The given array is:");

        for (int i = 0; i < arr.length; i++) {

            System.out.print(arr[i] + "\t");

        }

        for (int i = 0; i < arr.length; i++) {

             if (arr[i] > largest) {

                secondLargest = largest;

                largest = arr[i];

             } else if (arr[i] > secondLargest) {

                secondLargest = arr[i];

            }

        }

        System.out.println("\nSecond largest number is:" + secondLargest);

    }

}

Output :

The given array is:

14      46     47     86     92     52     48     36     66     85    

Second largest number is : 86


ONE MORE

public class ThirdLargestNumberInAnArray {

    public static void main(String args[]){

      int temp, size;

      int array[] = {10, 20, 25, 63, 96, 57};

      size = array.length;

 

      for(int i = 0; i<size; i++ ){

         for(int j = i+1; j<size; j++){

 

            if(array[i]>array[j]){

               temp = array[i];

               array[i] = array[j];

               array[j] = temp;

            }

         }

      }

      System.out.println("Third second largest number is:: "+array[size-2]);

   }

}

Output :

Third second largest number is:: 63


5. Swap corner words and reverse middle characters 

import java.util.Scanner;

public class Reversestr {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter String :"); //I Love My India


 

        String str = sc.nextLine();

        String[] s = str.split(" ");

        int n = s.length;

        //swap first nd last

        String s1 = s[0];

        s[0] = s[n - 1];

        s[n - 1] = s1;

        for (String s2 : s) {

            System.out.print(s2 + " "); //India Love My I

        }

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

        //find middle ele

        int l = n / 2;

        String s3 = s[l];

        //reverse middle ele

        String s4 = "";

        int m = str.length();

        for (int i = s3.length() - 1; i >= 0; i--) {

            s4 = s4 + s3.charAt(i);

        }

        s[l] = s4;

        for (String s2 : s) {

            System.out.print(s2 + " "); //India Love yM I

        }

    }

}

Output :

Enter String :

I Love My India

India Love My I

India Love yM I


ONE MORE 

public class ExchangeFirstLastReverseMiddle {

    static void print(String s) {

        // Taking an Empty String

        String fst = "";

        int i = 0;

        for (i = 0; i < s.length();) {

            // Iterating from starting index

            // When we get space, loop terminates

            while (s.charAt(i) != ' ') {

                fst = fst + s.charAt(i);

                i++;

            }

            // After getting one Word

            break;

        }

        // Taking an Empty String

        String last = "";

        int j = 0;

        for (j = s.length() - 1; j >= i;) {

            // Iterating from last index

            // When we get space, loop terminates

            while (s.charAt(j) != ' ') {

                last = s.charAt(j) + last;

                j--;

            }

            // After getting one Word

            break;

        }

        // Printing last word

        System.out.print(last);

        for (int m = j; m >= i; m--) {

            // Reversing the left characters

            System.out.print(s.charAt(m));

        }

        // Printing the first word

        System.out.println(fst);

    }

 

    public static void main(String[] args) {

        String s = "Hello World You";

        print(s);

    }

}

Output :

You dlroW Hello

 

6. Reverse A String In Java


  1.Reverse a String using CharAt Method
>

import java.util.Scanner;

public class StringReverse {

    public static void main(String args[]) {

        String initial, rev = "";

        Scanner in = new Scanner(System.in);

        System.out.println("Enter the string to reverse");

        initial = in.nextLine();

        int length = initial.length();

        for (int i = length - 1; i >= 0; i--) {

            rev = rev + initial.charAt(i);

        }

        System.out.println("Reversed string: " + rev);

    }

}

Output :

Enter the string to reverse

Rahul

Reversed string: luhaR


2. Reverse a String using String Builder / String Buffer Class 

public class StringRev {

// Function to reverse a string in Java using StringBuilder

    public static String rev(String s) {

        return new StringBuilder(s).reverse().toString();

    }

    public static void main(String[] args) {

        String s = "Welcome to My Blog"; // Note that string is immutable in Java

        s = rev(s);

        System.out.println("Result after reversing a string is : " + s);

    }

}

Output :

Result after reversing a string is : golB yM ot emocleW


 3. Reversing a String using Reverse Iteration 

public class StringRev1 {

// Function to reverse a string in Java

    public static String reverseString(String s) {

//Converting the string into a character array

        char c[] = s.toCharArray();

        String reverse = "";

//For loop to reverse a string

        for (int i = c.length - 1; i >= 0; i--) {

            reverse += c[i];

        }

        return reverse;

    }

    public static void main(String[] args) {

        System.out.println(reverseString("Hi All"));

        System.out.println(reverseString("Welcome to My Blog"));

    }

}

Output :

llA iH

golB yM ot emocleW


 4. String Reverse using Recursion

import java.util.Scanner;

public class StringRecursion {

    String rev(String str) {

        if (str.length() == 0) {

            return " ";

        }

        return str.charAt(str.length() - 1) + rev(str.substring(0, str.length() - 1));

    }

    public static void main(String[] args) {

        StringRecursion r = new StringRecursion();

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the string : ");

        String s = sc.nextLine();

        System.out.println("Reversed String: " + r.rev(s));

    }

}

Output :

Enter the string : chaudhari Rahul

Reversed String: luhaR irahduahc 


6. Java Program to Reverse Array In Place


import java.util.Arrays;

public class ArrayReversalDemo {

    public static void main(String[] args) {

        int[] numbers = {1, 2, 3, 4, 5, 6, 7};

        reverse(numbers);

    }

     public static void reverse(int[] input) {

        System.out.println("original array : " + Arrays.toString(input));

        // handling null, empty and one element array

        if (input == null || input.length <= 1) {

            return;

        }

        for (int i = 0; i < input.length / 2; i++) {

            int temp = input[i]; // swap numbers

            input[i] = input[input.length - 1 - i];

            input[input.length - 1 - i] = temp;

        }

        System.out.println("reversed array : " + Arrays.toString(input));

    }

}

Output :

original array : [1, 2, 3, 4, 5, 6, 7]

reversed array : [7, 6, 5, 4, 3, 2, 1]



Post a Comment

0 Comments