Friday, July 22, 2016

String is Immutable and property hash is not final




How is that possible? We have read all over the internet that all properties must be final to make a class immutable.

Well it is possible but with some rules/restrictions and that is access to mutable properties/fields must provide same result every time we access it.

In String class hashcode actually calculated on the final array of characters which is not going to change if String has constructed. Therefore immutable class can contain mutable fields/properties but it has to make sure that access to field/property will produce the same result every time it is accessed.

Can we create a immutable class without marking it as final?

Most of java developers (may be 90%) will answer this question with a big "NOooo" and its absolutely fine to answer with a big "NOooo" because its written everywhere on internet that for a class to be immutable it must be final but surprisingly we can create a immutable class without declaring it as final.

So the answer of the above question is "YES" we can create a immutable class without making it as final but how???

Let me tell you one of such example from java classes itself  "BigInteger" class is immutable but its not final



As marked in red BigInteger is not a final class.

Let's test BigInteger's immutability now

Since BigInteger is immutable therefore the output of the above program will be 0.

Actually Immutability is a concept according to which ones the object created then it can not be modified.

Let's think from JVM point of view, from JVM point of view all threads must share the same copy of the object and it is fully constructed before any thread accesses it and the state of the object doesn't change after its construction.

Immutability means there is no way yo change the state of the object once it is created and this is achieved by three thumb rules which makes the compiler to recognize that class is immutable and they are as follows :-

  • all non private fields should be final
  • make sure there is no method in the class that can change the fields of the object either directly or indirectly
  • any object reference defined in the class can't be modified outside from the class

Therefore for creating immutable class it is not mandatory to mark the class as final.

Static methods are redefined not overidden...

What will be out put of the following program?
--------------------------------------------------------------
class StaticSuper {
 public static void m1() {
  System.out.println("Super m1");
 }
 public void m2() {
  System.out.println("Super m2");
 }
 public void m3() {
  m1();
  m2();
 }
}
class StaticSub extends StaticSuper {
 public static void m1() {
  System.out.println("Sub m1");
 }
 public void m2() {
  System.out.println("Sub m2");
 }
}
public class Test {
 public static void main(String args[]) {
  StaticSuper ss = new StaticSub();
  ss.m3();
 }
}
--------------------------------------------------------------
Output of the following program will be :
Super m1
Sub m2

The output of the above program proves that Static methods are not overridden they are redefined.
If you try to override the static method then it will be treated as a non overridden method of the sub class. Static methods will be called based on the type of the reference not the object created.


Monday, August 10, 2015

Defining Map to maintain counter on key basis


Most of the time if we have to maintain a counter on key basis then we define a map as follows
Map<String, Integer> map = new HashMap<String, Integer>();
Do we have any problem with the above statement???
Yes, the problem is with value but what's the problem with Integer as a value?
We have defined Integer object as a value and Integer is an immutable class so whenever we perform operation on the value (increment or decrement) a new Integer object will be created this is where the problem lines in, after increment/decrement n number of time we might have created n number of objects.
So whats the solution for the above problem
1) A very simple solution is to define a bean and take primitive int/long/double (whatever datatype you want) and based on the key increment/decrement the values in the bean object and provide getters to get the Count.
2) We can use AtomicInteger because its mutable.
Keep exploring Java smile emoticon
Now a days, a very simple but tricky question "How to Prevent Method Overriding in Java" is asked in interview.
Many of us just answer that final keyword is used to prevent overriding but there are 2 more ways to prevent overriding.
1. final
2. private
3. static
Generally, we answered only first one i.e. final keyword but make sure to answer properly (mentioned all 3 ways) to impress interviewer. Interviewer knows that all are familiar with final and they ask this question to know whether you know about other 2 ways or not.
So, don't take this question easily and make sure to explain all three, if this question is asked in interview.
Keep exploring Java.
Why are all OS built by C, C++ etc.? Why not Java?

Because Java itself requires JVM to ensure platform independence. So, lets assume you code an OS using Java. Now, if you start thinking recursively, your OS requires JVM to run, JVM requires OS, OS requires JVM, JVM requires OS.. infinite mutual recursion.
System Stack Overflow! grin emoticon
On a serious note, Java is just not designed for system programming. C is more effective when you require direct interaction with the hardware and memory but Java doesn't allow interaction with hardware/memory. You will understand it even better if you get your hands dirty on some system programming with C/C++.
Even, OS can't be built 100% in Java but it can be built with the mixture of Java and C/C++. Just write some part of OS in C/C++ that would be sufficient to start the JVM then rest of the OS could be written in Java.
Examples of attempts at such an operating system include JavaOS, JOS,[2] JNode, and JX.

Friday, November 21, 2014

Empty String Check

Most of the time we prefer equals method to check whether string is empty or not like in the below method we are checking string with equals method which is returning true or false depending on the String input.



But is it the optimized way to check string?

And the answer is no there is one more way to check whether string is empty or not like in below method we are checking length of string which will perform much better than equals method.




Here is the sample program :-

public class EmptyString {

            public static void main(String[] args) {
                        long startTime = System.currentTimeMillis();
                        for (long i = 0; i < 8300000; i++) {
                                    isEmptyEquals("");
                        }
                        long endTime = System.currentTimeMillis();

                        System.out.println("Time taken by equals check method(in milliseconds) : " + (endTime - startTime) + "ms");

                        startTime = System.currentTimeMillis();
                        for (long i = 0; i < 8300000; i++) {
                                    isEmptyLength("");
                        }
                        endTime = System.currentTimeMillis();
                        System.out.println("Time taken by length check method(in milliseconds) : " + (endTime - startTime) + "ms");
            }

            public static boolean isEmptyEquals(String str) {
                        return str == null || str.equals("");
            }

            public static boolean isEmptyLength(String str) {
                        return str == null || str.length() == 0;
            }

}

And the output of the above program is (on my machine)

Time taken by equals check method(in milliseconds) : 119ms
Time taken by length check method(in milliseconds) : 35ms


In Java 6 isEmpty method is added in String class which checks length to verify that String is empty or not. Therefore if we are working on java version 6 or greater than 6 then we can use isEmpty method of String class.
Snapshot taken from String class