What is String in
Java? Is String is data type?
String is a Class
in java and defined in java.lang package. It’s not a primitive data type like
int and long. String class represents character Strings.
Is String a
keyword in java?
No. String is not
a keyword in java. String is a final class in java.lang package which is used
to represent the set of characters in java.
Is String a
primitive type or derived type?
String is a
derived type.
In how many ways
you can create string objects in java?
There are two
ways to create string objects in java. One is using new operator and another
one is using string literals.
The objects
created using new operator are stored in the heap memory and objects created
using string literals are stored in string constant pool.
String s1 = new
String("abc");
//Creating string object using new operator
String s2 =
"abc"; //Creating string
object using string literal
Why String is
different from all other data types in Java?
In Java there are
primitive data types and class data types. One problem with primitive data
types is that they have a fixed data size. Since strings vary in length, many
languages that have primitive data types have implemented a string class that
can deal with data of any size, since it can allocate as much memory as it
needs. So this is why. There are also class versions of the primitive data
types in Java, which add methods that can be useful in manipulating the data
they hold, e.g. Integer, Double and so on.
What is String
literal pool? How to create a String?
The String
Constant Pool
It is a special place where the collection of
references to string objects are placed.
Let us first write a program to understand
object comparison and references
public class
StringConstantPool {
public static void main(String[] args) {
String s = "prasad";
String s2 = "prasad";
System.out.println(s.equals(s2));
System.out.println(s == s2);
}
}
The output of the
above code is
true
true
Now lets know
what happens here step by step
The class is
loaded when JVM is invoked.
JVM will look for
all the string literals in the program
First, it finds
the variable s which refers to the
literal “prasad” and it will be created in the memory
A reference for
the literal “prasad” will be placed in the string constant pool memory.
Then it finds
another variable s2 which is referring to the same string literal “prasad“.
Now that JVM has
already found a string literal “prasad“, both the variables s and s2 wil refer
to the same object i.e. “prasad“.
The diagram below
demonstrates this
Now we have looked
into the case when string literals are created without using the new operator.
What happens if String s2 = new ("prasad");
As we are
invoking the new keyword, The object “prasad” will be created when the new
String(“prasad”) is invoked. This is unlike the string literal “prasad” which
is created when class is loaded.
Now the values of
objects referenced by variable s and variable s2 are the same i.e. “prasad” but
those are not the same objects. They refer to different objects. We will verify
this with a program
public class
StringConstantPool {
public static void main(String[] args) {
String s = "prasad";
String s2 = new
String("prasad");
System.out.println(s.equals(s2));
System.out.println(s == s2);
}
}
This outputs,
true
false
The contents of
both objects are the same so equals method returns true
The objects
referred by both variables are different so == operator returns false
This is
elaborated in this diagram
Points to be
remembered
String literals
with same values will always refer to the same String object
String objects
created using new operator will be different from literals
What is the
reason to make String as Immutable or Final?
String immutable
Benefits
1. String pool is
possible only because String is immutable in java, this way Java Runtime saves
a lot of java heap space because different String variables can refer to same
String variable in the pool. If String would not have been immutable, then
String interning would not have been possible because if any variable would
have changed the value, it would have been reflected to other variables also.
2. If String is
not immutable then it would cause severe security threat to the application.
For example, database username, password are passed as String to get database
connection and in socket programming host and port details passed as String.
Since String is immutable it’s value can’t be changed otherwise any hacker
could change the referenced value to cause security issues in the application.
3. Since String
is immutable, it is safe for multithreading and a single String instance can be
shared across different threads. This avoid the usage of synchronization for
thread safety, Strings are implicitly thread safe.
4. Strings are
used in java classloader and immutability provides security that correct class
is getting loaded by Classloader. For example, think of an instance where you
are trying to load java.sql.Connection class but the referenced value is
changed to myhacked.Connection class that can do unwanted things to your
database.
5. Since String
is immutable, its hashcode is cached at the time of creation and it doesn’t
need to be calculated again. This makes it a great candidate for key in a Map
and it’s processing is fast than other HashMap key objects. This is why String
is mostly used Object as HashMap keys.
What is a String
Buffer>
StringBuffer is
mutable means one can change the value of the object . The object created
through StringBuffer is stored in the heap . StringBuffer has the same methods as the StringBuilder ,
but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this it
does not allow two threads to
simultaneously access the same method . Each method can be accessed by one
thread at a time .
But being thread
safe has disadvantages too as the performance of the StringBuffer hits due to
thread safe property . Thus
StringBuilder is faster than the StringBuffer when calling the same
methods of each class.
StringBuffer
value can be changed , it means it can be assigned to the new value . Nowadays
its a most common interview question ,the differences between the above classes
.
String Buffer can
be converted to the string by using toString() method.
StringBuffer
demo1 = new StringBuffer("Hello") ;
// The above
object stored in heap and its value can be changed .
demo1=new
StringBuffer("Bye");
// Above
statement is right as it modifies the value which is allowed in the
StringBuffer.
What is a String
Builder?
StringBuilder is same as the StringBuffer , that is it
stores the object in heap and it can also be modified . The main difference between
the StringBuffer and StringBuilder is that StringBuilder is also not thread
safe.
StringBuilder is
fast as it is not thread safe .
StringBuilder
demo2= new StringBuilder("Hello");
// The above
object too is stored in the heap and its value can be modified
demo2=new
StringBuilder("Bye");
// Above
statement is right as it modifies the value which is allowed in the
StringBuilder.
What is the
difference between String and String Buffer?
The basic
difference between String and StringBuffer class is String is immutable(means
value stored in string object cannot be changed) where as StringBuffer is not.
Whenever you do
any changes to your String object,it creates a new string object and does not
change the existing object.
For ex:
So suppose you
declare a String object:
String test=
“Hello”;
Next, you want to
append “Guest” to the same String. What do you do?
test=test+"Guest";
When you print
the contents of test the output will be “Hello Guest”. Although we made use of
the same object(test), internally a new object was created in the process. So,
if you were to do some string operation involving an append or trim or some
other method call to modify your string object, you would really be creating
those many new objects of class String.This creates a performance issue.
In order to avoid
this performance issue ,we use StringBuffer/StringBuilder class to efficiently
use append and other string operations.
String
StringBuffer StringBuilder
------------------------------------------------------------------------------------------------------
Storage Area | Constant String Pool Heap Heap
Modifiable | No (immutable) Yes( mutable ) Yes( mutable
------------------------------------------------------------------------------------------------------
Storage Area | Constant String Pool Heap Heap
Modifiable | No (immutable) Yes( mutable ) Yes( mutable
Thread Safe
| Yes
Yes
No
Performance | Fast Very slow Fast
------------------------------------------------------------------------------------------------------
Performance | Fast Very slow Fast
------------------------------------------------------------------------------------------------------
How do you
compare two String in Java?
or
How to compare
strings? Use "==" or use equals()?
Or
Can we compare
String using == operator? What is the risk?
Use the
string.equals(Object other) function to compare strings, not the == operator.
The function
checks the actual contents of the string, the == operator checks whether the
references to the objects are equal.
Can we use string
for switch statement?
Java (before
version 7) does not support String in switch/case. But you can achieve the
desired result by using an enum.
private enum
Fruit {
apple, carrot, mango, orange;
}
String value; //
assume input
Fruit fruit =
Fruit.valueOf(value); // surround with try/catch
switch(fruit) {
case apple:
method1;
break;
case carrot:
method2;
break;
// etc...
}
How To Convert a
String to an int?
String s = "123";
int i = Integer.parseInt( s );
What Substring
does?
The substring(int
beginIndex, int endIndex) method in JDK 6 and JDK 7 are different.substring()
represent the substring(int beginIndex, int endIndex) method.
Substring shares
same character array as original String which can create a memory leak if
original String is quite big and not required to retain in memory but
unintentionally retained by substring which is very small in size and prevents
large array from begin claimed during Garbage collection in Java.
What substring()
does?
The substring(int
beginIndex, int endIndex) method returns a string that starts with beginIndex
and ends with endIndex-1.
System.out.println(x);
Output:
Bc
What happens when
substring() is called?
You may know that
because x is immutable, when x is assigned with the result of x.substring(1,3),
it points to a totally new string like the following:




No comments:
Post a Comment