Showing posts with label interview-java-question. Show all posts
Showing posts with label interview-java-question. Show all posts

Thursday, 27 July 2017

Missing Number In Array using java

import java.util.Arrays;
import java.util.BitSet;
 
/**
 * Java program to find missing elements in a Integer array containing 
 * numbers from 1 to 100.
 *
 * @author Rajdeo Singh
 */
public class MissingNumberInArray {
 
    public static void main(String args[]) {

        // one missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);
 
        // two missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);
 
        // three missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);
 
        // four missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);
 
        // Only one missing number in array
        int[] iArray = new int[]{1, 2, 3, 5};
        int missing = getMissingNumber(iArray, 5);
        System.out.printf("Missing number in array %s is %d %n"
                           Arrays.toString(iArray), missing);
    }

   /**
    * A general method to find missing values from an integer array in Java.
    * This method will work even if array has more than one missing element.
    */
    private static void printMissingNumber(int[] numbers, int count) {
        int missingCount = count - numbers.length;
        BitSet bitSet = new BitSet(count);
 
        for (int number : numbers) {
            bitSet.set(number - 1);
        }
 
        System.out.printf("Missing numbers in integer array %s, with total number %d is %n",
        Arrays.toString(numbers), count);
        int lastMissingIndex = 0;

        for (int i = 0; i < missingCount; i++) {
            lastMissingIndex = bitSet.nextClearBit(lastMissingIndex);
            System.out.println(++lastMissingIndex);
        }
 
    }

   /**
    * Java method to find missing number in array of size n containing
    * numbers from 1 to n only.
    * can be used to find missing elements on integer array of 
    * numbers from 1 to 100 or 1 - 1000
    */
    private static int getMissingNumber(int[] numbers, int totalCount) {
        int expectedSum = totalCount * ((totalCount + 1) / 2);
        int actualSum = 0;
        for (int i : numbers) {
            actualSum += i;
        }
 
        return expectedSum - actualSum;
    }
 
}
 
Output
Missing numbers in integer array [1, 2, 3, 4, 6], with total number 6 is
5
Missing numbers in integer array [1, 2, 3, 4, 6, 7, 9, 8, 10], with total number 10 is
5
Missing numbers in integer array [1, 2, 3, 4, 6, 9, 8], with total number 10 is
5
7
10
Missing numbers in integer array [1, 2, 3, 4, 9, 8], with total number 10 is
5
6
7
10
Missing number in array [1, 2, 3, 5] is 4

Restrict a class from serialization, but super class is serialized?

Restrict a class from serialization, but super class is serialized

Suppose you had scenario like below.
a.   There is a class Employee.java, which implements Serializable interface.
b.   There is a class PermanentEmployee, which extends Employee class.

Your problem statement is, you have to restrict PermanentEmployee objects from serialization process.

Let me give a working example first, after that will see how to solve this problem.


Employee.java
import java.io.Serializable;

public class Employee implements Serializable {
 private static final long serialVersionUID = 1234L;

 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


PermanentEmployee.java
public class PermanentEmployee extends Employee {
 private static final long serialVersionUID = 1234L;

 private String phoneNum;

 public String getPhoneNum() {
  return phoneNum;
 }

 public void setPhoneNum(String phoneNum) {
  this.phoneNum = phoneNum;
 }

 @Override
 public String toString() {
  return "PermanentEmployee [phoneNum=" + phoneNum + ", getId()=" + getId() + ", getFirstName()=" + getFirstName()
    + ", getLastName()=" + getLastName() + ", toString()=" + super.toString() + ", getClass()=" + getClass()
    + ", hashCode()=" + hashCode() + "]";
 }

}

Test.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {
 private static ObjectOutputStream out;
 private static ObjectInputStream in;

 private static PermanentEmployee getEmployee() {
  PermanentEmployee emp = new PermanentEmployee();
  emp.setId(1);
  emp.setFirstName("Hari Krishna");
  emp.setLastName("Gurram");
  emp.setPhoneNum("123456");

  return emp;
 }

 public static void main(String args[]) throws IOException, ClassNotFoundException {
  /* Serialize object */
  FileOutputStream fos = new FileOutputStream("ser.out");
  out = new ObjectOutputStream(fos);
  PermanentEmployee emp = getEmployee();
  out.writeObject(emp);

  /* Deserialize object */
  FileInputStream fis = new FileInputStream("ser.out");
  in = new ObjectInputStream(fis);
  PermanentEmployee emp1 = (PermanentEmployee) in.readObject();

  System.out.println(emp1);

 }
}

Output

PermanentEmployee [phoneNum=123456, getId()=1, getFirstName()=Hari Krishna, getLastName()=Gurram, toString()=Employee [id=1, firstName=Hari Krishna, lastName=Gurram], getClass()=class PermanentEmployee, hashCode()=1096979270]

As you see the output, since Employee class is implementing Serializable interface, I can able to serialize all the sub classes (PermanentEmployee) of Employee class.

How to restrict sub class from serialization?
By using custom serialization you can restrict sub class from serialization. In my previous post, I already explained how to achieve custom serialization. To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.

Add following methods to PermanentEmployee class.

private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
         throw new NotSerializableException("PermanentEmployee is not serializable");
}

private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
         throw new NotSerializableException("PermanentEmployee is not serializable");
}

Following is the updated PermanentEmployee.java file.

PermanentEmployee.java

import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;

public class PermanentEmployee extends Employee {
 private static final long serialVersionUID = 1234L;

 private String phoneNum;

 public String getPhoneNum() {
  return phoneNum;
 }

 public void setPhoneNum(String phoneNum) {
  this.phoneNum = phoneNum;
 }

 @Override
 public String toString() {
  return "PermanentEmployee [phoneNum=" + phoneNum + ", getId()=" + getId() + ", getFirstName()=" + getFirstName()
    + ", getLastName()=" + getLastName() + ", toString()=" + super.toString() + ", getClass()=" + getClass()
    + ", hashCode()=" + hashCode() + "]";
 }

 private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
  throw new NotSerializableException("PermanentEmployee is not serializable");
 }

 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
  throw new NotSerializableException("PermanentEmployee is not serializable");

 }

}

Re run Test.java, you can able to see following output.

Exception in thread "main" java.io.NotSerializableException: PermanentEmployee is not serializable
 at PermanentEmployee.writeObject(PermanentEmployee.java:26)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
 at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
 at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
 at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
 at Test.main(Test.java:26)

You may lik

what is JIT Compiler in Java ?


JIT stands for Just-in-Time. It is part of Java Run time Environment (JRE). It optimizes the performance of Java Application, by compiling byte codes to native machine code at run time.

JIT compiler enabled by default. Whenever a particular method is called, the JIT compiler compiles the byte code related to that method to native machine code.

JIT compilation threshold
Usually not every method code is compiled by JIT. JVM increases method call count for each method whenever a particular method is called. If the call count reaches to particular threshold, then JIT compiles and apply optimization's to the code. Until method count reaches to threshold, JVM interprets the byte code of the method whenever it is called.

What happens after JIT performs Compilation
Once JIT performs compilation, then method call count is reset to zero. Any calls to the method uses the compiled code(It won't interpret again and again) and method call count starts incrementing on sub sequent calls. Once method count reaches to thresh hold again, the code is recompiled by JIT and applies some more optimizations. This process repeats until the maximum optimization level is reached.

To do optimization JIT uses various techniques like Register usage optimization, Loop reduction and inversion, switch Analysis, GC and memory allocation optimizations etc.,a