Wednesday, 19 June 2019

Sort a binary array using one traversal in Java

     In the current post, we can discuss the binary sort i.e 0 and 1 in Java. Given a binary array contains 0 & 1 in unsorted order, the output should be in sorted but we have to traverse only once.

Example:-

Input , array - {0,1,1,0,0,0,1,0,1}
Output, array - {0,0,0,0,0,1,1,1,1}

Java code:-

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 example

        This question is also important for experienced java developers to know about type of locks in multithreading.         
        As we know that java supports multiple threads to be executed concurrently. If  two or more threads accessing the same resource at a time then conflict/inconsistent will occur. To avoid this inconsistency we are following synchronization concept i.e at a time one thread can access resource and wait for another thread to access. Using synchronized keyword to achieve the synchronization.  The synchronized keyword can be used as method level or block level.

   There are two types of locking in java in threading,

  • 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 Custom Immutable Class with mutable object references in Java?

       We discussed in previous post about How to create the Immutable object in Java.  We discussed the all steps or rules we need to follow while creating immutable class in java. But if any field in the custom immutable class contains reference to any other mutable class then it will break immutable behavior. The reference class can be from imported jar files or any other imported application class and we can not access/control that mutable class. In this post, we will discuss how to make/convert mutable reference to immutable so that the complete class will become immutable.

      In the below example, Employee class is immutable but filed Address is mutable, it's another java class . 

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 ?