Skip to main content
Showing 1 - 10 of 30 results

What are Java Access Modifiers/Specifiers and their scope?

An access modifier restricts the access of a class, constructor, data member and method in another class. In java we have four access modifiers:

Access Modifier Same Class Same Package Subclass Other Packages
Public Y Y Y Y
Protected Y Y Y N
Default Y Y N N
Private Y N N N

Java program to find one missing number in an array of 1 to N

You are given an integer array containing 1 to n but one of the number from 1 to n in the array is missing. You need to provide optimum solution to find the missing number. Number can not be repeated in the array. 

For Example 

int[] arr1 = {1, 5, 4, 2}; 3 is missing
int[] arr1 = {7, 5, 4, 1, 2, 3}; 6 is missing

package com.seleniumtest;

public class MissingNumber 
{
    public void findMissingNumber(int[] inputArray)
    {
        //Increment by 1, total number will be one more than array size because 1 number is missing in array
        int n = inputArray.length + 1;
        int sum = n * (n+1) / 2;
        int restSum = 0;
		
        for(int i = 0; i < inputArray.length; i++)
        {
            restSum += inputArray[i];
        }
		
        int missingNumber = sum - restSum;
        System.out.println("Missing Number is:" +missingNumber);
	}

	public static void main(String args[])
	{
		int[] arr = {7, 5, 4, 1, 2, 3};
		
		MissingNumber mn = new MissingNumber();
		mn.findMissingNumber(arr);
	}
}

Difference Between String, StringBuffer and StringBuilder in Java?

String and StringBuffer, StringBuilder are the classes which operate on strings. Below are the differences:

Point of Distinction String StringBuffer StringBuilder
Length Fixed Increased Increased
Mutable  Immutable. if you try to alter their values, another object gets created Mutable. It can change its value Mutable. you can add/remove characters, substring without creating new objects.
Performance Slower Faster Faster
Memory Consumption More Less Less
Storage Constant Pool Heap Memory -
Use When String not going to change String change and will be accessed from a multiple thread. String change and will only be accessed from a single thread.
Synchronized - Yes No
Thread Safe - Yes. multiple threads can call its method without compromising internal data structure No
Efficient - Less than StringBuilder More than StringBuffer

Example

package com.seleniumtest;

public class StringDifference 
{
	// Concatenates to String
	public static void concateString(String str1)
	{
		str1 = str1 + " World";
	}

	// Concatenates to StringBuffer
	public static void concateStringBuffer(StringBuffer str2)
	{
		str2.append(" World");
	}
	 
	// Concatenates to StringBuilder
	public static void concateStringBuilder(StringBuilder str3)
	{
		str3.append(" World");
	}

	public static void main(String[] args)
	{
		String str1 = "Hello";
		concateString(str1);  // str1 is not changed
		System.out.println("String: " + str1);

		StringBuffer str2 = new StringBuffer("Hello");
		concateStringBuffer(str2); // str2 is changed
		System.out.println("StringBuffer: " + str2);

		StringBuilder str3 = new StringBuilder("Hello");
		concateStringBuilder(str3); // str3 is changed
		System.out.println("StringBuilder: " + str3);	
	}
}

Output

String: Hello
StringBuffer: Hello World
StringBuilder: Hello World

Bubble Sort in Java

Bubble sort repetitively compares adjacent pairs of elements and swaps if necessary.

Bubble Sort Steps

1. Scan the array, swapping adjacent pair of elements if they are not in relative order. This bubbles up the largest element to the end.
2. Scan the array again, bubbling up the second largest element.
3. Repeat until all elements are in order.

Example

When i = 5
Array = {40, 30, 50, 20, 60, 10}; 
Array = {30, 40, 50, 20, 60, 10}; j=0; Swap Left(40) > Right(30)
Array = {30, 40, 50, 20, 60, 10}; j=1; No Swap Left(40) < Right(50)
Array = {30, 40, 20, 50, 60, 10}; j=2; Swap Left(50) > Right(20)
Array = {30, 40, 20, 50, 60, 10}; j=3; No Swap Left(50) < Right(60)
Array = {30, 40, 20, 50, 10, 60}; j=4; Swap Left(60) > Right(10)

When i = 4
Array = {30, 40, 20, 50, 10, 60}
Array = {30, 40, 20, 50, 10, 60}; j = 0; No Swap, Left(30) < Right(40)
Array = {30, 20, 40, 50, 10, 60}; j = 1; Swap, Left(40) > Right(20)
Array = {30, 20, 40, 50, 10, 60}; j = 2; No Swap, Left(40) < Right(50)
Array = {30, 20, 40, 10, 50, 60}; j = 3; Swap, Left (50) > Right (10)

When i = 3
Array = {30, 20, 40, 10, 50, 60};
Array = {20, 30, 40, 10, 50, 60}; j = 0; Swap, Left (30) > Right(20)
Array = {20, 30, 40, 10, 50, 60}; j = 1; No Swap, Left (30) < Right (40)
Array = {20, 30, 10, 40, 50, 60}; j = 2; Swap Left(40) > Right (10)

When i = 2 
Array = {20, 30, 10, 40, 50, 60}
Array = {20, 30, 10, 40, 50, 60}; j = 0; No swap; Left(20) < Right(30)
Array = {20, 10, 30, 40, 50, 60}; j = 1; Swap; Left(30) > Right(10)

When i = 1
Array = {20, 10, 30, 40, 50, 60};
Array = (10, 20, 30, 40, 50, 60); J = 1, Swap; Left(20) > Right(10)

Here outer loop i iterate n times and innter loop iterate n/2 times. Total Time t(n) = n * (n/2) = O(n^2)

package com.seleniumtest;

public class BubbleSortDemo 
{
	public void bubbleSort(int[] inputArray)
	{
		int n = inputArray.length;
		
		for(int i = n-1; i >= 0; i--)
		{
			System.out.println("\n" + "Value of i:"+i+"\n");
			for (int j = 0; j <= i-1; j++)
			{
				System.out.println("Value of j:"+j);
				if(inputArray[j] > inputArray[j+1])
				{
					int temp = inputArray[j];
					inputArray[j] = inputArray[j+1];
					inputArray[j+1] = temp;
				}
			}
		}
	}
	
	public void printArray(int[] inputArray)
	{		
		for(int i = 0; i < inputArray.length; i++)
		{
			System.out.print(inputArray[i]+" ");
		}
	}
	
	public static void main(String args[])
	{
		int[] arr = {40, 30, 50, 20, 60, 10};
		
		BubbleSortDemo bsd = new BubbleSortDemo();
		bsd.bubbleSort(arr);
		System.out.println("Sorted Array");
		bsd.printArray(arr);
	}

}

What are the differences between ArrayList and Vector in Java?

ArrayList and Vector both use Array as a data structure internally. However there are few differences in the way they store and process the data. Below is the list of difference:

Point of Distinction ArrayList Vector
Synchronization Non-Synchronized, which means multiple threads can work on ArrayList at the same time. Synchronized. This means if one thread is working on Vector, no other thread can get a hold of it.
Resize Grow by half of its size when resized. Double the size of itself by default when grows.
Performance Fast. Better performance as its non-synchronized. Slow. Poor performance as they are thread-safe.
Fail-Fast Iterator and Listiterator returned by ArrayList are fail-fast. Enumeration returned by Vector is not fail-fast.
Syntax ArrayList<T> al = new ArrayList<T>(); Vector<T> v = new Vector<T>(); 
Thread Safe No Yes
Legacy Class No Yes
Define Increment Size No Yes
Traversing Iterator for Traversing. Use Iterator and Enumeration both.
Size to Array If an element is inserted into the Array List, it increases its Array size by 50%. Vector defaults to doubling size of its array.

Java program to find common elements between two arrays

 Below program will compare elements of 2 array and display duplicates elements.

package com.seleniumtest;

public class CommonArrayElements 
{
    public static void main(String args[])
    {
        int[] firstArray = {1, 4, 2, 3, 7, 5};
        int[] secondArray = {3, 4, 1, 6};
	
        for(int i=0; i < firstArray.length; i++)
        {
            for(int j=0; j<secondArray.length; j++)
            {
                if(firstArray[i] == secondArray[j])
                {
                    System.out.println(firstArray[i] + " ");
                }
            }
        }
    }
}

Difference between List and Set in Java?

List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.

Point of Distinction List Set
Positional Access Yes No
Duplicates Yes

No. If you try yo insert the duplicate element in Set it would replace the existing value.

Order Ordered. Insertion order is maintained. Depends upon implementation. LInkedHashSet maintains the elements in insertion order.
Null Value Any number of null values One null value in its collection.
Method inside Interface New methods are defined inside List interface. No new methods are defined inside Set interface.
Forward or Backward insertion Both direction using Listiterator. Forward direction with the help of iterator.
Use To store non-unique ordered elements in as per insertion order. To store unique non-ordered elements.
Implementation ArrayList, LinkedList etc. HashSet LinkedHashSet, TreeSet etc.
Legacy Class Vector None

Java Program To Count Occurrences Of Each Character In String using HashMap

Note: below program is Case sensitive and will also count space because space is also a character.

import java.util.HashMap;

public class OccuranceOfCharacter
{
    public void countOccurance(String inputString)
    {
        // HashMap char as a key and occurrence as a value
        HashMap <Character, Integer> charCountMap = new HashMap<Character, Integer>();

        // Convert String to Char Array
        char[] charArray = inputString.toCharArray();

        for(char ch : charArray)
        {
            // If char is already present in Map increment count by one
            if(charCountMap.containsKey(ch))
            {
                charCountMap.put(ch, charCountMap.get(ch)+1);
            }
           
            // If char is not present set key value to 1
            else
            {
                charCountMap.put(ch, 1);
            }
        }
		
        // Print CharCount Map
        System.out.println(charCountMap);
    }

    public static void main(String args[])
    {
        OccuranceOfCharacter ooc = new OccuranceOfCharacter();
        ooc.countOccurance("aabbbcccddddddd");
    }
}

Output: {a=2, b=3, c=3, d=7}

What is singleton class and how can we make a class singleton in Java?

Singleton class means you can create only one object for the given class. To design a singleton class:

  1. Make constructor as private.
  2. Write a static method that has return type object of this singleton class. 

Example:

class SingletonDemo
{
    // static variable single Instance of type Singleton
    private static SingletonDemo singleInstance = null;

    // private constructor restricted to this class itself
    private SingletonDemo()
    {
    }

    // static method to create instance of Singleton class
    public static SingletonDemo getInstance()
    {
        if (singleInstance == null)
            singleInstance = new SingletonDemo();
        return singleInstance;
    }
}

It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects.

Anagram Program In Java Using sort() and equals() Methods

 Two strings are said to be anagram if they contain same set of characters but in different order. For example, "Mother In Law" and "Hitler Woman" are anagrams.

import java.util.Arrays;

public class Anagram
{
    public void isAnagram(String str1, String str2)
    {
        //Removing all white spaces from Strings
        String newStr1 = str1.replaceAll("\\s", "");
        String newStr2 = str2.replaceAll("\\s", "");
        
        //Set initial status to true
        boolean status = true;

        if(newStr1.length() != newStr2.length())
        {
            //Setting status as false if newStr1 and newStr2 doesn't have same length
            status = false;
        }
        else
        {
            //Change the case of characters of both newStr1 and newStr2 and convert them to char array
            char[] str1Array = newStr1.toLowerCase().toCharArray();
            char[] str2Array = newStr2.toLowerCase().toCharArray();
            
           //Sort both str1Array and str2Array
            Arrays.sort(str1Array);
            Arrays.sort(str2Array);

            //Check whether str1Array and str2Array are equal
             status = Arrays.equals(str1Array, str2Array);
        }

        //Display if Strings are Anagrams or not
        if(status)
        {
            System.out.println(str1+" and "+str2+" are Anagrams.");
        }
        else
        {
            System.out.println(str1+" and "+str2+" are not Anagrams.");
        }
    }
 
    public static void main(String[] args)
    {
        Anagram an = new Anagram();
        an.isAnagram("School MASTER", "The ClassROOM");
        an.isAnagram("ASTRONOMERS", "NO MORE STARS");
        an.isAnagram("joy", "enjoy");
    }
}

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.