Sunday, June 21, 2015



Write a java program to reverse a string?
public class ReverseTheString
{
    public static void main(String[] args)
    {
        String str = "MyJava";

        //1. Using StringBuffer Class

        StringBuffer sbf = new StringBuffer(str);

        System.out.println(sbf.reverse());    //Output : avaJyM

        //2. Using iterative method

        char[] strArray = str.toCharArray();

        for (int i = strArray.length - 1; i >= 0; i--)
        {
            System.out.print(strArray[i]);    //Output : avaJyM
        }

        System.out.println();

        //3. Using Recursive Method

        System.out.println(recursiveMethod(str));    //Output : avaJyM
    }

    //Recursive method to reverse string

    static String recursiveMethod(String str)
    {
         if ((null == str) || (str.length() <= 1))
         {
                return str;
         }

         return recursiveMethod(str.substring(1)) + str.charAt(0);
    }
}
Write a java program to remove all white spaces from a string.? –

class RemoveWhiteSpaces
{
    public static void main(String[] args)
    {
        String str = "  Core Java jsp servlets             jdbc struts hibernate spring  ";

        //1. Using replaceAll() Method

        String strWithoutSpace = str.replaceAll("\\s", "");

        System.out.println(strWithoutSpace);         //Output : CoreJavajspservletsjdbcstrutshibernatespring

        //2. Without Using replaceAll() Method

        char[] strArray = str.toCharArray();

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < strArray.length; i++)
        {
            if( (strArray[i] != ' ') && (strArray[i] != '\t') )
            {
                sb.append(strArray[i]);
            }
        }

        System.out.println(sb);           //Output : CoreJavajspservletsjdbcstrutshibernatespring
    }
}
3) Write a java program to find the duplicate words and their number of occurrences in a string?
class CountDuplicateWords
{
    public static void main(String[] args)
    {
        System.out.println("Enter the string");

        Scanner sc = new Scanner(System.in);

        String s=sc.nextLine();

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

        HashMap<String, Integer> wordDuplicateCount = new HashMap<String, Integer>();

        int count;

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

            for (int j = 0; j < words.length; j++)
            {
                if(words[i].equalsIgnoreCase(words[j]))
                {
                    count++;
                }
            }

            if(count > 1)
            {
                wordDuplicateCount.put(words[i].toLowerCase(), count);
            }
        }

        System.out.println(wordDuplicateCount);
    }
}

4) Write a java program to count the number of words in a string?
class CountTheWords
{
    public static void main(String[] args)
    {
        System.out.println("Enter the string");

        Scanner sc = new Scanner(System.in);

        String s=sc.nextLine();

        String[] words = s.trim().split(" ");

        System.out.println("Number of words in the string = "+words.length);
    }
}


Or
class CountTheWords
{
    public static void main(String[] args)
    {
        System.out.println("Enter the string");

        Scanner sc = new Scanner(System.in);

        String s=sc.nextLine();

        int count = 1;

        for (int i = 0; i < s.length()-1; i++)
        {
            if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
            {
                count++;
            }
        }

        System.out.println("Number of words in a string = "+count);
    }
}

5) Write a java program to count total number of occurrences of a given character in a string without using any loop?

class CountCharacterOccurence
{
    public static void main(String[] args)
    {
        String s = "Java is java again java again";

        char c = 'a';

        int count = s.length() - s.replace("a", "").length();

        System.out.println("Number of occurances of 'a' in "+s+" = "+count);
    }
}
5) Write a java program to count the number of occurrences of each character in a string?

class CountCharOccurence
{
    public static void main(String[] args)
    {
        String str = "java is java again java again";

        HashMap<Character, Integer> charCount = new HashMap<Character, Integer>();

        int count;

        char[] strArray = str.toCharArray();

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

            for (int j = 0; j < strArray.length; j++)
            {
                if(strArray[i] == strArray[j])
                {
                    count++;
                }
            }

            charCount.put(strArray[i], count);
        }

        System.out.println(charCount);
    }
}
6)Java program to check whether one string is rotation of another string?
public class MainClass
{
    public static void main(String[] args)
    {
        String s1 = "JavaJ2eeStrutsHibernate";

        String s2 = "StrutsHibernateJavaJ2ee";

        //Step 1

        if(s1.length() != s2.length())
        {
            System.out.println("s2 is not rotated version of s1");
        }
        else
        {
            //Step 2

            String s3 = s1 + s1;

            //Step 3

            if(s3.contains(s2))
            {
                System.out.println("s2 is a rotated version of s1");
            }
            else
            {
                System.out.println("s2 is not rotated version of s1");
            }
        }
    }
}
Copying An Array In Java
public class ArraysInJava
{
    public static void main(String[] args)
    {
        int[] a = {12, 21, 0, 5, 7};   //Declaring and initializing an array of ints

        int[] b = a;             //copying array 'a' to array 'b'

        //Printing elements of array 'b'

        for (int i = 0; i < b.length; i++)
        {
            System.out.println(b[i]);
        }

        a[2] = 56;     //Changing value of 3rd element of array 'a'

        System.out.println(b[2]);    //value of 3rd element of array 'b' also changes

        b[4] = 100;     //Changing value of 5th element of array 'b'

        System.out.println(a[4]);     //value of 5th element of array 'a' also changes
    }
}
1)     Copying An Array Using for Loop :
public class ArraysInJava
{
    public static void main(String[] args)
    {
        int[] a = {12, 21, 0, 5, 7};   //Declaring and initializing an array of ints

        int[] b = new int[a.length];             //Declaring and instantiating another array of ints with same length

        for (int i = 0; i < a.length; i++)
        {
            b[i] = a[i];
        }

        //Now changing values of one array will not reflect in another array

        a[2] = 56;       //Changing value of 3rd element in array 'a'

        System.out.println(b[2]);    //value of 3rd element in array 'b' will not change

        b[4] = 100;     //Changing value of 5th element in array 'b'

        System.out.println(a[4]);    //value of 5th element in array 'a' will not change
    }
}                                                                                                                                                          
2) Copying An Array Using copyOf() Method of java.util.Array Class
public class ArraysInJava
{
    public static void main(String[] args)
    {
        int[] a = {12, 21, 0, 5, 7};   //Declaring and initializing an array of ints

        //creating a copy of array 'a' using copyOf() method of java.util.Arrays class

        int[] b = Arrays.copyOf(a, a.length);

        //Printing elements of array 'b'

        for (int i = 0; i < b.length; i++)
        {
            System.out.println(b[i]);
        }

        //Now changing values of one array will not reflect in other array

        a[2] = 56;       //Changing value of 3rd element in array 'a'

        System.out.println(b[2]);    //value of 3rd element in array 'b' will not change

        b[4] = 100;     //Changing value of 5th element in array 'b'

        System.out.println(a[4]);    //value of 5th element in array 'a' will not change
    }
}
3) Copying An Array Using clone() Method :
public class ArraysInJava
{
    public static void main(String[] args)
    {
        int[] a = {12, 21, 0, 5, 7};   //Declaring and initializing an array of ints

        //creating a copy of array 'a' using clone() method

        int[] b = a.clone();

        //Printing elements of array 'b'

        for (int i = 0; i < b.length; i++)
        {
            System.out.println(b[i]);
        }

        //Now changing values of one array will not reflect in other array

        a[2] = 56;       //Changing value of 3rd element in array 'a'

        System.out.println(b[2]);    //value of 3rd element in array 'b' will not change

        b[4] = 100;     //Changing value of 5th element in array 'b'

        System.out.println(a[4]);    //value of 5th element in array 'a' will not change
    }
}
4) Copying An Array Using arraycopy() Method Of System Class : -
public class ArraysInJava
{
    public static void main(String[] args)
    {
        int[] a = {12, 21, 0, 5, 7};   //Declaring and initializing an array of ints

        //Creating an array object of same length as array 'a'

        int[] b = new int[a.length];

        //creating a copy of array 'a' using arraycopy() method of System class

        System.arraycopy(a, 0, b, 0, a.length);

        //Printing elements of array 'b'

        for (int i = 0; i < b.length; i++)
        {
            System.out.println(b[i]);
        }

        //Now changing values of one array will not reflect in other array

        a[2] = 56;       //Changing value of 3rd element in array 'a'

        System.out.println(b[2]);    //value of 3rd element in array 'b' will not change

        b[4] = 100;     //Changing value of 5th element in array 'b'

        System.out.println(a[4]);    //value of 5th element in array 'a' will not change
    }
}
Write a java program to find common elements between two arrays?

OR

Write a java program to find intersection of two arrays?
1) Using Iterative Method
class CommonElements
{
    public static void main(String[] args)
    {
        String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};

        String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};

        HashSet<String> set = new HashSet<String>();

        for (int i = 0; i < s1.length; i++)
        {
            for (int j = 0; j < s2.length; j++)
            {
                if(s1[i].equals(s2[j]))
                {
                    set.add(s1[i]);
                }
            }
        }

        System.out.println(set);     //OUTPUT : [THREE, FOUR, FIVE]
    }
}
2) Using retainAll() Method :
class CommonElements
{
    public static void main(String[] args)
    {
        Integer[] i1 = {1, 2, 3, 4, 5, 4};

        Integer[] i2 = {3, 4, 5, 6, 7, 4};

        HashSet<Integer> set1 = new HashSet<>(Arrays.asList(i1));

        HashSet<Integer> set2 = new HashSet<>(Arrays.asList(i2));

        set1.retainAll(set2);

        System.out.println(set1);     //Output : [3, 4, 5]
    }
}
How To Check The Equality Of Two Arrays In Java?
1) Iterative Method :
public class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {  
        int[] arrayOne = {2, 5, 1, 7, 4};
        
        int[] arrayTwo = {2, 5, 1, 7, 4};
        
        boolean equalOrNot = true;
        
        if(arrayOne.length == arrayTwo.length)
        {
            for (int i = 0; i < arrayOne.length; i++)
            {
                if(arrayOne[i] != arrayTwo[i])
                {
                    equalOrNot = false;
                }
            }
        }
        else
        {
            equalOrNot = false;
        }
        
        if (equalOrNot)
        {
            System.out.println("Two Arrays Are Equal");
        }
        else
        {
            System.out.println("Two Arrays Are Not equal");
        }
    }
}
2) Using Arrays.equals() Method :
class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {
        String[] s1 = {"java", "j2ee", "struts", "hibernate"};

        String[] s2 = {"jsp", "spring", "jdbc", "hibernate"};

        String[] s3 = {"java", "j2ee", "struts", "hibernate"};

        System.out.println(Arrays.equals(s1, s2));        //Output : false

        System.out.println(Arrays.equals(s1, s3));      //Output : true
    }
}
class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {
        String[] s1 = {"java", "swings", "j2ee", "struts", "jsp", "hibernate"};

        String[] s2 = {"java", "struts", "j2ee", "hibernate", "swings", "jsp"};

        Arrays.sort(s1);

        Arrays.sort(s2);

        System.out.println(Arrays.equals(s1, s2));       //Output : true
    }
}
3) Using Arrays.deepEquals() Method :
public class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {  
        String[][] s1 = { {"java", "swings", "j2ee" }, { "struts", "jsp", "hibernate"} };

        String[][] s2 = { {"java", "swings", "j2ee" }, { "struts", "jsp", "hibernate"} };

        System.out.println(Arrays.deepEquals(s1, s2));     //Output : true
        
        //Calling equals() method on same arrays will return false
        
        System.out.println(Arrays.equals(s1, s2));        //Output : false
        
        //That's why use deepEquals() method to compare multidimensional arrays
    }
}
Write a java program to find duplicate elements in an array.? –
class DuplicatesInArray
{
    public static void main(String[] args)
    {
        String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz"};

        //1. Using Brute Force Method

        for (int i = 0; i < strArray.length-1; i++)
        {
            for (int j = i+1; j < strArray.length; j++)
            {
                if( (strArray[i].equals(strArray[j])) && (i != j) )
                {
                    System.out.println("Duplicate Element is : "+strArray[i]);
                }
            }
        }

        //2. Using HashSet

        HashSet<String> set = new HashSet<String>();

        for (String arrayElement : strArray)
        {
            if(!set.add(arrayElement))
            {
                System.out.println("Duplicate Element is : "+arrayElement);
            }
        }
    }
}

No comments:

Post a Comment