equals() vs contentEquals() vs ==

Why equals method is used?

To compare two string contents [One string can be in stack memory and other can be in Heap memory, still it compares the contents of the strings]

String s1 = “abc”;

String s2 =  “abc”;

String s3 = new String (“abc”);

System.out.println(s1.equals(s2));  // o/p: True  [hashcodes are same in this case]

System.out.println(s1.equals(s3));   // o/p: True [hashcodes are different in this case]

Why ‘==’ is used?

It is an operator which compares the Hashcodes (not the content present inside them).

String s1 = “abc”;

String s2 =  “abc”;

String s3 = new String (“abc”);

System.out.println(s1==s2);  // o/p: True  [hashcodes are same in this case]

System.out.println(s1==s3);   // o/p: False [hashcodes are different in this case]

Why contentEquals is used?

It is used to compare the String object with StringBuffer/StringBuilder/ Char Array objects.

Note:

  • You can’t compare String object with StringBuffer object using equals method.
  • You can compare String object with another String object using equals and contentEquals methods. [both are same, but equals is specific to compare strings only]

 

String s1 =”abc”;

String s2 =new StringBuilder(“abc”);

System.out.println(s1.contentEquals(s2)); // o/p: true [hashcodes are different in this case]

 

String Is Immutable?

String:

Yes, String is Immutable. Means once the data is assigned to a String variable, it stores in a memory slot where the data can not be modified. If you try to modify the data, it’ll create a new data slot and the reference variable point to the new dataslot.

Eg:

 


String s = "abc"; //This will create a dataslot in string pool of stack memory, and point the reference variable 's' to that data slot.

s.concat("def"); 

System.out.println(s);

// Guess the output? It is "abc". [the concated data is stored in a new dataslot, but reference variable 's' is still referencing to the old dataslot]

s = s.concat("def");

System.out.println(s);

// Now the output is "abcdef". [The concated data is stored in new dataslot and the reference variable 's' is pointing to this new dataslot];

 

Then, the data present in previous dataslot of string pool won’t be changed, instead a new dataslot will be created in the string pool and the reference variable ‘s’ will point to the new dataslot created.

Then what about the previous dataslot?

Garbage Collector will take care of that. GC will clear the memory slots of all in regular cycles, to those there are no reference variables. So that memory will be cleared.

So with the above example and discussion, we concluded that String is Immutable.

StringBuffer & StringBuilder:

Before discussing about StringBuilder& StringBuffer, first let’s know why these are used when we have ‘String’. The answer is because String is Immutable and these are Mutable versions of String. Means when you have a requirement that you need to add/modify the data multiple times after initial assignment, then use StringBuilder. If you do the same with String, it’ll create a new memory slot for data for each modification which leads to memory leakage/wastage.

StringBuilder & StringBuffer are mutable. Means once the data is stored in a dataslot, if you modify the data, then it won’t create a new dataslot, it just updates the existing dataslot and the reference variable point to the same dataslot.

StringBuffer sb = new StringBuffer("abc"); // mutable, synchronized
sb.append("def");
System.out.println(sb);

StringBuilder sbuilder = new StringBuilder("abc"); // mutable, non synchronized
sbuilder.append("def");
System.out.println(sbuilder);

 

Note:  StringBuilder is introduced in Java 1.5, in Java 1.4 there is only StringBuffer.

Why StringBuilder came when there is StringBuffer?

It’s very rare that you really need to build strings in a thread-safe manner, so why pay the synchronization cost? So that is the reason StringBuffer is obsolete now.

 

 

HashMap and Object Class:

====================================================================
Object Class:
Before discussing about Object class methods you should know one thing that every class by default extends ‘Object’ class. So you can override its methods.
Methods which you can override:
1) toString()
@Override
public String toString() {
return this.itemName+this.itemsCount;
}
2) equals(Object obj)
@Override
public boolean equals(Object obj) {
if(obj instanceof Price){  //checking that the new object getting created is instance of Price class or different class.
return (((Price)obj).itemName.equals(this.itemName) && (((Price)obj).itemsCount==this.itemsCount)) ;
// ((Price)obj).itemName -> means type casting current obj to Price obj as it is instnce of Price class and getting val of ‘itemName’
// this.itemName -> means getting value of ‘itemName’ from Price class.
}
3)     Hashcode()
@Override
public int hashCode() {
// TODO Auto-generated method stub
return new Integer(this.itemsCount).hashCode()+this.itemName.hashCode();
}

4) Clone()
5) finalize()

====================================================================
toString() method:
-> The wrapper classess like ‘Integer’, ‘Double’ will be having ‘toString()’ method in their calsses.
So you can convert Integer to string using that method which has implementation to convert. That’ll take Integer as input and gives string as output.
eg: Integer i = 10;
String ival = i.toString();
Note that toString() method has the code to convert Integer to String.
You can not overwrite the toString method of Integer class. [you can’t extend Integer class as it is decalred as Final. So you can not overwrite its toString method. This applies to all wrapper classes.]
-> If you want to store your class object as key in map. you can do it, but when you try to print the keys present in the Map then it’ll return the hashcode of address where the class object stored in hash memory, insted returning exact key. So you need to overwrite the ‘toString()’ method to give your own implementaion. By default toString method returns hashcode, so by overwriting this method in your class you can return any value for the class object instead of its hashcode.
Go thorugh post for detailed explanation:

====================================================================
hashcode() & equals(Object obj) methods:

  • In your hashmap if your key is String or any wrapper class type then if you insert record like hm.put(“fruit”,”banana”) and again if you insert record like hm.put(“fruit”,”apple”), then the second record’s value will be overridden on existing record, it won’t create new record. Because all the wrapper classes implements (Object class) hashcode() and equals(Object obj) methods. So when you insert a record whose key of wrapper class type, first hashcode() method will be called where the hashcode of key will be generated and checked with existing hashcodes of buckets and if it finds any similar hashcode present for any key then it’ll call equals method. In equals method it matches the current key with the matched hashcode key and if the Key’s are also same then returns boolean ‘True’. If it returns true then it will override the existing record, instead creating a new record.
  • Suppose your hashmap is using the key of custom type instead of wrapper class type like below HashMap<Price, int>hm = new HashMap<>(); In this case Key ‘Price’ class is not a wrapper class, so by default it won’t implement equals and hashcode methods. So if you insert a record even though the keys are same it’ll create a new record instead overriding the existing record. So you have to manually override the hashcode() and equals(Object obj) methods. In those method write the logic to generate the hashcode in hashcode() method and logic to compare Keys in equal method.

Now let’s discuss about equals() method. Lets take an example to understand about this method. You have an HashMap and you are storing the class object as Key and value as String. HashMap allows you to insert duplicate Keys(If your key is not of wrapper class type). If your requirement is like not to allow duplicate Keys then you must have to override equals(Object obj) method along with Hashcode() method and put your own implementation. Why? As shown in above example code snippets, first hashcode method will be triggered in which we are manually assigning hashcode to the key. after hashcode()  method, if the same hashcode generated is already present in bucket then equals(Object obj) method will be triggered. In equals(Object obj) method we are comparing current key object getting inserted is an instance of Price class, If yes then compare current object is already exists in HashMap or not, if yes return True. If you return true in equals method, then it’ll assign the new value to the existing key instead creating a new key value pair in HashMap.

====================================================================
HashMap vs Concurrent Hashmap:
Assume HashMap has a bucket and all the contents(Key Value pairs) are stored in it in one of the 16 slots based on Key’s hash value.
Let’s take a scenario, if many threads are acessing same Hashmap and if one thread is trying to modify the HashMap data(Key) and if another thread trying to read the data from HashMap then it’ll get ‘ConcurrentModificationException’. So to avoid this we can use ConcurrentHashMap which is synchronized. By using ConcurrentHashMap the same instance is cloned/shared by all the threads. So if the key is changed in one thread, then its newly generated Hashcode(address in bucket) is automatically updated in all the threads.
Note: You can synchronize your method also, but using Concurrent Hashmap is preferred over this as only HashMap is synchronized rather than everything in mehtod. And another thing you have to understand is that performance will be decreased when using ConcurrentHashMap as it updates latest records in all the current threads (which depends on number of users accessing the HashMap).
-> When you’ve multiple threads which try to modify data in HashMap, then  (1) use ConcurrentHashMap and use Forloop (don’t use Iterator) (2) use HashMap and use method as Synchronized, and ForLoop. (3) use HashMap and use Iterator (don’t use For loop).
-> If multiple threads try to just read the data(not modify) then use ‘HashMap’ and use ForLoop (don’t use Itertor)

====================================================================

HashMap vs ConcurrentHashMap vs Collections.synchronizedMap( HashMap ) :

The difference between HashMap and ConcurrenHashMap we just discussed above.

ConcurrentHashMap contains segments which are nothing but HashMaps (default 16 segments) so that multiple threads can access these multiple segments at a time. There is no lock/blocking for one thread if another thread is accessing. Means Concurrency is achieved here.

Collections.synchronizedMap(HashMap) is a synchronized version of HashMap. Here lock is enabled to the Map, means if one thread is modifying the map another thread can not access it. Means synchronization is achieved here and Map is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.

====================================================================

Collections.synchronizedMap( HashMap ) vs HashTable:

Both are synchronized version of collection. Both have synchronized methods inside class. Both are blocking in nature i.e. multiple threads will need to wait for getting the lock on instance before putting/getting anything out of it.

So what is the difference. Well, NO major difference for above said reasons. Performance is also same for both collections.

Only thing which separates them is the fact HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.

====================================================================

HashMap vs Hashtable detailed:

HashMap Hashtable
Synchronized No Yes
Thread-Safe No Yes
Null Keys and Null values One null key Any null values Not permit null keys and values
Iterator type Fail fast Iterator Fail safe iterator
Performance Fast Slow in comparison
Superclass and Legacy AbstractMap, No Dictionary, Yes

http://javahungry.blogspot.com/2014/03/hashmap-vs-hashtable-difference-with-example-java-interview-questions.html

====================================================================

HashMap, Collections.synchronizedMap, HashTable, ConcurrentHashMap:

  HashMap Collections.synchronizedMap HashTable ConcurrentHashMap
What? Map which stores (K, V) pairs. Which doesn’t allow multiple threads to modify the structure of Map. [e.g.: while iterating map, if you try to insert a record, it throws ConcurrentModificationException] Synchronized version of HashMap. [which allows only one thread to access Map a time as the lock is at object level. So lock will be for put, get methods.] Synchronized version of HashMap. [which allows only one thread to access Map a time as the lock is at object level. So lock will be for put, get methods.] This is also synchronized version of HashMap.  which allows multiple threads to modify the records(add/remove) at a time, as the lock is only at HashMap bucket level.
Can Multiple threads can read at a time? Yes Yes Yes Yes
Can Multiple threads can modify size of Map (Add or remove records while iterating) No (gives ConcurrentModificationException) No (gives ConcurrentModificationException) No (gives ConcurrentModificationException) Yes
Syntax HashMap<String, String> hm = new HashMap<> (); HashMap<String, String> hm = Collections.synchronizedMap(new HashMap<> ()); HashTable<String, String> ht = new HashTable<> (); HashMap<String, String> hm = new ConcurrentHashMap<> ();
Null Keys and Null values Can insert one Null key & any no of Null values. Can insert one Null key & any no of Null values. Can’t insert Null keys and Null Values. Can insert one Null key & any no of Null values.
Performance Faster than remaining all. Less compare to HashMap, but same as HashTable. Less compare to HashMap, but same as Collections.synchronizedMap Less compare to HashMap.
Synchronized? No Yes, at Object level Yes, at Object level Yes, at HashMap bucket level.

====================================================================
Default Constructor vs Parameterized Constructor:
-> If you have Default Constructor in your class, when ever you create an object to the class, the default constructor will assign default values to the class objects (global variables). Note that even though you didn’t define default constructor in your class, compiler will creates it.
-> If your have Parameterized Constructor in your class, when ever you create an object to the class by passing parameters defined constructor then those values will be assigned to the global variables.

====================================================================
Flow when record is inserted into HashMap:
HashMap<Price, String> hm = new HashMap<>();
hm.put(new Price(10, “Oranges”),”Fruit Orange”);
Insert Record to HashMap using put-> Hashcode() method’ll be called to get hashcode for key where it stores key, value pair -> Internally it comapares Hashcode generated is already present in Bucket or not -> If already present enters equals(Object obj) method.
====================================================================
Sample Code:

package model;

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

public class Price {

int itemsCount;
String itemName;

Price(int item, String name) {
this.itemsCount = item;
this.itemName = name;
}
Price() {
}

public static void main(String[] args) {

HashMap&amp;amp;lt;Price, String&amp;amp;gt; hm = new HashMap&amp;amp;lt;&amp;amp;gt;();
hm.put(new Price(10, "Oranges"),"Fruit Orange");
hm.put(new Price(20, "Mangos"), "Fruit Mango");
hm.put(new Price(30, "Bananas"), "Fruit Banana");
hm.put(new Price(30, "Bananas"), "Fruit Fruit");
hm.put(new Price(40, "Grapes"), "Fruit Grapes");
System.out.println("size:"+hm.size());

for (Entry&amp;amp;lt;Price, String&amp;amp;gt; entry : hm.entrySet()) {
System.out.println("Key:" + entry.getKey() + " &amp;amp;amp; Value:" + entry.getValue());
}

/*Iterator&amp;amp;lt;Price&amp;amp;gt; keySetIterator = hm.keySet().iterator();
while(keySetIterator.hasNext()){
Object key = keySetIterator.next();
System.out.println("key: " + key+ " value: " + hm.get(key));
}&amp;amp;nbsp;&amp;amp;nbsp; &amp;amp;nbsp;*/
}

//Alt+Shift+S -&amp;amp;gt; Override/Implement methods

@Override
public String toString() {
return this.itemName+this.itemsCount;
//return "ravi";
}

@Override
public int hashCode() {
System.out.println("Hashcode entered..");
// TODO Auto-generated method stub
return new Integer(this.itemsCount).hashCode()+this.itemName.hashCode();
}

@Override
public boolean equals(Object obj) {
if(obj instanceof Price){
System.out.println("equals method..obj is instance of class");
Boolean b = ((Price)obj).itemName.equals(this.itemName) &amp;amp;amp;&amp;amp;amp; (((Price)obj).itemsCount==this.itemsCount);
return (b) ;
}
return false;
//return super.equals(obj);
}
}

Response:
Hashcode entered..
// When First record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
Hashcode entered..
// When Second record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
Hashcode entered..
// When third record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
Hashcode entered..
// When fourth record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
equals method..obj is instance of class
// After fourth record entered as hashcode genreated in fourth reocord is same as hashcode generated in third record, it enteres equals() method
Hashcode entered..
// When fifth record inserted it entered Hascode() method to get the Hashcode address for key where it stores Key& Value.
size:4  //here you can see only four records in HashMap as fourth record is overriden on third record address.
Key:Oranges10 & Value:Fruit Orange
Key:Bananas30 & Value:Fruit Fruit
Key:Mangos20 & Value:Fruit Mango
Key:Grapes40 & Value:Fruit Grapes

====================================================================
HashMap methods:
put(k,v), get(k), remove(k), size(), clear(), isEmpty(), containsKey(k), containsValue(v), entrySet(), keySet(), putAll(Map)
====================================================================
HashMap memory Allocation:
Default Size of HashMap: 16 and threshold is 0.75% i.e [0.75(16)=12]
So when you insert records in HashMap, when ever it reaches sixe of 12, then HashMap size will be extended to 12+16 = 28.
When ever the records in HashMap reaches [0.75(28)=21], then HashMap size will be extended to 21+16 = 35.
and so on the size wil be extended when ou keep on inserting records to HashMap.
====================================================================
// Do you know that you can not assign null value to int, if you do so, you’ll get NullPointer Exception. You can assign Null value to Integer.
Integer i = null;
int j = i;
System.out.println(“j”+j);  //java.lang.NullPointerException
====================================================================
Loop HashMap records:
/*  HashMap For Loop:
*  HashMap<Integer, String> hm = new HashMap<>();
*  for(Entry<Integer, String> m: hm.entrySet()){ }
*  for(Map.Entry<Integer, String> m:hm.entrySet()){  }
*  for(HashMap.Entry<Integer, String> m: hmap.entrySet()){ }
*  for(Entry m:hm.entrySet()){ } –without type casting
*  Inside for to get key and values -> m.getKey(), m.getValue()
*/

/*  HashMap Itertor and while Loop:
*  HashMap<Integer, String> hm = new HashMap<>();
*  Iterator<Price> keySetIterator = hm.keySet().iterator();
while(keySetIterator.hasNext()){
Object key = keySetIterator.next();
System.out.println(“key: ” + key+ ” value: ” + hm.get(key));
}
*/
====================================================================

HashMap References :
http://www.java2novice.com/java-collections-and-util/hashmap/iterate/
http://www.java2novice.com/java-collections-and-util/hashmap/

Overwrite toString() method in a Java class

  • The wrapper classes like ‘Integer’, ‘Double’, ‘Float’ will be having ‘toString()’ method in their classes. Implementation in that method is like they take input as respective type and return String value.
    eg: Integer i = 10;
    String ival = i.toString();
    Note that toString() method has the code to convert Integer to String.
  • You can not overwrite the toString() method of Integer class or any other wrapper classes. [you can’t extend Integer class as it is declared as Final. So you can not overwrite its toString() method. This applies to all wrapper classes.]
  • If you want to store your class object as key in map. you can do it, but when you try to print the keys present in the Map then it’ll return the hashcode of address where the class object stored in hash memory, instead returning exact key. So you need to overwrite the ‘toString()’ method to give your own implementation. By default toString() method returns hashcode, so by overwriting this method in your class you can return any value for the class object instead of its hashcode.
  • Check the below Java code.

package model;

import java.util.HashMap;
import java.util.Map.Entry;

public class Price {

int itemsCount;
String itemName;

Price(int item, String name) {
this.itemsCount = item;
this.itemName = name;
}

public static void main(String[] args) {
HashMap<Price, String> hm = new HashMap<>();
hm.put(new Price(10, "Oranges"), "Fruit Orange");
hm.put(new Price(20, "Mangos"), "Fruit Mango");
hm.put(new Price(30, "Bananas"), "Fruit Banana");
hm.put(new Price(30, "Grapes"), "Fruit Grapes");

for (Entry<Price, String> entry : hm.entrySet()) {
System.out.println("Key:" + entry.getKey() + " & Value:" + entry.getValue());
}

}

@Override
public String toString() {
return this.itemName+this.itemsCount;
//return "ravi";
}

}

 

Output if you don’t overwrite the toString() method:

Key:model.Price@7852e922 & Value:Fruit Banana
Key:model.Price@15db9742 & Value:Fruit Orange
Key:model.Price@6d06d69c & Value:Fruit Mango
Key:model.Price@4e25154f & Value:Fruit Grapes

Output after overwriting the toString() method:

Key:Bananas30 & Value:Fruit Banana
Key:Oranges10 & Value:Fruit Orange
Key:Mangos20 & Value:Fruit Mango
Key:Grapes30 & Value:Fruit Grapes

// If you return ‘ravi’ in toString() method then it’ll return ‘ravi’ as key for all records.

 

 

 

 

 

How to set ‘autoComplete’ property for html:text component in struts

If you are developing your jsp page using struts then, In few cases you get a requirement that while typing in an input filed it should not show the suggestions that previously entered.

So generally to achieve this we use the property ‘autoComplete=off’ for html input fields. But struts <html:text> doesn’t support this property. So to achieve this feature in struts we have three options.

1) Use normal html input component in the place of  struts html:text component.

<input type="text" value="" autoComplete="off" size="10" maxlength="10" name="Account" />

2) Use <html:text> in the following way that you set ‘autoComplete’ like a css injection. The below method can be used to set properties for the components which are not supported by struts html by default.


<html:text size="10" maxlength="10" property="Account" styleClass="\" autoComplete=\"off" />

3) Create a class extending Form class or Text class and add a custom property in it.

4) You can think of using jQuery also.

 

Exceptions in Java

There are many exceptions in Java. We can categorize them into two categories.

  1. Checked Exceptions (Which we can handle)
  2. UnChecked Exceptions (Which we can not handle- Run time)

Now let’s talk about each exception in Java.

Checked Exceptions: Remember that checked exceptions means the exceptions which we can handle. Few exceptions give error at compile time itself. Few exceptions doesn’t give exception at compile time but give at run time. But remember that what ever exceptions we can handle are checked exceptions. We do arithmetic operations and there might be a possibility to get exception if we pass zero to divide operation. So we can predict this error and can handle it with a catch block ArithmeticException or using throws ArithmeticException . We pass some values and execute some code and we have to predict what if the value passed is Null then we have to handle that using NullPointerException. So like these we have to predict the possibilities of getting and exception and have to handle them. If we can not predict the exceptions/ can not handle them then those are unchecked exceptions.

1. NoClassDefFoundException:

If the class reference is not available at runtime (though it is present at compile time and some how got deleted after that) then this error occurs. So this un cached exception as we can’t handle this exception.

2. ArithmeticException: Arithmetic error, such as divide-by-zero.

public static void main(String[] args) {
ArithMethod(40,0);
}
private static void ArithMethod(int a, int b) {
try{
int c = a/b;
}
catch(ArithmeticException ae){
System.out.println("Arithmetic Exception caught..");
}
}

3. NumberFormatException: Invalid conversion of a string to a numeric format.


try{
String v ="12j";
Integer inte = Integer.parseInt(v);
System.out.println("inte:"+inte);
}
catch(NumberFormatException nume){
System.out.println("NumberFormatException Caught...");
}

4. SecurityException: Attempt to violate security.

5. SqlException

6. ArrayIndexOutOfBoundsException: Array index is out-of-bounds


public static void main(String[] args) {

arrayBound();
}

private static void arrayBound() {
try{
int[] g = new int[3];
g[0] = 32;
g[1] = 26;
g[2] = 43;
g[3] = 61;
}
catch(ArrayIndexOutOfBoundsException AIOe){
System.out.println("ArrayIndexOutOfBoundsException Caught...");
}
}

7. StringIndexOutOfBoundsException: 

8. IndexOutOfBoundsException: Some type of index is out-of-bounds.

9. NullPointerException: Invalid use of a null reference.

Eg:


String s3=null;
try{
String s31 = new String(s3);
}
catch(Exception ne){
System.out.println("Null Pointer Exception Caught..");
}

I’ve listed few mostly used exceptions and There are few more catched exceptions in Java.

UnChecked Exceptions:

1. ClassNotFoundException:

If the class reference is not available at the time of compilation then this error occurs. So this is a compile time exception.

2. CloneNotSupportedException

Attempt to clone an object that does not implement the Cloneable interface.

3. IllegalAccessException

Access to a class is denied.

4. InstantiationException

Attempt to create an object of an abstract class or interface.

5. InterruptedException

One thread has been interrupted by another thread.

6. NoSuchFieldException

A requested field does not exist.

7. NoSuchMethodException

A requested method does not exist.

8. ResourceNotFoundException:

9. ResourceUnAvailableException:

Hexa to Decimnal conversion in Java

Have you ever tried to print the value of int i=0xbb; ? Do you think it’ll give numeric exception? No it works well and gives you the output of ‘187’. What is this value? It’s a decimal value of ‘bb’.

Well now coming to the point if you give value to integer starts with 0x (zero alphabet x) then jvm will convert the next value after prefix (assumes it as hex value) to decimal value. In the above example the hex value is ‘bb’ and its decimal value is ‘187’ which is then stored into integer. Want to cross check ? You can also do that calculation like below.

eg1: bb -> 11 X 160 + 11 X 161 = (11+176)= 187

eg2: bd -> 13 X 160 + 11 X 161 =(13+176)=189

Confused with Decimal and Hex values? Check below.

Hex             0     1     2     3     4     5     6     7     8     9     A       B     C       D      E       F
Decimal     0     1     2     3     4     5     6     7     8     9     10     11     12     13     14     15

Note: You can see decimal values for the alphabets a to f only. If you give any alphabet other than a to f then it’ll syntax error.

Leave your comments and suggestions in below comment section. Hope you enjoyed the post 🙂