Java String Interview Questions - 1

What is the output of following Java code:


public class TestString {

 public static void main(String[] args) {

     String str1 = "Hello";

     String str2 = new String("Hello");

     System.out.print(str2 == "Hello");

 }

}

Explanation:




Line 1: String str1 = "Hello";

Here String literal (object) is created in the String constant pool area of the heap memory. JVM see that it is string literal and there is no existing literal with that value in String constant pool, so it creates a new String literal with value "Hello" in the String constant pool. This is done by JVM for efficient usage of memory. The reference variable str1 refers(read have address of this String literal) to this String literal. 


Line 2: String str2 = new String("Hello");

Here as we are creating String object using new operator, JVM creates a new String object in heap with value "Hello". str2 refers to(or read have address of this newly created object in heap) to object in heap.


Line 3:  System.out.print(str2 == "Hello");

When we compare two object references using '==' , we are comparing whether two object references are pointing to same object in memory or not. If two object references are pointing to same object in memory or in other words if two object references have addresses of same object in memory, then result of comparing two object references using '==' will return true and if two object references have address of two different memory locations then comparison will return false.


so str1 == str2 would have returned false as str1 has address of String object in String constant pool and str2 has memory address of String object in heap and of course as two addresses are different, result of comparison will be false.

As in our case, we are comparing str2 (which is reference to String object in heap) with String literal "Hello" using '==', it is apparently comparing memory address of the String in heap(4444) with memory address of the String  literal "Hello" in String constant pool(5555), which is of course not equal, so answer will be false.



How to convert Array to List in Java

Hello Friends,

In this tutorial, we will learn, various ways in which we can convert an array to a List. 

How to convert String to int in Java


In this tutorial, we will see the various ways in which we can convert String to int(or Integer) in Java.

You can use any of the following ways :

- Using Integer.parseInt(string)
- Using Integer.valueof(string)
- Using Apache commons NumberUtils.toInt(string)
- Using Apache commons  NumberUtils.createInteger(string)
- Using Guava library's Ints.tryParse(string) method
- Using Integer.decode(string)
- Using new Integer(string)

Sorting a List having null values with Comparator's nullsFirst

Hello Friends,

In this tutorial, we will see how we can sort a list of items when few of the items are null in the list using Java 8 Comparator.nullsFirst, such that nulls are treated as smallest elements in the list.

- What is Comparator
- What is nullsFirst method doing in Comparator
- Sorting a list of Strings having non null names
- Sorting a list of Strings having names and Nulls without using nullsFirst
- Solving above problem by sorting the list using nullsFirst method
- Sorting a list of Custom objects without nulls
- Sorting a list of Custom objects with nulls without using nullsFirst
- Solving above problem by sorting the list using nullsFirst method
- Sorting the list having employee with name as null


Why We Should override hashCode method when we override equals method

Hello Friends,

In one of my previous post, I wrote about Why Should we override equals method in Java.In this article, let us try to find out Why overriding hashcode method is important when we override equals method.


Why Should we override equals method in Java

In this tutorial,we will try to understand need for overriding equals method in Java.

Can we overload or override main method in Java

Hello Friends,

In this tutorial, we will see whether we can overload or override main method in Java. This is very common interview question as well and the answer is really simple, if we don't overthink :)

Why we have private data and public getters setters to access them

It is common norm in Object oriented languages like Java to keep data which belongs to class as private and provide a public interface in the form of getter and setter method to access the data.

This wrapping up of data and methods which act on this data within single class has been named as encapsulation. In this post, let us try to understand what is the benefit we achieve out of keeping data private and with public getter ,setters to access data.




What does main method do in Java? Why main method is public,static,void?

Lets try to understand, What does main method do in Java?

main method is entry point(like main gate of your house) of your stand alone java application.Having said that it means that if we have a Java project(Not a Web Project) which has many classes in it with lot of code(business logic),you need some starting point such that your code starts executing.main method is this starting point or entry gate,which then can call other classes code.
Lets take an example to check how main method gets called and how it calls other method
package com.blogspot.javasolutionsguide;

public class TestClass {
    public static void main(String[] args) {
        System.out.println("In TestClass");
        System.out.println(new TestClass1().display());  // calling TestClass1 display method
    }
}
package com.blogspot.javasolutionsguide;
public class TestClass1 {
    public String display(){
        return "In TestClass1";
    }
}
Let us run TestClass from command prompt or from within eclipse
command prompt :
java TestClass
Eclipse : Right click on class having main method or right click on project name ,then select Run as -> Java Applicaiton
Output :
In TestClass
In TestClass1
Additional Info :
1) If you right click on a class which does not have main method ,eclipse will not show you Run as->Java application option.
2) If you remove any of public,static,void or arguments of main method,it will not be identified by JVM, but it will be considered as overload of main method and hence will not be called by JVM.So we need to be sure that we are using correct signature of main method,if we want JVM to call this method and below are the possible signatures of main method :

Before Java 5 :
public static void main(String[] args);
After Java 5 :
public static void main(String... args);
Or
public static void main(String[] args);
Why main method is public, static, void and with String array argument?
Why main method is Public :

There are four access modifiers in Java viz. private, default, protected, public.

Class members : Instance variables + methods 

private : Class members with private access modifier can be accessed only from within that same class.

So what if main method would have been private? It could not be called by JVM which calls main from outside the class containing main method, but methods with private access are accessible only from within that class.

default : There is no such keyword as such "default", but class members without any access modifier have default access which is also called as package-private access, which means that such class members can be accessed from any class which are within same package as the class whose members we want to access.

So what if main method would have been defined with default level access, it could still not be called by JVM, as methods with default access can only be accessed from classes which are in same package.

protected : class members with protected access can be accessed from any class within same package plus from subclasses outside the package.

So what if main method would have been defined with protected access, it could still not be called by JVM, as methods with protected access can be accessed only from classes within same package and subclasses outside package.
public : class members with public access can be accessed from any class outside the class, be it classes in same package or classes in different package.
Now as JVM is sitting somewhere outside of classes of your project, so to call main method of your project, main method must have public access.
why main method is static
As main method is invoked by JVM and by that time(when JVM invokes main method) no object of class in which main method is defined exists, there should be some way to call main method. This is the reason main method has been forced by java specifications to be static. Now as static methods belong to class(and not objects),it can be called by JVM using class name.

why main method has void return type

As main method does not need to return anything to JVM, return type of main method is void.

What is the use of String array arguments in main method

main method accepts array of String. These are called command line arguments.
Consider following example :
package com.blogspot.javasolutionsguide;

public class TestClass {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println("In TestClass");
    }
}
So if you are executing java program from command prompt as below :
java TestClass "hello"
Output will be :
hello
in TestClass
If you want to pass more than 1 argument, you can do like
Consider following example :
package com.blogspot.javasolutionsguide;

public class TestClass {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println(args[1]);
        System.out.println("In TestClass")
    }
}
java TestClass "hello" "Quora"
and output will be
hello
Quora
in TestClass
This was just an example. In real projects you can pass some relevant arguments which will be required to your application at start up.
For example ,you can pass name of the applicationContext file(xml) in application using Spring,which then can be used in main method to load applicationContext.
Hope this article was helpful.If you have any comments,feedback,please dont hestitate to provide same in below comments section.

How to make object eligible for garbage collection

Dear Friends,

In this tutorial I would try to explain what is garbage collection in Java and How to make objects eligible for Garbage collection.

In the language like C, a programmer need to manually do the memory management himself/herself by allocating memory programmatically and then de-allocating memory programmatically, but Java provides automatic memory management facility, wherein a programmer need not take care of allocating/de-allocating memory, but there is utility which is part of JVM which do it for programmer automatically and we call is as Mr. Garbage Collector. Don't go on its name, it's a big guy actually, which does pretty decent job for programmer :)


What are Exceptions and types of Exceptions in Java

Hi Friends,

In this tutorial I would try to explain what are exceptions and types of exceptions in Java.

What are Exceptions?

Exception as its name suggest is the exceptional flow in your program rising due to the unexpected run time condition. For Example : FileNotFoundException. You may have written a code which would be reading a file placed at file system and source of that file is some other system. While writing code you are expecting that file at that particular location will always be there, but it is possible due to some issue in another system, that system or application would not have placed file at that location, which will result in FileNotFoundException in your program. Now this is a exceptional flow, as in normal or happy scenario, file would have been there and your program would have read the file and would have exit gracefully. Now you would like your program to complete gracefully if such kind of exceptional scenario arises. For that you can surround your code which is prone to exception by try block and can handle exceptional scenario in Catch block.

Java 7 language features - Try with Resources statement

Hi Friends,

Java has come up with really cool features in version 1.7.Code was named as Dolphin and released on July 28,2011.If you are interested in knowing history of all Java releases, you can go throw my earlier post History of java language.                                      


Writing your first Java Program

Hello Friends,

If you have come to this page so that means you are Java enthusiast and looking forward to learn Java. Let me tell you Java is very easy to learn, if you learn some core concepts well.

Okay, Let us create a Java project and write a java program step by step as follow :

How to get value of xml tags from a File

Hi Friends,

Sometime back I cam across situation where I had a very big file(it was log file actually) having multiple xml requests on multiple lines,so that means one xml request per line and I wanted to get values from one particular tag from each request.So I wrote program mentioned in below post,which gave me FileNames from each request.

Let us see now how we can get value of  xml tags from a big file.