Skip to main content

Posts

Showing posts with the label java

Generics wild card in java

List<Double> or List<Float> cannot be assigned to List<Number> because, List<Double> isn't extend List<Number>. List<Double> dblList = new ArrayList<>(); List<Number> numList = dblList; //illegal To do that we need to use upper-bound wild card. List<Double> dblList = new ArrayList<>(); List<? extends Number> numList = dblList; Same way List<Number> isn't extend List<Object> so, List<Object> cannot be assigned to List<Number> List<Object> objList = new ArrayList<>(); List<Number> numList = objList; //illegal To do that we need to use lower-bound wild card List<Object> objList = new ArrayList<>(); List<? super Number> numList = objList; Upper-bound We can add object of Double type or its sub types to List<Double>. Same way we can add Number or its sub types (e.g. Double, Float, Integer) to List<Number> but, we cannot assign dblLis...

synchronized, wait() and notify() in java

synchronized keyword in java used to make sure that the code block would be executed by one and only one thread at a time. Using the keyword one can write a code block which would be side effects free from other concurrently running thread. There are two way we can use the keyword: 1) synchronized block and 2) synchronized method. synchronized (lockingObject) {     // code which must be executed by single thread at a time. } public synchronized void doWork () {     // code which must be executed by single thread at a time. } The synchronized block locks on lockingObject whereas synchronized method locks on object of that method ( this ). Good example of this is to achieve singleton pattern. public class Singleton {     private static Singleton s;     public static Singleton getInstance () {         if ( s == null ) {             synchronized (Singleton.class) {    ...

Why String is immutable in java?

The question asked lot of time to lot of people. Each has some reasons for immutability of java strings. Java has primitive types which are inherently immutable. int i = 0; void changeValue(int val) {     val = 1; } changeValue(i); Value of "i" is still 0. The same way strings are just sequence of character. It should be primitive as well. It brings peace of mind with it. As primitive has + and - operations strings also have concatenation and substring operations. String is not primitive so java has workaround for it and made it feels like primitive. All this lead us to immutable string object. The same rules applied to other java objects like. All wrapper classes (Integer, Float etc.), BigDecimal, BigInteger, Color etc.