Search This Blog

Wednesday, May 22, 2019

Internal Working of 'ValueOf' method from String class

Today I got to fix a bug which was related to below scenario and not easy to find out easily. So let's check your understanding on this.

Let's guess the output of below program-

//Code snippet
String str= null;
String resultString = String.valueOf(str);

if(resultString != null && !resultString.isEmpty()){
      System.out.println("String is not empty");
      System.out.println("String is  empty or null");

Its better to understand the process behind this result. So lets explore the execution happening behind valueOf method.

So static method 'valueOf' of String class just return the string as "<input passed to this method>". In the above case you will get a "null" string as output and hence 'If' block gets executed.

Please comment in comment box if you have any query regarding this post.

No comments :

Post a Comment