Wednesday, 19 June 2019

How to Sort a Binary Array Using a Single Traversal in Java

    In this post, we will discuss how to sort a binary array (containing only 0s and 1s) in Java. Given an unsorted binary array, the goal is to sort it by placing all 0s before all 1s while traversing the array only once.

Example:

Input:

{0, 1, 1, 0, 0, 0, 1, 0, 1}

Output:

{0, 0, 0, 0, 0, 1, 1, 1, 1}


Java Program:

SortBinaryArray.java

package com.practice;

public class SortBinaryArray {
 
        public static void main(String[] args) {
  
                  int arr[] = {1, 0, 1, 0, 0, 1, 1};
                  SortBinaryArray sort = new SortBinaryArray();
  
                  sort.sortBinaryArray(arr);
  
                  for (int i =0; i<arr.length; i++) {
                          System.out.print(arr[i]+" ");
                  }
         }
 
         private void sortBinaryArray(int arr[]) { 
        
                 int length = arr.length;
                 int j = -1; 
                 for (int i = 0; i < length; i++) { 
  
                         if (arr[i] < 1) { 
                               j++; 
                               int temp = arr[j]; 
                               arr[j] = arr[i]; 
                               arr[i] = temp; 
                          } 
                  } 
         } 

}

Output:-   0 0 0 1 1 1 1 


Related Posts:-
1) Java Program for Bubble Sort in Ascending and Descending order
2) Java Program to implement Selection Sort
3) Implementation of merge sort in Java
4) Java Object sorting example (Comparable and Comparable)
5) Difference between Comparable and Comparator Interface in Java
6) Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface
7) Java program to find second largest number in an array

Monday, 10 June 2019

Object-Level and Class-Level Locks in Java with Examples

         This is an important interview question for experienced Java developers, as it tests their understanding of the different types of locks used in multithreading.

As we know, Java supports the concurrent execution of multiple threads. When two or more threads access the same shared resource simultaneously, it can lead to data inconsistency or race conditions. To avoid these issues, Java provides the synchronization mechanism, which ensures that only one thread can access a shared resource at a time while other threads wait for their turn.

Synchronization is achieved using the synchronized keyword, which can be applied at either the method level or the block level.

There are two types of locking in Java multithreading:

  • Object level lock
  • Class level lock

Object level lock:-

         Object level locking is about synchronizing a non-static method or non-static code block such that only one thread will execute the code block on given instance of the class. Object level locking make instance level data thread safe.

There are different ways we can lock the object in thread as below,

public class ThreadClassEx {
      
       public synchronized void syncMethod(){
             //method implementation here
       }
}

public class ThreadClassEx {
      
       public void syncMethod(){
           
              synchronized(this) {
                  //block implementation here
              }
       }
}

public class ThreadClassEx {
      
         private final Object lock = new Object();

         public void syncMethod(){
           
                   synchronized(lock) {
                           //block implementation here
                   }
          }
}


Class level lock:-

         Class level locking is about a synchronizing a static method or block so that it can be accessed by only one thread for whole class. If you have 100 instances of class, only one thread will be able to access only one method or block of any one instance at a time.

        This should always be done to make static data thread safe.

Various ways of class level locking is as follows,

public class ThreadClassEx {

      public synchronized static void syncMethod(){
               //method implementation here
      }
}

public class ThreadClassEx {

      public void syncMethod(){
         
            synchronized(ThreadClassEx.class) {
               //block implementation here
            }
      }
}

public class ThreadClassEx {

      private final static Object lock = new Object();

      public void syncMethod(){
         
            synchronized(lock) {
               //block implementation here
            }
      }
}

Thank you for visiting blog.


Related Posts:-
1) Producer Consumer Problem - Solution using wait and notify In Java
2) Thread join() method example in Java
3) Difference between the Runnable and Callable interface in Java
4) Explain Thread life cycle and difference between wait() and sleep() method.
5) How many ways to create a thread in Java? Which one Prefer and why?
6) Producer Consumer Problem - Solution using BlockingQueue in Java

Wednesday, 5 June 2019

How to Create an Immutable Class with Mutable Object References in Java

     In the previous post, we discussed how to create an immutable class in Java. We covered all the rules and best practices that should be followed when designing an immutable class.

However, if an immutable class contains a reference to another mutable class, its immutability can be compromised. The referenced mutable class may come from a third-party library (JAR) or another application module, and you may not have access to modify or control its implementation.

In this post, we will discuss how to safely handle mutable object references within an immutable class. Specifically, we'll learn how to prevent a mutable reference from breaking the immutability of the enclosing class, ensuring that the entire class remains truly immutable.

In the example below, the Employee class is designed to be immutable, but the Address field refers to another Java class that is mutable. We will see how to handle this scenario correctly. 

Employee.java,
package com.practice;

public final class Employee {
 
        private final String empName;
        private final int age;
        private final Address address;
 
        public Employee(String name, int age, Address address) {
                super();
                this.empName = name;
                this.age = age;
                this.address = address;
        }

        public String getEmpName() {
                return empName;
        }

        public int getAge() {
                return age;
        }

         public Address getAddress() {
                return address;
         }

}

        In the above code, empName and age fields are immutable, we can not change the value but Address field it's reference of another java class and we can not have access or to modify the Address class.Here Address field is mutable, so we can restrict to modify the Address object/field in Employee class.

Address.java,

package com.practice;

public class Address implements Cloneable{
 
         public String addressType;
         public String address;
         public String city;
 
         public Address(String addressType, String address, String city) {
                   super();
                   this.addressType = addressType;
                   this.address = address;
                   this.city = city;
         }
         public String getAddressType() {
                   return addressType;
         }
         public void setAddressType(String addressType) {
                   this.addressType = addressType;
         }
         public String getAddress() {
                   return address;
         }
         public void setAddress(String address) {
                    this.address = address;
         }
         public String getCity() {
                    return city;
         }
         public void setCity(String city) {
                    this.city = city;
         }

         public Object clone() throws CloneNotSupportedException {  
                  return super.clone();  
         }

        @Override
        public String toString() {
                 return "Address Type - "+addressType+", address - "+address+", city - "+city;
        }
}

         In the below main class, you can create the Employee object using constructor, pass all parameters i.e empName, age and address. In the next line again we can set the addressType, address and city into the Address object. Now you try to access the address field from employee object it will get change. So in this case it will break the immutable behavior.

MainClass.java,

package com.practice;

public class MainClass {
 
     public static void main(String[] args) {
  
          Employee emp = new Employee("Mahesh", 34, new Address("Home", "JP Nagar", "Bangalore"));
  
          Address address = emp.getAddress();
  
          System.out.println(address);
  
          address.setAddress("Jayanagar");
          address.setAddressType("Office");
          address.setCity("Sangli");
  
          System.out.println(emp.getAddress());  
    }
}

Output:-
Address Type - Home, address - JP Nagar, city - Bangalore
Address Type - Office, address - Jayanagar, city - Sangli



Solution : -

The best solution is to modify the getAddress method in employee class, and instead of returning original Address object, we will return deep cloned copy of that instance. But one condition Address class must implements cloneable interface.

Modified employee class is as follow,

Employee.java,
package com.practice;

public final class Employee {
 
         private final String empName;
         private final int age;
         private final Address address;
 
         public Employee(String name, int age, Address address) {
                  super();
                  this.empName = name;
                  this.age = age;
                  this.address = address;
         }

         public String getEmpName() {
                  return empName;
         }

         public int getAge() {
                  return age;
         }

         public Address getAddress() throws CloneNotSupportedException {
                  return (Address) address.clone();
         }

}

Now we can check to execute main class,

MainClass.java,

package com.practice;

public class MainClass {
 
     public static void main(String[] args) {
  
           Employee emp = new Employee("Mahesh", 34, new Address("Home", "JP Nagar", "Bangalore"));
  
           Address address = emp.getAddress();
  
           System.out.println(address);
  
           address.setAddress("Jayanagar");
           address.setAddressType("Office");
           address.setCity("Sangli");
  
           System.out.println(emp.getAddress());  
     }

}

Output:-
Address Type - Home, address - JP Nagar, city - Bangalore
Address Type - Home, address - JP Nagar, city - Bangalore



Related Posts:-
1) String Interview Questions and Answers
2) Why String is immutable or final in java?
3) Difference between Loose Coupling and Tight Coupling in Java With Examples.
4) Builder Design Pattern in Java
5) What is call by value and call by reference in Java ?