{"id":2762,"date":"2018-03-12T05:34:38","date_gmt":"2018-03-12T05:34:38","guid":{"rendered":"http:\/\/codethataint.com\/blog\/?p=2762"},"modified":"2019-05-06T14:42:28","modified_gmt":"2019-05-06T14:42:28","slug":"whatsapp-java-group-java-questions-set2","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/whatsapp-java-group-java-questions-set2\/","title":{"rendered":"Whatsapp Java Group &#8211; Java Questions &#8211; Set2"},"content":{"rendered":"<p><strong>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?<\/strong><\/p>\n<p><em>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.<\/em><\/p>\n<pre>JVM assigns unique hashcode value to each object when they are created in memory and if developers don\u2019t override the hashcode method then there is no way the two object returns same hashcode value.\r\n<\/pre>\n<p><strong>Without HashCode<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org.qs;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Iterator;\r\nimport java.util.Map;\r\n\r\npublic class Question31 \r\n{\r\n\tpublic static void main(String&#x5B;] args) \r\n\t{\r\n\t\tMap hmStudents = new HashMap();\r\n\t\t\r\n\t\tStudent objStudent1 = new Student();\r\n\t\tobjStudent1.setName(&quot;Abdul&quot;);\r\n\t\tobjStudent1.setAge(23);\r\n\t\t\r\n\t\thmStudents.put(objStudent1, &quot;Playboy&quot;);\r\n\t\t\r\n\t\tStudent objStudent2 = new Student();\r\n\t\tobjStudent2.setName(&quot;Joseph&quot;);\r\n\t\tobjStudent2.setAge(23);\r\n\t\t\r\n\t\thmStudents.put(objStudent2, &quot;Upcoming Playboy&quot;);\r\n\t\t\r\n\t\t\r\n\t\tStudent objStudent4 = new Student();\r\n\t\tobjStudent4.setName(&quot;Joseph&quot;);\r\n\t\tobjStudent4.setAge(23);\r\n\t\t\r\n\t\thmStudents.put(objStudent4, &quot;Playboy&quot;);\r\n\t\t\r\n\t\t\r\n\t\tIterator it = hmStudents.entrySet().iterator();\r\n\t\t\r\n\t    while (it.hasNext()) \r\n\t    {\r\n\t        Map.Entry pair = (Map.Entry)it.next();\r\n\t        System.out.println(((Student)pair.getKey()).getName() + &quot; = &quot; + pair.getValue());\r\n\t        \r\n\t    }\r\n\t}\r\n}\r\n\r\nclass Student\r\n{\r\n\tString Name;\r\n\tInteger Age;\r\n\t\r\n\tpublic String getName() {\r\n\t\treturn Name;\r\n\t}\r\n\tpublic void setName(String name) {\r\n\t\tName = name;\r\n\t}\r\n\tpublic Integer getAge() {\r\n\t\treturn Age;\r\n\t}\r\n\tpublic void setAge(Integer age) {\r\n\t\tAge = age;\r\n\t}\t\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><br \/>\nJoseph = Playboy<br \/>\nAbdul = Playboy<br \/>\nJoseph = Upcoming Playboy<\/p>\n<p><strong>With HashCode Object with same value gets replaced<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass Student\r\n{\r\n\tString Name;\r\n\tInteger Age;\r\n\t\r\n\tpublic String getName() {\r\n\t\treturn Name;\r\n\t}\r\n\tpublic void setName(String name) {\r\n\t\tName = name;\r\n\t}\r\n\tpublic Integer getAge() {\r\n\t\treturn Age;\r\n\t}\r\n\tpublic void setAge(Integer age) {\r\n\t\tAge = age;\r\n\t}\r\n\t\r\n\t\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((Age == null) ? 0 : Age.hashCode());\r\n\t\tresult = prime * result + ((Name == null) ? 0 : Name.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tStudent other = (Student) obj;\r\n\t\tif (Age == null) {\r\n\t\t\tif (other.Age != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!Age.equals(other.Age))\r\n\t\t\treturn false;\r\n\t\tif (Name == null) {\r\n\t\t\tif (other.Name != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!Name.equals(other.Name))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\t\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><br \/>\nJoseph = Playboy<br \/>\nAbdul = Playboy<\/p>\n<p><strong>32.Why List&lt;Parent&gt; is not same as List&lt;Child&gt; ?<\/strong><br \/>\nLet&#8217;s say we allow a List to be a subtype of List<object width=\"300\" height=\"150\">.Consider the following example:We allow a List<string> to be a subtype of List<object>. Consider the following example:<\/object><\/string><\/object><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n   List&lt;String&gt; stringList = new ArrayList&lt;String&gt;;\r\n   List&lt;Object&gt; objectList = stringList; \/\/this does compile only if List&lt;String&gt; where subtypes of List&lt;Object&gt;\r\n   objectList.add(new Object());\r\n   String s = stringList.get(0);\/\/ attempt to assign an Object to a String and the Java compiler has to prevent these cases.\r\n<\/pre>\n<p>In the above code you can see adding Parent and Child class within the same List may result in scenario where you wont be<br \/>\nable to guess whether its a Parent or Child.<\/p>\n<p><em>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. <\/em><\/p>\n<p>It&#8217;s useful to make comparison to arrays.<br \/>\n<em>List is not subclass of List But Dog[] is subclass of Animal[]<\/em><br \/>\nArrays 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<br \/>\nsafety.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n   \/\/ All compiles but throws ArrayStoreException at runtime at last line\r\n    Dog&#x5B;] dogs = new Dog&#x5B;10];\r\n    Animal&#x5B;] animals = dogs; \/\/ compiles\r\n    animals&#x5B;0] = new Cat(); \/\/ throws ArrayStoreException at runtime\r\n<\/pre>\n<p>It&#8217;s vice versa for generics:Generics are erased and invariant. Therefore generics can&#8217;t provide runtime type safety, but they provide compile-time type safety.<br \/>\nIn the code below if generics were covariant it will be possible to make heap pollution at line 3.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n    List&lt;Dog&gt; dogs = new ArrayList&lt;&gt;();\r\n    List&lt;Animal&gt; animals = dogs; \/\/ compile-time error, otherwise heap pollution\r\n    animals.add(new Cat());\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>33.What is the difference between instanceof and getclass()<\/strong><br \/>\n<em>instanceof<\/em> 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.<br \/>\n<em>getClass()<\/em> == &#8230; tests whether the types are identical.<\/p>\n<p><strong>34.What are different reference types in java<\/strong><\/p>\n<ol>\n<li><strong>Strong References<\/strong> : 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.\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nMyClass obj = new MyClass ();  \r\n<\/pre>\n<\/li>\n<li><strong>Weak References<\/strong> :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.<\/li>\n<li><strong>Soft References<\/strong> :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<\/li>\n<li><strong>Phantom References<\/strong> :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 \u2018reference queue\u2019 . They are put in a reference queue after calling finalize() method on them<\/li>\n<\/ol>\n<p><strong>35.Difference betwen connection timeout and socket timeout?<\/strong><br \/>\nA\u00a0connection timeout\u00a0is the maximum amount of time that the program is willing to wait to setup a connection to another process.A\u00a0connection timeout\u00a0occurs 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.<br \/>\nA socket timeout is the timeout when waiting for individual packets. A\u00a0socket timeout\u00a0is 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.<\/p>\n<p><strong>36.Why we need to do serialization when the same can be done by using file streams?<\/strong><br \/>\nSerialized objects maintain state in space, they can be transferred over the network, file system, etc<br \/>\nyou 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<br \/>\nprogram respond differently. if you use Serializable then you can easily load your Object graph to memory. For example you have a Student class<br \/>\nwhich have a Deportment. So if you serialize your Student then the Department also be saved.<\/p>\n<p>Serializing on the other hand, puts things directly into computer language. It&#8217;s like you&#8217;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.<br \/>\nSerialization 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.<\/p>\n<p><strong>37.What is Functional Interface?<\/strong><br \/>\nFunctional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method compareTo is used for comparison purpose<br \/>\nFunctional 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 <a href=\"http:\/\/codethataint.com\/blog\/what-are-functional-interface-how-it-works\/\">here<\/a><\/p>\n<p><strong>38.What are marker interfaces?<\/strong><br \/>\nMarker 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.<\/p>\n<p>Few Marker interface are as below<\/p>\n<ol>\n<li>Searilizable interface<\/li>\n<li>Cloneable interface<\/li>\n<li>Remote interface used for RMI<\/li>\n<li>ThreadSafe interface<\/li>\n<\/ol>\n<p>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.<\/p>\n<p><strong>39.What is the Difference between String Literal and String Object?How it is stored in memory?<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nString s1 = &quot;abc&quot;; \r\nString s2 = &quot;123&quot;;\r\nString obj1 = new String(&quot;abc&quot;);\r\nString obj2 = new String(&quot;def&quot;);\r\nString obj3 = new String(&quot;456);\r\n<\/pre>\n<p>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.&#8221;abc&#8221; will appear in heap and in string constant pool. Why is String s1 = &#8220;abc&#8221; and String obj1 = new String(&#8220;abc&#8221;) will be created this way? It&#8217;s because String obj1 = new String(&#8220;abc&#8221;) explicitly creates a new and referentially distinct instance of a String object and String s1 = &#8220;abc&#8221; may reuse an instance from the string constant pool if one is available.<\/p>\n<p><strong>40.What are ways of object creation in Java?<\/strong><\/p>\n<ol>\n<li>\n<strong>Using new Keyword<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nEmployee objEmp = new Employee(); \r\n<\/pre>\n<\/li>\n<li>\n<strong>Using newInstance<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nClass cls = Class.forName(&quot;Employee&quot;); \r\nEmployee obj =  (Employee) cls.newInstance(); \r\n<\/pre>\n<\/li>\n<li>\n<strong>Using clone() method<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Employee implements Cloneable \r\n{ \r\n    @Override\r\n    protected Object clone() throws CloneNotSupportedException \r\n    { \r\n        return super.clone(); \r\n    }     \r\n  \r\n    public static void main(String&#x5B;] args) \r\n    { \r\n        Employee obj1 = new Employee(); \r\n        try\r\n        { \r\n            Employee obj2 = (Employee) obj1.clone();       \r\n        } \r\n        catch (CloneNotSupportedException e) \r\n        { \r\n            e.printStackTrace(); \r\n        } \r\n    } \r\n} \r\n<\/pre>\n<\/li>\n<li>\n<strong>Using deserialization<\/strong><br \/>\nRefere Here\n<\/li>\n<li>\n<strong>Using newInstance() method of Constructor class(Reflection)<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nConstructor&lt;Employee&gt; constructor = Employee.class.getDeclaredConstructor();\r\nEmployeer = constructor.newInstance();\r\nr.setName(&quot;GeeksForGeeks&quot;);\r\nSystem.out.println(r.name);\r\n<\/pre>\n<\/li>\n<\/ol>\n<p><strong>41.When overriding a method, why can I increase access but not decrease it?<\/strong><br \/>\nIt&#8217;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<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass Person{\r\n public void display(){\r\n      \/\/some operation\r\n    }\r\n }\r\n\r\nclass Employee extends Person{\r\n   private void display(){\r\n       \/\/some operation\r\n   }\r\n }\r\n<\/pre>\n<p>Calling Overridden method<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nPerson p=new Employee();\r\n<\/pre>\n<p>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<\/p>\n<p><strong>42.What if the same method is there in Abstract class and in interface?<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic interface Intr {\r\n    public void add();\r\n}\r\n\r\npublic abstract class Abs {\r\n    public void add() {\r\n        System.out.println(&quot;Abs.m1()&quot;);\r\n    }\r\n    \/\/ public abstract void m1();\r\n}\r\n\r\npublic class A extends Abs implements Intr {\r\n\r\n    @Override\r\n    public void add() {\r\n        \/\/ which method am I overriding, well it is Abs.m1() but why?\r\n        \/\/ if method implemented is Abs.add(), then why I am not getting error for Intr.add() not implemented.\r\n    }\r\n}\r\n<\/pre>\n<p>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.<\/p>\n<p><strong>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?<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\ndate = getDate();\r\ndate.setYear(2010); \/\/ allowed!\r\n<\/pre>\n<p>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.<\/p>\n<p><strong>Solution<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic Date getDate() {\r\n    \/\/ Not correct.\r\n    return this.date; \/\/ This will make your class mutable.\r\n\r\n    \/\/ Instead use, \r\n    return new Date(this.date.getTime()); \/\/ This will make sure your date field cannot be changed.\r\n}\r\n<\/pre>\n<p><strong>44.What is Defensive Copying?<\/strong><br \/>\nLets take the code as below<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass Point {\r\n  final int x;\r\n  final int y;\r\n\r\n  Point(int x, int y) {\r\n    this.x = x;\r\n    this.y = y;\r\n  }\r\n\r\n  Point(Point p) {\r\n    this(p.x, p.y);\r\n  }\r\n}\r\n<\/pre>\n<ol>\n<li>In the above code note how the constructor Point(Point p) takes a Point and makes a copy of it &#8211; that&#8217;s a copy constructor.<\/li>\n<li>This is a defensive copy because the original Point is protected from change by taking a copy of it<\/li>\n<\/ol>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ A simple point.\r\nPoint p1 = new Point(3,42);\r\n\/\/ A new point at the same place as p1 but a completely different object.\r\nPoint p2 = new Point(p1);\r\n<\/pre>\n<p><em>Using the above code you never have two references to the same object by accident<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&hellip; <a href=\"https:\/\/codethataint.com\/blog\/whatsapp-java-group-java-questions-set2\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[193],"tags":[253,225],"class_list":["post-2762","post","type-post","status-publish","format-standard","hentry","category-interview-questions-java","tag-interview","tag-whatsapp-java-group"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2762","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=2762"}],"version-history":[{"count":23,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2762\/revisions"}],"predecessor-version":[{"id":3364,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2762\/revisions\/3364"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=2762"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=2762"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=2762"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}