Java / Strings
instanceof
Cloneable is checked?
32.
What is the default implementation of equals method in Object class.
String is a class that helps represent sequence of characters, defined in java.lang package.
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.
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@6ae6235dOverriding toString() method yields desired and more readable output of the object.
String object is immutable whereas StringBuffer and StringBuilder objects are mutable.
StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
Yes.
Yes.
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.
- Do not provide any setters.
- Mark all fields as private.
- Make the class final.
- java.lang.StackTraceElement
- java.io.File
- java.util.Locale
Yes. However it is derived datatype (Predefined object) and not the primitive data type like int, char, boolean etc.
An object is considered to be immutable if its state cannot be altered once it is created.
Yes. It is also final.
We can create String object using new operator like any other class. Alternatively you can create by assigning String literals using double quote.
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.
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.
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.
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.
It is a representation of a sequence of characters or string value enclosed in double quotes. e.g. "Example String Literal"
Yes. Because immutable objects can not be changed.
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
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.
Immutability nature of String objects prevent hash collision is HashMap.
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.
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);
String implements Serializable and Comparable interfaces.
== tests for reference equality to find whether they are the same object. equals() tests for value equality to find whether they are logically "equal".
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;
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.
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.
Prototype design pattern.
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.
The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal.