31.How will you make a HashMap of Unique Objects(Object with same Attributes should not be added more than once) or Mutable class does not allow override of HashCode and Equals?

If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.

Without HashCode

package com.mugil.org.qs;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Question31 
{
	public static void main(String[] args) 
	{
		Map hmStudents = new HashMap();
		
		Student objStudent1 = new Student();
		objStudent1.setName("Abdul");
		objStudent1.setAge(23);
		
		hmStudents.put(objStudent1, "Playboy");
		
		Student objStudent2 = new Student();
		objStudent2.setName("Joseph");
		objStudent2.setAge(23);
		
		hmStudents.put(objStudent2, "Upcoming Playboy");
		
		
		Student objStudent4 = new Student();
		objStudent4.setName("Joseph");
		objStudent4.setAge(23);
		
		hmStudents.put(objStudent4, "Playboy");
		
		
		Iterator it = hmStudents.entrySet().iterator();
		
	    while (it.hasNext()) 
	    {
	        Map.Entry pair = (Map.Entry)it.next();
	        System.out.println(((Student)pair.getKey()).getName() + " = " + pair.getValue());
	        
	    }
	}
}

class Student
{
	String Name;
	Integer Age;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}	
}

Output
Joseph = Playboy
Abdul = Playboy
Joseph = Upcoming Playboy

With HashCode Object with same value gets replaced

class Student
{
	String Name;
	Integer Age;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((Age == null) ? 0 : Age.hashCode());
		result = prime * result + ((Name == null) ? 0 : Name.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (Age == null) {
			if (other.Age != null)
				return false;
		} else if (!Age.equals(other.Age))
			return false;
		if (Name == null) {
			if (other.Name != null)
				return false;
		} else if (!Name.equals(other.Name))
			return false;
		return true;
	}	
}

Output
Joseph = Playboy
Abdul = Playboy

32.Why List<Parent> is not same as List<Child> ?
Let’s say we allow a List to be a subtype of List.Consider the following example:We allow a List to be a subtype of List. Consider the following example:

   List<String> stringList = new ArrayList<String>;
   List<Object> objectList = stringList; //this does compile only if List<String> where subtypes of List<Object>
   objectList.add(new Object());
   String s = stringList.get(0);// attempt to assign an Object to a String and the Java compiler has to prevent these cases.

In the above code you can see adding Parent and Child class within the same List may result in scenario where you wont be
able to guess whether its a Parent or Child.

If Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G is a subtype of G.

It’s useful to make comparison to arrays.
List is not subclass of List But Dog[] is subclass of Animal[]
Arrays are reifiable and covariant. Reifiable means their type information is fully available at runtime. Therefore arrays provide runtime type safety but not compile-time type
safety.

   // All compiles but throws ArrayStoreException at runtime at last line
    Dog[] dogs = new Dog[10];
    Animal[] animals = dogs; // compiles
    animals[0] = new Cat(); // throws ArrayStoreException at runtime

It’s vice versa for generics:Generics are erased and invariant. Therefore generics can’t provide runtime type safety, but they provide compile-time type safety.
In the code below if generics were covariant it will be possible to make heap pollution at line 3.

    List<Dog> dogs = new ArrayList<>();
    List<Animal> animals = dogs; // compile-time error, otherwise heap pollution
    animals.add(new Cat());

 

33.What is the difference between instanceof and getclass()
instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
getClass() == … tests whether the types are identical.

34.What are different reference types in java

  1. Strong References : We can create an object and then assign it to a reference. Note that if the object has a strong reference, this object is never be garbage collected.
    MyClass obj = new MyClass ();  
    
  2. Weak References :This type of reference is used in WeakHashMap to reference the entry objects.If JVM detects an object with only weak references (i.e. no strong or soft references linked to any object object), this object will be marked for garbage collection.
  3. Soft References :even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory
  4. Phantom References :A special reference which says that the object was already finalized, and the garbage collector is ready to reclaim its memory.Before removing them from the memory, JVM puts them in a queue called ‘reference queue’ . They are put in a reference queue after calling finalize() method on them

35.Difference betwen connection timeout and socket timeout?
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process.A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name or the network connection to the server is down.
A socket timeout is the timeout when waiting for individual packets. A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

36.Why we need to do serialization when the same can be done by using file streams?
Serialized objects maintain state in space, they can be transferred over the network, file system, etc
you could save your data to a text file on the computer, then have a program that reads that info, and based on the file, you could have your
program respond differently. if you use Serializable then you can easily load your Object graph to memory. For example you have a Student class
which have a Deportment. So if you serialize your Student then the Department also be saved.

Serializing on the other hand, puts things directly into computer language. It’s like you’re telling a Spanish computer something in Spanish, rather than telling it something in French, forcing it to learn French, then save things into its native Spanish by translating everything.
Serialization is also faster, because in Java, objects are handled on the heap, and take much longer than if they were represented as primitives on the stack.

37.What is Functional Interface?
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method compareTo is used for comparison purpose
Functional Interface is an interface which has one and only one abstract method. Apart from abstract method it can have any number of default and static methods which have an implementation and are not abstract and overriden method from Object.These interfaces are also called Single Abstract Method Interfaces. Few Functional Interfaces are Comparable, Runnable etc.More details here

38.What are marker interfaces?
Marker Interface in java is an interface with no fields or methods within it. It is used to convey to the JVM that the class implementing an interface of this category will have some special behavior.

Few Marker interface are as below

  1. Searilizable interface
  2. Cloneable interface
  3. Remote interface used for RMI
  4. ThreadSafe interface

Marker interface in Java e.g. Serializable, Clonnable, and Remote are used to indicate something to compiler or JVM that the class implementing any of these would have some special behavior. Hence, if the JVM sees a Class is implementing the Serializable interface it does some special operation on it and writes the state of the object into object stream. This object stream is then available to be read by another JVM. Similarly, if JVM finds that a class is implementing Cloneable interface, it performs some special operation in order to support cloning.

39.What is the Difference between String Literal and String Object?How it is stored in memory?

String s1 = "abc"; 
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);

JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.String literals s1 and s2 will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.”abc” will appear in heap and in string constant pool. Why is String s1 = “abc” and String obj1 = new String(“abc”) will be created this way? It’s because String obj1 = new String(“abc”) explicitly creates a new and referentially distinct instance of a String object and String s1 = “abc” may reuse an instance from the string constant pool if one is available.

40.What are ways of object creation in Java?

  1. Using new Keyword

    Employee objEmp = new Employee(); 
    
  2. Using newInstance

    Class cls = Class.forName("Employee"); 
    Employee obj =  (Employee) cls.newInstance(); 
    
  3. Using clone() method

    public class Employee implements Cloneable 
    { 
        @Override
        protected Object clone() throws CloneNotSupportedException 
        { 
            return super.clone(); 
        }     
      
        public static void main(String[] args) 
        { 
            Employee obj1 = new Employee(); 
            try
            { 
                Employee obj2 = (Employee) obj1.clone();       
            } 
            catch (CloneNotSupportedException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
    } 
    
  4. Using deserialization
    Refere Here
  5. Using newInstance() method of Constructor class(Reflection)

    Constructor<Employee> constructor = Employee.class.getDeclaredConstructor();
    Employeer = constructor.newInstance();
    r.setName("GeeksForGeeks");
    System.out.println(r.name);
    

41.When overriding a method, why can I increase access but not decrease it?
It’s a fundamental principle in OOP: the child class is a fully-fledged instance of the parent class, and must, therefore, present at least the same interface as the parent class. Making protected/public things less visible would violate this idea; you could make child classes unusable as instances of the parent class. Lets take the below code

class Person{
 public void display(){
      //some operation
    }
 }

class Employee extends Person{
   private void display(){
       //some operation
   }
 }

Calling Overridden method

Person p=new Employee();

Here p is the object reference with type Person(superclass) when we are calling p.display(). As the access modifier is more restrictive, the object reference p cannot access child object of type Employee

42.What if the same method is there in Abstract class and in interface?

public interface Intr {
    public void add();
}

public abstract class Abs {
    public void add() {
        System.out.println("Abs.m1()");
    }
    // public abstract void m1();
}

public class A extends Abs implements Intr {

    @Override
    public void add() {
        // which method am I overriding, well it is Abs.m1() but why?
        // if method implemented is Abs.add(), then why I am not getting error for Intr.add() not implemented.
    }
}

In the above implementation at the sametime, we are fulfilling the abstract class requirements and the interface requirements.it might make sense to move the implements Intr up to the abstract class definition. Though the abstract class method would be overridden first.

43.When you add a date Field to Immutable class despite it being declared as final it is modifiable as in below code, How will you create an immutable class with date field in it?

date = getDate();
date.setYear(2010); // allowed!

In the below code we have used defensive copying by sending the values of the date field and sending a copy of the date for accessing its value.

Solution

public Date getDate() {
    // Not correct.
    return this.date; // This will make your class mutable.

    // Instead use, 
    return new Date(this.date.getTime()); // This will make sure your date field cannot be changed.
}

44.What is Defensive Copying?
Lets take the code as below

class Point {
  final int x;
  final int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }

  Point(Point p) {
    this(p.x, p.y);
  }
}
  1. In the above code note how the constructor Point(Point p) takes a Point and makes a copy of it – that’s a copy constructor.
  2. This is a defensive copy because the original Point is protected from change by taking a copy of it
// A simple point.
Point p1 = new Point(3,42);
// A new point at the same place as p1 but a completely different object.
Point p2 = new Point(p1);

Using the above code you never have two references to the same object by accident

Comments are closed.