Prev Next

Java / Strings

Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. String in Java.

String is a class that helps represent sequence of characters, defined in java.lang package.

2. isEmpty()

This non-static method of any String object returns true when length of the String is zero. This method does not check for null and if the string is null then it throws NullPointerException.

3. What is toString() method?

Returns a string representation of an(y) object. The toString() method returns a string that textually represents this object.

The toString method for any Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

package org.javatutorials.StringBased;

public class Employee {
	
	private String firstName;
	
	private String lastName;
	
	private int age;
	

	public String getFirstName() {
		return firstName;
	}


	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}


	public String getLastName() {
		return lastName;
	}


	public void setLastName(String lastName) {
		this.lastName = lastName;
	}


	public int getAge() {
		return age;
	}


	public void setAge(int age) {
		this.age = age;
	}


	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.setFirstName("Kelly");
		emp.setLastName("Scott");
		emp.setAge(40);
		
		System.out.println(emp);
	}

}

Output

org.javatutorials.StringBased.Employee@6ae6235d

Overriding toString() method yields desired and more readable output of the object.

4. Difference between String, StringBuffer and StringBuilder.

String object is immutable whereas StringBuffer and StringBuilder objects are mutable.

StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.

5. Is String interning an example of flyweight design pattern?

Yes.

6. All the String objects created using String literals are stored in String pool?

Yes.

7. Difference between StringBuffer and StringBuilder.

All the methods in StringBuffer is synchronized whereas in StringBuilder, it is not synchronized.

StringBuffer is threadsafe while StringBuilder is not. If you need to manipulate a string in a single thread, use StringBuilder instead.

8. How to create our own immutable class in Java?
  • Do not provide any setters.
  • Mark all fields as private.
  • Make the class final.
9. Other examples of Immutable classes.
  • java.lang.StackTraceElement
  • java.io.File
  • java.util.Locale
10. Can String be referred as a datatype?

Yes. However it is derived datatype (Predefined object) and not the primitive data type like int, char, boolean etc.

11. What is Immutable?

An object is considered to be immutable if its state cannot be altered once it is created.

12. Is String is Immutable?

Yes. It is also final.

13. How do you create a String object?

We can create String object using new operator like any other class. Alternatively you can create by assigning String literals using double quote.

14. What is the difference between creating String object using new and String literals?

When a String object is created using String literals, JVM searches at the String pool to find if any other String object is stored already with the same value. If found, it returns the reference to that String object from String pool otherwise it creates a new String object with given value and stores it in the String pool.

When we use new operator, JVM creates the new String object but don’t store it into the String Pool or try to reuse the existing objects with same value.

15. String Interning.

The method of storing only one copy of each distinct string value, which must be immutable. The distinct values are stored in a string intern pool. string intern pool allows a runtime to save memory by preserving immutable strings in a pool so that areas of the application can reuse instances of common strings instead of creating multiple instances of it.

16. Java String Pool.

The String Constant pool is the JVM's implementation of the string interning. String Pool is a pool of Strings stored in Java Heap Memory.

17. Explain Flyweight Pattern.

Flyweight is a Structural design pattern that helps minimizes memory use by sharing as much data as possible with other similar objects String interning is an example of flyweight design pattern.

18. String Literal in Java.

It is a representation of a sequence of characters or string value enclosed in double quotes. e.g. "Example String Literal"

19. Immutable objects are thread-safe?

Yes. Because immutable objects can not be changed.

20. Overriding toString() example.

In the above Employee example, overriding toString() method makes clean and understandable result.

package org.javatutorials.StringBased;

public class Employee {
	
	private String firstName;
	
	private String lastName;
	
	private int age;
	

	public String getFirstName() {
		return firstName;
	}


	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}


	public String getLastName() {
		return lastName;
	}


	public void setLastName(String lastName) {
		this.lastName = lastName;
	}


	public int getAge() {
		return age;
	}


	public void setAge(int age) {
		this.age = age;
	}

	public String toString() {
		return "Employee name: " + getFirstName() + " " + getLastName() + " and his age: " + age;
		
	}

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.setFirstName("Kelly");
		emp.setLastName("Scott");
		emp.setAge(40);
		
		System.ot.println(emp);
	}

}

Output: Employee name: Kelly Scott and his age: 40

21. Why does the default Object.toString() include the hashcode?

The object hash code is the only standard identifier that might allow you to tell different arbitrary objects apart in Java. It's not necessarily unique, but equal objects normally have the same hash code.

22. Why String is often used as key in HashMap?

Immutability nature of String objects prevent hash collision is HashMap.

23. What is String interpolation in Java?

It is the process of evaluating a string literal containing one or more placeholders, yielding a result where placeholders are replaced with its corresponding values.

24. How to perform String interpolation?

Java 5 or higher has String.format() method which supports String interpolation.

String completeString += String.format("str1=%s;str2=%s;str3=%s;str4=%s;", str1, str2, str3, str4);

25. Name the interfaces that Java String class implements.

String implements Serializable and Comparable interfaces.

26. How do I compare strings in Java?

== tests for reference equality to find whether they are the same object. equals() tests for value equality to find whether they are logically "equal".

27. Can we use Java String in switch case?

Java 7 extended the capability of switch case to use Strings also.

    String month = "january";
    switch (month) {
        case "january":
            monthNumber = 1;
            break;
        case "february":
            monthNumber = 2;
            break;
        case "march":
            monthNumber = 3;
            break;
        
        default: 
            monthNumber = 0;
            break;
    }

    return monthNumber;
28. Can we have case null in string switch case?

No. case null is not allowed per design. Use if condition before switch to handle null.

switch statement will throw NullPointerException when it evaluate null.

29. Where are the string created with the toString() method in memory?

It is based on jvm implementation per object. Usually toString method creates object in heap.

Integer.toString() method creates in heap but not for all toString() methods. Boolean.toString(), for example, returns strings from the string pool.

30. Which design pattern is based on object cloning?

Prototype design pattern.

31. Where CloningNotSupportedException starts? (Or) Where object is instanceof Cloneable is checked?

This is not a common interview question. However one of my colleagues faced this question when the interviewer dived deep into marker interface. If anyone has the correct answer, kindly leave on the comment with your name. Thank you.

32. What is the default implementation of equals method in Object class.

The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal.

«
»
Using String

Comments & Discussions