Java – Interview program on String using null

In this article, we will discuss a sample program on String which is commonly asked to test skill on String

Q) What will be output of below program ?

package in.bench.resources.string.test;

public class TestString {

	public static void main(String[] args) {

		String str1 = null;
		str1 = str1 + " Infosys";
		System.out.println(str1);
	}
}

Output:

null Infosys

Explanation:

  • Initially, String str1 is initialized with null
  • In the next step at line no. 8, a concatenation operation performed on the same String str1 using “+” operator
  • So, now it will be interesting to see what will be exact output,
  • as one may consider that it will simply print only “ Infosys” leaving null part
  • But while printing after concatenation for String str1 where it will prefix String literal null
  • And finally print along with null i.e.; “null Infosys”

Interview program to suffix null

  • On the same line, we can expect below program where instead of prefixing null, program to suffix null
package in.bench.resources.string.test;

public class TestString {

	public static void main(String[] args) {

		String str1 = null;
		str1 = "Infosys " + str1;
		System.out.println(str1);
	}
}

Output:

Infosys null

Hope, you found this article very useful. Share with us interesting interview program you have faced during your interview hours. We will publish those article here along with its solution.

Related Articles:

Suggest tutorials from Contact Us page

Happy Coding !!
Happy Learning !!

Java - Interview program on static method
Java 5 - Generics interview question and answers