Vous êtes sur la page 1sur 98

10 Things Every Java Programmer Should

Know about String


String in Java is very special class and most frequently used class as well. There are lot
many things to learn about String in Java than any other class, and having a good
knowledge of different String functionalities makes you to use it properly. Given
heavy use of Java String in almost any kind of project, it become even more important
to know subtle detail about String. Though I have shared lot of String related article
already here in Javarevisited, this is an effort to bring some of String feature together.
In this tutorial we will see some important points about Java String, which is worth
remembering. You can also refer my earlier post 10 advanced Java String questions to
know more about String. Though I tried to cover lot of things, there are definitely few
things, which I might have missed; please let me know if you have any question or
doubt on java.lang.String functionality and I will try to address them here.

1) Strings are not null terminated in Java.


Unlike C and C++, String in Java doesn't terminate with null character. Instead String
are Object in Java and backed by character array. You can get the character array used
to represent String in Java by calling toCharArray() method of java.lang.String
class of JDK.

2) Strings are immutable and final in Java


Strings are immutable in Java it means once created you cannot modify content of
String. If you modify it by using toLowerCase(), toUpperCase() or any other
method, It always result in new String. Since String is final there is no way anyone can
extend String or override any of String functionality. Now if you are puzzled why String is
immutable or final in Java. checkout the link.

3) Strings are maintained in String Pool

As I Said earlier String is special class in Java and all String literal e.g. "abc"
(anything which is inside double quotes are String literal in Java) are maintained in a
separate String pool, special memory location inside Java memory, more precisely
inside PermGen Space. Any time you create a new String object using String literal,
JVM first checks String pool and if an object with similar content available, than it
returns that and doesn't create a new object. JVM doesn't perform String pool check if
you create object using new operator.

You may face subtle issues if you are not aware of this String behaviour , here is an
example
String name = "Scala"; //1st String object
String name_1 = "Scala"; //same object referenced by name variable
String name_2 = new String("Scala") //different String object

//this will return true


if(name==name_1){
System.out.println("both name and name_1 is pointing to same string
object");
}

//this will return false


if(name==name_2){
System.out.println ("both name and name_2 is pointing to same string
object");
}

if you compare name and name_1 using equality operator "==" it will return true
because both are pointing to same object. While name==name_2 will return false
because they are pointing to different string object. It's worth remembering that equality
"==" operator compares object memory location and not characters of String. By
default Java puts all string literal into string pool, but you can also put any string into
pool by calling intern() method of java.lang.String class, like string created
using new() operator.

4) Use Equals methods for comparing String in Java


String class overrides equals method and provides a content equality, which is based on
characters, case and order. So if you want to compare two String object, to check
whether they are same or not, always use equals() method instead of equality
operator. Like in earlier example if we use equals method to compare objects, they will
be equal to each other because they all contains same contents. Here is example of
comparing String using equals method.
String name = "Java"; //1st String object
String name_1 = "Java"; //same object referenced by name variable
String name_2 = new String("Java") //different String object

if(name.equals(name_1)){
System.out.println("name and name_1 are equal String by equals
method");
}

//this will return false


if(name==name_2){
System.out.println("name_1 and name_2 are equal String by equals
method");
}

You can also check my earlier post difference between equals() method and ==
operator for more detail discussion on consequences of comparing two string using ==
operator in Java.

5) Use indexOf() and lastIndexOf() or matches(String regex) method to search


inside String
String class in Java provides convenient method to see if a character or sub-string or a
pattern exists in current String object. You can use indexOf() which will return
position of character or String, if that exist in current String object or -1 if character
doesn't exists in String. lastIndexOf is similar but it searches from end.
String.match(String regex) is even more powerful, which allows you to search
for a regular expression pattern inside String. here is examples of indexOf,
lastIndexOf and matches method from java.lang.String class.

String str = "Java is best programming language";

if(str.indexOf("Java") != -1){
System.out.println("String contains Java at index :" +
str.indexOf("Java"));
}

if(str.matches("J.*")){
System.out.println("String Starts with J");
}

str ="Do you like Java ME or Java EE";

if(str.lastIndexOf("Java") != -1){
System.out.println("String contains Java lastly at: " +
str.lastIndexOf("Java"));
}

As expected indexOf will return 0 because characters in String are indexed from zero.
lastIndexOf returns index of second “Java”, which starts at 23 and matches will
return true because J.* pattern is any String starting with character J followed by any
character because of dot(.) and any number of time due to asterick (*).

Remember matches() is tricky and some time non-intuitive. If you just put "Java" in
matches it will return false because String is not equals to "Java" i.e. in case of plain
text it behaves like equals method. See here for more examples of String matches()
method.

Apart from indexOf(), lastIndexOf() and matches(String regex) String also


has methods like startsWith() and endsWidth(), which can be used to check an
String if it starting or ending with certain character or String.
6) Use SubString to get part of String in Java
Java String provides another useful method called substring(), which can be used
to get parts of String. basically you specify start and end index and substring()
method returns character from that range. Index starts from 0 and goes till
String.length()-1. By the way String.length() returns you number of
characters in String, including white spaces like tab, space. One point which is worth
remembering here is that substring is also backed up by character array, which is used
by original String. This can be dangerous if original string object is very large and
substring is very small, because even a small fraction can hold reference of complete
array and prevents it from being garbage collected even if there is no other reference for
that particular String. Read How Substring works in Java for more details. Here is an
example of using SubString in Java:

String str = "Java is best programming language";

//this will return part of String str from index 0 to 12


String subString = str.substring(0,12);

System.out.println("Substring: " + subString);

7) "+" is overloaded for String concatenation


Java doesn't support Operator overloading but String is special and + operator can be
used to concatenate two Strings. It can even used to convert int, char, long or
double to convert into String by simply concatenating with empty string "". internally +
is implemented using StringBuffer prior to Java 5 and StringBuilder from Java
5 onwards. This also brings point of using StringBuffer or StringBuilder for
manipulating String. Since both represent mutable object they can be used to reduce
string garbage created because of temporary String. Read more about StringBuffer vs
StringBuilder here.

8) Use trim() to remove white spaces from String


String in Java provides trim() method to remove white space from both end of String.
If trim() removes white spaces it returns a new String otherwise it returns same
String. Along with trim() String also provides replace() and replaceAll()
method for replacing characters from String. replaceAll method even support regular
expression. Read more about How to replace String in Java here.

9) Use split() for splitting String using Regular expression


String in Java is feature rich. it has methods like split(regex) which can take any
String in form of regular expression and split the String based on that. particularly useful
if you dealing with comma separated file (CSV) and wanted to have individual part in a
String array. There are other methods also available related to splitting String, see this
Java tutorial to split string for more details.
10) Don't store sensitive data in String
String pose security threat if used for storing sensitive data like passwords, SSN or any
other sensitive information. Since String is immutable in Java there is no way you can
erase contents of String and since they are kept in String pool (in case of String literal)
they stay longer on Java heap ,which exposes risk of being seen by anyone who has
access to Java memory, like reading from memory dump. Instead char[] should be
used to store password or sensitive information. See Why char[] is more secure than
String for storing passwords in Java for more details.

11) Character Encoding and String


Apart from all these 10 facts about String in Java, the most critical thing to know is what
encoding your String is using. It does not make sense to have a String without
knowing what encoding it uses. There is no way to interpret an String if you don't know
the encoding it used. You can not assume that "plain" text is ASCII. If you have a
String, in memory or stored in file, you must know what encoding it is in, or you cannot
display it correctly. By default Java uses platform encoding i.e. character encoding of
your server, and believe me this can cause huge trouble if you are handling Unicode
data, especially if you are converting byte array to XML String. I have faced instances
where our program fail to interpret Strings from European language e.g. German,
French etc. because our server was not using Unicode encodings like UTF-8 or UTF-
16. Thankfully, Java allows you to specify default character encoding for your
application using system property file.encoding. See here to read more about character
encoding in Java

That's all about String in Java. As I have said String is very special in Java, sometime
even refer has God class. It has some unique feature like immutability,
concatenation support, caching etc, and to become a serious Java
programmer, detailed knowledge of String is quite important. Last but not the least don't
forget about character encoding while converting a byte array into String in Java. Good
knowledge of java.lang.String is must for good Java developers.

 When to make a method static in Java


 How to convert Binary Number to Decimal in Java - Algorithm
 Difference between equals method and "==" operator in Java - Interview Question
 How SubString method works in Java - Memory Leak Fixed in JDK 1.7

1) While calling equals() method with String literal, prefer defensive approach e.g.
calling equals() on String literal rather than on String object e.g.

"USA".equals(country) will return false if country is null. While country.equals("USA")


will throw NullPointerException, if country is null.
2) Always override toString() method, especially for value object, business and domain
objects. At the same time, encrypt, mask or simply don't include sensitive information
e.g. SSN on toString, because those information may end up on log files, compromising
security and confidentiality.

3) Prefer System.out.printf() over System.out.println() for better formatting.

4) Prefer StringBuilder over StirngBuffer over String concatenation.

I love the fact that in Java, developers are more mindful of writing immutable classes. I
don't appreciate it before, until of course running into problems later due to concurrency.

Point (1) should say you can get *a copy of* the character array used to represent String
in Java by calling toCharArray().

From Java 7u6 onwards, the substring() method does NOT use the underlaying char array
anymore, it DOES copy the part of the array it needs.

->Regarding the PermGen comments.

From Oracle's Java SE 7 Features and Enhancements:

"In JDK 7, interned strings are no longer allocated in the permanent generation of the
Java heap, but are instead allocated in the main part of the Java heap (known as the young
and old generations), along with the other objects created by the application."

Garbage collection strategies vary by Java vendor, version, and JVM configuration.

what happens when we use

String str1="abc"
str1="xyz";

GC will clean abc or that will be in literal pool?

as per example .GC will not clear the abc, because String declaration and creation done
by string literal
inside double quotes are String literal in Java are maintained in a separate String pool,
special memory location inside java memory .

In String pool will not clean abc immediately .. if String pool(max 200 object will
stored ) memory is full then automatically string pool will clear the abc object
4) Advice to prefer StringBuilder is good for when dealing with single threads only.
Otherwise, if multiple threads could be accessing it, a StringBuffer (being synchronised)
may be what you are after.

Doubt below as learned already jvm doesnot check when we use new operator

I read that When


String s = new String("JAVA"); instruction is executed,
JVM checks SCP for "JAVA" , if SCP already holds a reference to "JAVA" , then only one
object in heap will be created other wise two objects will be created in heap where one is
referenced in SCP and one will be in String. Please answer .. Reference link
http://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-
use-new-to-create-them

In the first case, a new object is being created in each iteration, in the second case, it's
always the same object, being retrieved from the String constant pool.

In Java, when you do:

String bla = new String("xpto");

You force the creation of a new String object, this takes up some time and memory.

On the other hand, when you do:

String muchMuchFaster = "xpto"; //String literal!

The String will only be created the first time (a new object), and it'll be cached in the
String constant pool, so every time you refer to it in it's literal form, you're getting the
exact same object, which is amazingly fast.

Now you may ask... what if two different points in the code retrieve the same literal and
change it, aren't there problems bound to happen?!

No, because Strings, in Java, as you may very well know, are immutable! So any
operation that would mutate a String returns a new String, leaving any other references to
the same literal happy on their way.

This is one of the advantages of immutable data structures, but that's another issue
altogether, and I would write a couple of pages on the subject.

Just a clarification, the constant pool isn't exclusive to String types, you can read more
about it here, or if you google for Java constant pool.

http://docs.oracle.com/javase/specs/jvms/se7/jvms7.pdf
Also, a little test you can do to drive the point home:

String a = new String("xpto");


String b = new String("xpto");
String c = "xpto";
String d = "xpto";

System.out.println(a == b);
System.out.println(a == c);
System.out.println(c == d);

With all this, you can probably figure out the results of these Sysouts:

false
false
true

Since c and d are the same object, the == comparison holds true.

->as already have been answered the second retrieves the instance from the String pool
(remember Strings are immutable).

Additionally you should check the intern() method which enables you to put new String()
into a pool in case you do not know the constant value of the string in runtime: e.g:

String s = stringVar.intern();

or

new String(stringVar).intern();

I will add additional fact, you should know that additionally to the String object more
info exist in the pool (the hashcode): this enables fast hashMap search by String in the
relevant data Strtuctures (instead of recreating the hashcode each time)

->Few more things to add into this excellent articles :

1) String are stored as UTF-16 characters and not UTF-8, may be some day they will
move to UTF-32 as well.

2) JVM does not intern all strings created by Java code, only String literals are interned.
String created using new() is not interned until you explicitly call intern method on them.

 10 Examples of Lambda Expressions in Java 8


 9 Difference between TCP and UDP Protocol
 20 Java 8 Date and Time API Examples
 10 Points about NULL in Java
 Where is Java used in Real World
 10 Object Oriented Design Principle Every Programmer Should Know
 10 Articles Every Programmer Must Read
 Difference between Java and Scala Programming
 How Android App works, A Java Programmers Introduction

 JQuery Selectors Examples to find elements in DOM ...


 2 Books to Prepare Oracle Java Certification Exams...
 How to bypass Websense Internet Filter at Office, ...
 File Upload Example in Java using Servlet, JSP and...
 How to create Thread Pools using Java 1.5 Executor...
 How to Configure HTTPS (SSL) in Tomcat 6 and 7 Jav...
 10 Things Every Java Programmer Should Know about ...
 Difference between linked list and array data stru...
 When to make a method static in Java
 Top 5 JQuery books for Beginners and Web developer...
 How SSL, HTTPS and Certificates works in Java web ...
 Role based Access control using Spring Security an...

 Java API documentation JDK 6

 JDK 7 API

 Eclipse

 jQuery
Blog about Java programming language, FIX Protocol, Tibco Rendezvous and related Java
technology stack.

 android
 ant tutorials

 Array

 Autosys

 Bash

 batch file

 best practices

 books

 cloud computing

 coding

 core java

 core java interview question

 data structure and algorithm

 database

 date and time tutorial

 debugging

 design patterns

 Eclipse

 error and exception

 FIX protocol tutorial

 general

 hibernate

 HTML and JavaScript

 interview questions

 J2EE

 java 5 tutorial
 Java 7

 Java 8

 Java Certification OCPJP SCJP

 java collection tutorial

 java IO tutorial

 Java JSON tutorial

 Java multithreading Tutorials

 java networking tutorial

 Java Programming Tutorials

 Java xml tutorial

 JDBC

 JQuery

 jsp-servlet

 JSTL

 JUnit

 JUnit testing

 linux

 logging

 Maven

 MQ Series

 mysql

 object oriented programming

 oracle database

 performance

 programmers

 programming

 Scala

 spring
 SQL

 SQL Interview Questions

 SSL

 String

 Sybase and SQL Server

 thread

 tibco

 xml

 xslt

Top 10 Java String interview Question


answers - Advanced
10 Java String interview Question answers
String interview questions in Java is one of Integral part of any Core Java or J2EE interviews. No one can
deny importance of String and how much it is used in any Java application irrespective of whether its
core Java desktop application, web application, Enterprise application or Mobile application. String is one
of the fundamental of Java programming language and correct understanding of String class is must for
every Java programmer. What makes String interview questions in Java even more interesting is the
special status of String in terms of features and privileges it has, like + operator is kind of overloaded to
perform String concatenation despite the fact that Java does not support operator overloading. There is
a separate String pool to store String literal etc. In this article we will some frequently asked question on
String in a Java interview which focuses on range of features like immutability, thread-safety, security,
performance, memory consumption, mutable counterparts of String e.g. StringBuilder and StringBuffer,
comparing String instances in Java, equals() vs == check for String, using String as key in HashMap,
storing String on array and List etc.

Java String Interview Questions and Answers

Here are my list of frequently asked question on String, feel free to add any other interesting
question which you faced on String during any Core Java interview :
1) What is String in Java? Is String is data type?
String in Java is not a primitive data type like int, long or double. String is a class or in more simple term a
user defined type. This is confusing for some one who comes from C background. String is defined in
java.lang package and wrappers its content in a character array. String provides equals() method to
compare two String and provides various other method to operate on String like toUpperCase() to
convert String into upper case, replace() to replace String contents, substring() to get
substring, split() to split long String into multiple String.

2) Why String is final in Java?


String is final by design in Java, some of the points which makes sense why String is final is Security,
optimization and to maintain pool of String in Java. for details on each of this point see Why String is final
in Java.

3) What is Difference between String and StringBuffer in Java


This is probably the most common question on String I have seen in Java interviews. Though String and
StringBuffer are two different class they are used in context of concatenating two Strings, Since
String is immutable in Java every operation which changes String produces new String, which can be
avoided by using Stringbuffer. See String vs StringBuffer for more details.

4) What is difference in String on C and Java?


If you have mentioned C in your resume, then you are likely to face this String interview question. Well C
String and Java String are completely different to each other, C String is a null terminated character array
while String in Java is an Object. Also String is more feature rich in Java than C.

5) Why char array is better than String for storing password?


This String interview question is debatable and you might not agree with interviewer but this is also a
chance to show that how deep and differently you can think of. One of the reason which people give
Why you should store password in char array over String is related to immutability, since its not possible
to remove erase contents of String but you can erase contents of char array. See Why char array
preferred over String for password for complete discussion.
6) How do you compare two String in Java?
This is another common String interview question which appears on fresher level interviews. There are
multiple ways to compare two String like equals() method, equalsIgnoreCase() etc, You can
also see 4 ways to compare String in Java for more examples. Main thing which interviewer checks is that
whether candidate mentioned equality operator or not "==", comparing String with equality operator is
common mistake which works in some case and doesn't work in other. next String interview question is
follow-up up of this.

7) Can we compare String using == operator? What is risk?


As discussed in previous String question, You can compare String using equality operator but that is not
suggested or advised because equality operator is used to compare primitives and equals() method
should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality
operator can cause subtle issue while comparing primitive to Object, any way String is free from that
issue because it doesn't have corresponding primitive type and not participate in autoboxing. Almost all
the time comparing String means comparing contents of String i.e. characters and equals() method is
used to perform character based comparison. equals() return true if two String points to same object
or two String has same contents while == operator returns true if two String object points to same object
but return false if two different String object contains same contents. That explains why sometime it
works and sometime it doesn't. In short always use equals method in Java to check equality of two String
object.

8) How substring method work in Java?


This is one of the tricky Java question relate to String and until you are familiar with internals of String
class, its difficult to answer. Substring shares same character array as original String which can create
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. See How Substring works in Java for more details.

9) What is String pool in Java?


Another tough Java question asked in String interview. String pool is a special storage area in Java heap,
mostly located on PerGen space, to store String literals like "abc". When Java program creates a new
String using String literal, JVM checks for that String in pool and if String literal is already present in pool
than same object is returned instead of creating a whole new object. String pool check is only performed
when you create String as literal, if you create String using new() operator, a new String object will be
created even if String with same content is available in pool.
10) What does intern() method do in Java?
As discussed in previous String interview question, String object crated by new() operator is by default
not added in String pool as opposed to String literal. intern() method allows to put an String object
into pool.

11) Does String is thread-safe in Java?


If you are familiar with the concept of immutability and thread-safety you can easily answer this String
interview question in Java. Since String is immutable, it is thread-safe and it can be shared between
multiple thread without external synchronization.

String based Coding Questions


These questions are most based upon Java's implementation of String and you can only answer them
well if you have good knowledge of java.lang.String class. But, String is very general data structure and
you will find it in almost all programming and scripting language e.g. C, C++, C#, Python, Perl or Ruby.
That's why I am going to share some more String based coding question, which is not Java specific. You
can solve these question in any programming language as they are mostly logic based programming
question.

1) Write a Java program to reverse String in Java without using any API? which means you can not use
StringBuffer's reverse() method, neither any of String utility method, all you can have is a character array
for reversing contents.

2) Write a Program to check if a String is palindrome or not? For example an String e.g. "madam" is a
palindrome but "book" is not palindrome. You also need to solve this question without taking any help
from Java String API.

3) Write a Java program to check if two String are Anagram or not? You need to write method e.g.
isAnagram(String first, String second) which will return true if second String is
anagram of first string. An anagram must contain same number of characters and exactly same
characters but on different order e.g. top and pot, or army and mary.
4) Write a method in Java to remove any character from String? For example you need to write method
remove(String word, char removeThis), this method should return an String without
character, which is asked to remove. you can use indexOf(), substring() and similar methods
from String class, but your method must handle corner cases e.g. passing null or empty String, String
containing just one character etc.

5) Write a method to Split a comma separated String in Java?

6) Write Java program to print all permutations of a String e.g. passing "ABC" will print all permutations
like "BCA", "CBA" etc

That's all about Java String interview question and answers. In Summary there are lot of specifics about
String which needs to be know for any one who has started Java programming and these String question
will not just help to perform better on Java Interviews but also opens new door of learning about String. I
didn't know many String related concepts until I come across these question which motivated to
research and learn more about String in Java.

Other Java String tutorials and questions from Javarevisited Blog

1. How to convert Date to String in Java


2. How to convert Enum to String in Java

3. How to create comma separated String from Collection in Java

4. How to convert String to Double in Java

5. How to reverse String in Java with recursion

6. How to format String in Java

7. ailHow SubString method works in Java - Memory Leak Fixed in JDK 1.7

 How to reverse String in Java using Iteration and Recursion

 Why character array is better than String for Storing password in Java

 String vs StringBuffer vs StringBuilder in Java

Hi, Please confirm.. I face this question a lot in my interviews.


String aa = new String("abc");
String bb = "abc";

How many object of string class are created.

->To answer Shariq Bharat questions in more detail, Yes, there are two objects are
created, but both are created in first line itself. Before creating object using new String(),
JVM creates an string literal "abc", that is your first object, now by using content of this
object, second object is created by calling constructor of String, this object also has value
"abc" but created in heap, rather than in permgen area, where first object was created. In
second line no new object is created as bb will get reference of "abc" from String pool
from permgen space.

Now, from Java 7 onwards String pool is no longer located in permgen space, they are
now part of Java heap space. Which means you can use String literals and intern()
method more freely without worrying about OutOfMemoryError in permgen space. If
you are still using Java 1.6, then remember that permgen area has less space than heap
memory, by default around 64MB, by creating large number of String literals in String
pool, you can quickly fill permgen space.

->Hello Javin, Can we use String in Switch case? This question is asked to me at TCS
Interview? I said no, because Switch only accept integer values, but interviewer was not
happy at all?

August 22, 2013 at 8:42 PM

Kaushal Kapoor said...

In the JDK 7 release, you can use a String object in the expression of a switch statement

http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html

@Sanidhya A quick implementation, hopefully without bugs :)

public class ReverseWords {


public String run(String input, char delimiter){
if (input == null) return null;
char[] charArray = input.toCharArray();
int wordStartIdx = 0;
for(int i = 0; i from; to--, from++){
char tmp = charArray[from];
charArray[from] = charArray[to];
charArray[to] = tmp;
}
}

}
March 8, 2014 at 2:58 AM

madnorb said...

I left in a bug :), this is the bugfix:


...
flip(charArray, wordStartIdx, charArray.length-1);
return new String(charArray);
}
...

March 8, 2014 at 3:02 AM

madnorb said...

My previous String reversal implementation is very basic and limited, the task is a little
bit more complicated because of the unicode character representation:
http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#unicode
One have to consider surrogate ranges (a unicode character could be represented by two
char-s)

March 8, 2014 at 3:19 AM

Vikas Grover said...

two object are created to answer of shariq bhagat

for in heap memory and another will in string pool as constant'

and both have different hascode

March 11, 2014 at 6:08 AM

Vikas Grover said...

my question is

why we create main method , and how it will be created

March 11, 2014 at 6:09 AM

Karl the Pagan said...

2 months after this posting question #8 became voodoo optimization:


http://www.javaadvent.com/2012/12/changes-to-stringsubstring-in-java-7.html

2 years later I'm still seeing this blog post thrown around without the correction. Here is a
good overview of the differences: http://jaxenter.com/the-state-of-string-in-java-
49450.html

July 27, 2014 at 8:40 AM

Bhagath Sagar said...

How substring method work in Java ? , Answer for this question need an attention. The
new JDK provided the fix for memory leak.

August 19, 2014 at 11:40 PM

Anonymous said...

One question you need to add into this list is "What encoding method do Strings use?", as
I strongly feel that Java developer should be aware of character encoding and make sure
they use right encoding while converting bytes to string and vice-versa. I expect "UTF-
16" or "UCS 2" as answer, though UTF-16 is more appropriate. If candidate mention
about use of surrogate character pairs to represent certain characters then give him bonus
point.

September 4, 2014 at 8:34 AM

Amreesh Verma said...

package com.str1;
import java.io.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class B
{
public static void main(String[] args)throws IOException
{
String s1;
System.out.println("Enter the String= ");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
System.out.println(s1);
char ch[]=s1.toCharArray();
int j=0;
for(int i=0;i<ch.length;i++)
{
//System.out.println(i);
j=i;
}
System.out.println("Length="+(j+1));
int len=(j+1);
System.out.println("=reverse String is=");
for(j=len-1;j>=0;j--)
{
System.out.print(ch[j]);
}
}
}

October 25, 2014 at 11:26 PM

Anonymous said...

@ Anonymous: Yes in Java 7 we can use String in Switch. but We can achieve it using
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...
}

 What is static import in Java 5 with Example


 What is difference between java.sql.Time, java.sql...

 JSTL foreach tag example in JSP - looping ArrayLis...

 Eclipse shortcut to System.out.println in Java pro...

 Java program to calculate area of Triangle - Homew...

 Difference between notify and notifyAll in Java - ...

 5 ways to add multiple JAR in to Classpath in Java...

 Regular Expression in Java to check numbers in Str...


 Difference between private, protected, public and ...

 10 Garbage Collection Interview Questions and Answ...

 Java Program to get input from User from Console o...

 Eclipse shortcut to remove all unused imports in J...

 Top 10 Java String interview Question answers - Ad...

 What is Inheritance in Java and OOPS Tutorial - Ex...

Why String is Immutable or Final in Java


String is Immutable in Java because String objects are cached in String pool. Since cached String
literal is shared between multiple client there is always a risk, where one client's action would
affect all other client. For example, if one client changes value of String "Test" to "TEST", all
other client will also see that value as explained in first example. Since caching of String objects
was important from performance reason this risk was avoided by making String class Immutable.
At the same time, String was made final so that no one can compromise invariant of String class
e.g. Immutability, Caching, hascode calculation etc by extending and overriding behaviors.
Another reason of why String class is immutable could de due to HashMap. Since Strings are
very popular as HashMap key, it's important for them to be immutable so that they can retrieve
the value object which was stored in HashMap. Since HashMap works in principle of hashing,
which requires same has value to function properly. Mutable String would produce two different
hashcode at the time of insertion and retrieval if contents of String was modified after insertion,
potentially losing the value object in map. If you are an Indian cricket fan, you may be able to
correlate with my next sentence. String is VVS Laxman of Java, i.e. very very special class. I
have not seen a single Java program which is written without using String. That's why solid
understanding of String is very important for a Java developer. Important and popularity of
String as data type, transfer object and mediator has also make it popular on Java interviews.
Why String is immutable in Java is one of the most frequently asked String Interview questions
in Java, which starts with discussion of, What is String, How String in Java is different than
String in C and C++, and then shifted towards what is immutable object in Java , what are the
benefits of immutable object, why do you use them and which scenarios should you use them.
This question some time also asked as "Why String is final in Java". e

Why String is Final in Java


As I said, there could be many possible answer of this question, and only designer of String class
can answer it with confidence, I think following two reasons make a lot of sense on why String
class is made Immutable or final in Java : 1) Imagine String pool facility without making string
immutable , its not possible at all because in case of string pool one string object/literal e.g.
"Test" has referenced by many reference variables , so if any one of them change the value others
will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" ,
so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network
connection, you can pass hostname and port number as string , you can pass database URL as
string for opening database connection, you can open any file in Java by passing name of file as
argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can
access to any file for which he has authorization, and then can change the file name either
deliberately or accidentally and gain access of those file. Because of immutability, you don't need
to worry about those kind of threats. This reason also gel with, Why String is final in Java, by
making java.lang.String final, Java designer ensured that no one overrides any behavior
of String class.

3)Since String is immutable it can safely shared between many threads ,which is very important
for multithreaded programming and to avoid any synchronization issues in Java, Immutability
also makes String instance thread-safe in Java, means you don't need to synchronize String
operation externally. Another important point to note about String is memory leak caused by
SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its
hashcode , being immutable String in Java caches its hashcode, and do not calculate every time
we call hashcode method of String, which makes it very fast as hashmap key to be used in
hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short
because String is immutable, no one can change its contents once created which guarantees
hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson
on comments is: The absolutely most important reason that String is immutable is that it is used
by the class loading mechanism, and thus have profound and fundamental security aspects. Had
String been mutable, a request to load "java.io.Writer" could have been changed to load
"mil.vogoon.DiskErasingWriter"

Security and String pool being primary reason of making String immutable, I believe there could
be some more very convincing reasons as well, Please post those reasons as comments and I will
include those on this post. By the way, above reason holds good to answer, another Java
interview questions "Why String is final in Java". Also to be immutable you have to be final,
so that your subclass doesn't break immutability. what do you guys think ?
Few more String related post from Javarevisited, you may like:
How substring works in Java
How to replace String in java using regular expression
Why Character array is better than String for storing password in Java
How to convert String into Integer in Java
How to split String with 2 examples in Java
How to compare String in Java
Share on email Share on delicious Share on linkedin Share on stumbleupon Share on reddit
Share on digg Share on dzone Share on hackernews More Sharing Services
You might like:
 Difference between Thread vs Runnable interface in Java
 Why wait, notify and notifyAll is defined in Object Class and not on Thread class in Java

 Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java


 How to check if a thread holds lock on a particular object in Java

Recommended by
Posted by Javin Paul at 7:43 PM
Email This BlogThis! Share to Twitter Share to Facebook
Labels: core java , interview questions

57 comments :

Javin @ Tibco RV Tutorial said...

Hi Sandeep,

As per my knowledge ,String pool gets created in PERM area of Java Heap , so if there
are too many String there is good chance of OutOfMemoryError because garbage
collection doesn't happen in PERM area of java heap.

Thanks
Javin

January 19, 2011 at 3:59 AM


Javin @ Tibco RV Tutorial said...

Thanks Sandeep , Good to see you here back. Given extensive usage of String in any Java
application and immutability benefit it provides as you pointed out which make it
preferred choice in case of hashmap key or sharing between multiple thread everybody
should know more about String Pool and behavior of String class.this is mine initiative :)

January 20, 2011 at 6:40 AM


Anonymous said...
Very good. It is the same reason why String is final. If String is not final, you can always
extend it so that it is no longer immutable.

January 21, 2011 at 8:23 AM


Dan Bergh Johnsson said...

The absolutely most important reason that String is immutable is that it is used by the
class loading mechanism, and thus have profound and fundamental security aspects.

Had String been mutable, a request to load "java.io.Writer" could have been changed to
load "mil.vogoon.DiskErasingWriter".

January 21, 2011 at 12:39 PM


Javin @ Tibco RV Tutorial said...

@Dan Bergh Johonsson.

You are absolutely right. Since string is used in many place to identify names (whether its
class, file , network or anything else) and if you left String immutable you will end of
with big security hole.

Thanks John for highlighting some important thing and adding value to this blogpost.

January 21, 2011 at 6:55 PM


Jaroslav Sedlacek said...

String class is not a common class. It has a specific requirements and it is handled as
special by both JVM Specification and Java Language Specification. Many language
features depend on ability of String to represent constant text - some of them mentioned
above.

One of the "side effect" of String immutability is an ability to cache its hash value which
greatly improves String performance in hash based collections.

January 21, 2011 at 8:34 PM


Javin @ Tibco RV Tutorial said...

Thanks Jaroslav Sedlacek , you really highlighted very good point "ability to cache hash
value of String class". I guess that is true for wrapper class also which makes these
classes very good candidate for hashMap or hashtable keys.

January 21, 2011 at 9:37 PM


AhmedOsama said...

Thanks for this amazing info .


That explains why no one uses StringBuffer to hold a connection info of DB.
January 22, 2011 at 3:17 AM
Javin @ Tibco RV Tutorial said...

Thanks Ahmed , good to know that you find this useful and you brought up a good
example also that database connection name is also passes as string and not as mutable
stringbuffer.

January 22, 2011 at 4:38 AM


Javin @ Tibco RV Tutorial said...

Hi Michael,

Thanks you liked the post , yes I gonna compile the ideas/information mentioned in
comments in the main article whenever time allows me.

Thanks
Javin

January 25, 2011 at 4:34 AM


anshuiitk said...

Javin, Good article. Apart from the reason listed above and the pros and cons, the main
reason I think why we have immutable claases like Integer String etc is because of space.
As a designer you are always fighting for memory and performance, and this is a nice
little feature provided by Java to make things efficient and consume less space.

http://anshuiitk.blogspot.com/

April 3, 2011 at 8:19 AM


javaisfinal said...

you are absolutely correct mate above reason can be used to answer interview question
"Why String is final in Java". Though final and immutable are two different thing e.g.
StringBuffer is a final class in java but still mutable but Certain feature of String class
will not be possible until String are final in Java. I don't say use above reason as it is but
they can safely use to answer Why String is final in java.

July 29, 2011 at 12:16 AM


Anonymous said...

In one of the interview , i was asked, how will you make a class emp immutable , it has
some member variable, and another member variable say Salary, on which you don't have
any control. In the sense the interviewer said the methods in salary class, can actually
change the state of class salary.

Any answers
August 11, 2011 at 6:28 AM
Anonymous said...

Hashcode could of course be cached even if Strings were mutable, the cached value
would just have to be erased whenever the instance was modified. That's certainly doable.
Bigger problems with mutable Strings as map keys is the mutability itself - mutable keys
generally break contracts of existing Map and Set interfaces.

September 14, 2011 at 2:47 AM


*~řäđĥïķã~* said...

@Anonymous: to make a class immutable which has member variables of classes which
are mutable, you will have to deep clone the mutable objects so that only a copy of the
mutable variables are available to any classes which creates an instance of our immutable
class. So in your case you will have to write a method to deep clone your Salary class
object when giving out to some other class. Read this article:
http://www.javaranch.com/journal/2003/04/immutable.htm

September 19, 2011 at 2:16 AM


Anonymous said...

Another reason for making String as final Class in Java is to enable String to be used as
key in HashMap and Hashtable. If String was not final than any one can change value of
String and object will not be retrieved from hashmap. I think this is a very convincing
reason to make String final in Java, What do you think ?

October 16, 2011 at 7:25 PM


Mansi said...

I agree final and immutable are almost has same effect. Whether you say String is final in
Java or String is immutable in Java , reason will be same.you can't make string
immutable until string is final.

November 22, 2011 at 2:41 AM


Anonymous said...

garbage collection doesn't happen in PERM area of java heap?

November 23, 2011 at 10:57 PM


Diya said...

Why String Class is Final or Why String Class is Immutable in Java is the same questions
asked to me last week.I didn't about your blog post on String immutability or why String
is a final class otherwise I would have answered that interview question quite well:)

December 1, 2011 at 8:48 PM


jfolson said...

Another problem would be breaking the hashcode and comparable contracts. An object's
hashcode cannot change. Neither can it's compareTo values relative to other object's.

January 20, 2012 at 7:23 AM


Chandraprakash Sarathe said...

I would agree to usage of String as hashkey makes it immutable.Security aspect can be


broken in multiple ways.I doubt how String helps here.

http://javaved.blogspot.com

January 23, 2012 at 3:58 AM


Anonymous said...

If anybody has trouble understanding why Strings are immutable in Java (and other
languages) it surely means he/she has never coded in Assembly which is really helpful for
understanding a bit more about pointers, primitives, the Stack, etc.

February 1, 2012 at 7:01 AM


Javin @ String split Java said...

@Anonymous, Indeed coding in Assembly is most difficult and some of Java


programmer relatively newer is not even coded in C and C++ which makes them to
understand recursion, data-structure, pointers concept even more difficult. immutability is
relatively easier concept for them :)

February 3, 2012 at 10:37 PM


Vivekanand said...

I understand your point on why String is immutable and final in Java but my questions is
why String is reference type in Java , why not is just a null terminated character array or
primitive type in Java like C or C++ ? Also can you please give example of String being
immutable I mean what difference it make ?

March 19, 2012 at 2:36 AM


Anonymous said...

Java strings are immutable due to flawed design. Witness the [lethora of mutable string-
like classes since added to Java.

March 20, 2012 at 10:08 AM


carrion said...
Just a quick note: final and immutable is not the same! Consider a class Foo with a final
member bar and no setters for bar. I can still do stuff like this:
b=new Bar(5);
f=new Foo(b);
b.value=4;
The same problem arises when Foo passes bar to another Method outside it's class scope.

March 20, 2012 at 2:14 PM


narasimha said...

can you please explain more about how string is useful for security reasons and how can
we modify the string if it is mutable.

April 26, 2012 at 8:54 AM


chikky said...

sir,
yes string is immutable.but my question is as follows:
class StringEx
{public static void main(String args[])
{String s1=”hello”;
string s2=”friend”;
s1=s1+s2;
System.out.println(s1);
}
}
sir, the output for the program is hellofriend
then how can we say that string is immutable bcoz as here the string is being retrived by
another would you plz explain it as early as possible..

June 2, 2012 at 8:27 PM


Fabrizio Benigni said...

I don't get the argument suggested by Dan Bergh Johnsson: a request to load
"java.io.Writer" is either specified through the string literal (thus fixed at compile time)
or through a string reference (thus modifiable regardless of the immutability of the
object).

June 3, 2012 at 5:21 PM


Fabrizio Benigni said...

@chikky,

you are confusing the concept of object immutability with the concept of variable
immutability. When you reassign s1 you don't modify the object referenced by s1;
instead, you're creating a new string object and assigning it to the variable s1.
June 3, 2012 at 5:26 PM
Fabrizio Benigni said...

Regarding the concern with class loading and possibly mutable strings, I think you're
confusing the reasons behind the effects of making strings immutable with the effects of
the implementation choices that were enabled by the decision of making stings
immutable: immutable strings allowed optimizations such as the string pool, which would
not make any sense had Strings not been immutable, so obviously there wouldn't be any
problem with class loading and the like in case strings were mutable, as in that case we
wouldn't have string pools and modifying my string object "java.io.Writer" to
"gotcha.hahaha" wouldn't have any effect on another "java.io.Writer" object.

June 3, 2012 at 5:34 PM


Andrew Glassman said...

The interviewer has his facts messed up. As someone pointed out before, the value[] is
not copied, it is a reference. So there is NOT a new 1GB string every time you do a
substring. On the other hand, if you are doing substring on a 1GB string only to keep a
small substring of that, you most definitely would want to create a new String object.
Otherwise you have this small string backed by a huge value[].

June 22, 2012 at 7:08 AM


Javin @ split string in Java said...

not to worry Andrew, I understand :) By the way glad to welcome here and hope to see
some interesting comments :)

Javin

June 22, 2012 at 7:18 AM


Verhás Péter said...

Forget ALL SECURITY REASONS. As regarding security reasoning String IS mutable:

package com.verhas.elrettentopelda;

import java.lang.reflect.Field;

public class Wtf {


public static void main(String[] args) throws Exception {
String alma = "alma";
String korte = "alma";
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
value.set(alma, new char[] { 'k', 'o', 'r', 't', 'e' });
System.out.println(korte);
}
}

July 15, 2012 at 6:44 AM


Deep Shah said...

Hello Dir,
As u said:
"String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" ,
so A will also be "TEST" which is not desirable."

I tried this example but the output of String A does not changed it's till 'Test' instead of
'TEST'

So , can u please give me the example?

July 26, 2012 at 5:39 AM


Javin Paul @ sort arraylist in Java said...

Hi Deep, when you call TEST.toUpperCase(), original object will not change because
String is immutable it can not be changed once created, instead a new String object will
be created.

July 27, 2012 at 4:16 AM


Anonymous said...

Hii Dear,

What @deep tried is true which is i also tried then how come it changes the same object
when it is creating a new one. Please Explain

January 15, 2013 at 2:46 AM


Niraj Singh said...

Main Reason of String being immutable is performance. Before you guys tear my opinion
to shreds please read ahead :-).

Strings are backbone of Java or for that matter any other programming language. As we
have seen thousand examples in this great blog itself, for example classloaders uses
classname to load a class which is a string, usernames, passwords, database connection
names etc. all are stored as string.

Now lets assume for a second that String were not immutable what would happen? String
references pointing to litrals in constant pool would keep on changing the contents there
hence a havoc would occur.

To fix this java designers would have to remove the constant pool all together. Thus we
would have to create a new instance of string all the time which would go into the heaps.
Tons of string would result in out of memory errors hence impact the performance of all
the java applications.

January 22, 2013 at 6:08 AM


Javin @ ClassLoader in Java said...

Hi Niraj, Good comment. Performance would definitely will be in mind of Java


designers, because whole idea of String pool is caching. Immutability, String pool,
Security, Performance these all things put together nicely for String being immutable.

January 23, 2013 at 4:46 AM


Anonymous said...

If this was the answer given in an interview that I was giving, you would not get the job.
It misses the fundamental reason for using an immutable classes, and that is to allow this
object to be shared efficiently without fear of having the underlying value change. All of
the listed reasons are secondary to this fundamental point, so not to mention it means that
you are not seeing cause and effect in the right direction.

If you take the discussion in point (5) for example, it does not make any sense. These
classes were built on the assumption that String was safe to share. If they weren't safe,
they would never be used in a context that required safety. It's like saying that glue is
sticky because if it weren't, my furniture would fall apart.

April 7, 2013 at 12:36 PM


Anonymous said...

Hi!
Honestly, I take the security argument with caution. Nothing prevents a mutable object
holding the immuatable String to change the reference and so refer to another String.
More, without proper security policy, nothing prevents introspection to change an
existing String value and mess up the String pool. Take a look at this code:
String titi = "titi";
String titi2 = "titi";
String titi3 = new String(titi);
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char value[] = {'t', 'o', 't', 'o'};
field.set(titi, value);
System.out.println(titi2); // toto
System.out.println(titi3); // titi

You would expect this to fail, because the field is private and final; But this just works.
More interesting, explicitly creating a new instance allow you to avoid some of the
problems.

April 9, 2013 at 2:10 AM


Anonymous said...

I am really unable to understand immutable(object is not modifiable) meaning..

Pls... Give me an example of mutable class and its immutability..

Thank you for noticing me.

June 17, 2013 at 6:40 AM


Anonymous said...

i don't get the concept of security issue.

@Had String been mutable, a request to load "java.io.Writer" could have been changed to
load "mil.vogoon.DiskErasingWriter".

if we change it, [creates a new string] won't it pass the new modified string ?

what is a value in string class that they use to access?

June 20, 2013 at 4:35 PM


best students said...

yes it is a good article of final, could you please explain something about "How final
method bonded during compile time and why it is called static binding "

Please ...

August 14, 2013 at 12:47 PM


Nitin Taur said...

I do not very much agree with point (4) related to hashcode. Can we use an object as key
in hashmap whose hashcode can change once stored in hashmap? Basically this will have
same issue as with following class used as key in hashmap:

class A
{
private volatile int i = 1;
@Override
public int hashCode()
{
return ++i;
}
}

I think hashcode should never depend on changing state of object.

October 11, 2013 at 4:03 AM


Anonymous said...

Good post. Only one note: the hashcode caching is not the reason for making String
immutable, but visa versa hashcode caching mechanism is used because String is
immutable.

October 15, 2013 at 2:24 AM


ilavarasan rangasamy said...

Java uses the concept of string literal.Suppose if there are 5 reference variables ,all
references to one object.if any reference variable changes the value of an object,it will be
affected to all the reference variables.That is why string is immutable in java

October 25, 2013 at 9:42 AM


Constance said...

The two main reasons why strings are immutable in many modern languages, including
Java, are security and performance (or, more precisely, chance for optimizations).

The fact that strings are final is to ensure their immutability (by forbidding anyone from
extending them and making them mutable again).

April 22, 2014 at 7:01 AM


Anonymous said...

why do we need stringpool facility in java??

June 27, 2014 at 7:41 AM


Simerpreet Singh said...

@Annonymous: We use String Pool because it stores only one reference to String literal
eg.
String A = "Test"
String B = "Test"
So in String Pool there is only one instance of "Test" and variable A & B are just
reference to that string. Now if you create two "Test" String using new operator eg. new
String("Test") it will create a new object everytime but in case of string pool there is only
one reference.So i hope you understand string pool is saving time on string related
memory operations.

July 3, 2014 at 4:43 AM


vaibhav sharma said...

Good post!
can you give some highlight on String Buffer and String Builder classes as both are
providing mutable objects but in what aspect these are different from String class and
where should we use them as compare to String class.
Thanks in advance.

July 29, 2014 at 11:29 AM


Anonymous said...

A String value in Java is immutable but a String variable is not final. The term "final"
specifically marks a memory reference (variable) as a constant that cannot change. The
value to which a String variable refers in memory can be changed. In other words, the
variable can refer to a different value, even though the original value is immutable.

September 16, 2014 at 8:45 AM


Anonymous said...

Hi,
I executed below lines of code and unable to understand the output can u plz explain.
String str = "test";
String str1 = "test";
System.out.println(str);
System.out.println(str1);
"test".toUpperCase();
System.out.println(str);
System.out.println(str1);

Output Is:
test
test
test
test

According to first point str and str1 should contains "TEST".

October 2, 2014 at 2:21 AM


vaibhav sharma said...

The output is right and the reason behind this is while writing "test".toUpperCase(); the
value of String str become changed in to TEST but JVM didn't found any reference that
refers to new value(TEST).So the reference become lost.And while printing it prints the
previous value of string.If you want TEST in output then you should write
str="test".toUpperCase();
Now the reference become updated and new value of String str will be print.

October 6, 2014 at 3:09 AM


Javin Paul said...

@vaibhav, Yes indeed, that's a side effect of making a class Immutable in Java. You need
to be careful to store the modified reference otherwise it can really create hard to find
bugs in your code.

October 6, 2014 at 5:38 AM


Anonymous said...

Hi Javin, one more reason for String being immutable could be that String is more like
the primitive type but represented as object. Since java uses pass by value it makes sense
for passing an immutable object to the methods as parameter so that pass by value
behavior is maintained.

Akshat

December 2, 2014 at 11:37 PM


Keyur Shah said...

how immutability of string helps in class loading??

February 10, 2015 at 7:12 PM

Post a Comment

Newer Post Home


Subscribe to: Post Comments ( Atom )
Top of Form

Top of Form

Best of Javarevisited
 10 Examples of Lambda Expressions in Java 8
 9 Difference between TCP and UDP Protocol
 20 Java 8 Date and Time API Examples
 10 Points about NULL in Java
 Where is Java used in Real World
 10 Object Oriented Design Principle Every Programmer Should Know
 10 Articles Every Programmer Must Read
 Difference between Java and Scala Programming
 How Android App works, A Java Programmers Introduction

Followers
Follow Us

Follow @javinpaul

Subscribe by email:

By Javin Paul

Blog Archive

 ► 2015 ( 38 )

 ► 2014 ( 106 )

 ► 2013 ( 136 )

 ► 2012 ( 217 )

 ► 2011 ( 145 )

 ▼ 2010 ( 33 )
o ► December ( 4 )

o ▼ October ( 29 )

 List of Tibco RV, EMS Tutorials , Tips from Javare...


 Tibco tutorial : Certified Messagging
 What are builtin Properties in ANT >> Tutorial Ex...
 Top 30 Eclipse Keyboard Shortcuts for Java Program...
 How to write build.xml and run build in Apache ANT...
 Hot to build project using Apache ANT ? ANT Build...
 MySql Tutorial : mysqldump utility in mysql
 MySQL tutorial and commands part 3
 MySQL tutorial and commands part 2
 MySQL tutorial and commands Part 1
 How to use Regular Expression in Unix Linux
 Improving Performance of java application
 Networking Basics for FIX Connection in Unix Linux...
 How to avoid deadlock in Java Threads
 Top 10 Most useful cvs commands in linux/unix
 Top 10 basic networking commands in linux/unix
 Tibco tutorial : Tibco RV tips and commands
 Tibco Tutorial: Fundamentals of Tibco RV messaggi...
 TIBCO Tutorial : TIBCO Rendezvous or TIBCO RV me...
 What is Abstraction in Java? Abstract Class or Int...
 Fundamentals of Object Oriented Programming in Jav...
 What is difference between Enumeration and Iterato...
 What is difference between HashMap and Hashtable i...
 What is difference between Synchronized and Concur...
 What is the use of class “java.lang.Class” in Java...
 Why Comparing Integer using == in Java 5 is Bad?
 How do you find length of a Singly Linked list
 How to check if a thread holds lock on a particula...
 Why String is Immutable or Final in Java

References

 Java API documentation JDK 6


 Spring framework doc

 Struts

 JDK 7 API

 MySQL

 Linux

 Eclipse

 jQuery

Copyright by Javin Paul 2012. Powered by Blogger.


 About Me
 Privacy Policy

AddThis Sharing

Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-


java.html#ixzz3WEGjudO2

Javarevisited

Blog about Java programming language, FIX Protocol, Tibco Rendezvous and related Java
technology stack.

 android
 ant tutorials

 Array

 Autosys

 Bash

 batch file

 best practices
 books

 cloud computing

 coding

 core java

 core java interview question

 data structure and algorithm

 database

 date and time tutorial

 debugging

 design patterns

 Eclipse

 error and exception

 FIX protocol tutorial

 general

 hibernate

 HTML and JavaScript

 interview questions

 J2EE

 java 5 tutorial

 Java 7

 Java 8

 Java Certification OCPJP SCJP

 java collection tutorial

 java IO tutorial

 Java JSON tutorial

 Java multithreading Tutorials

 java networking tutorial

 Java Programming Tutorials


 Java xml tutorial

 JDBC

 JQuery

 jsp-servlet

 JSTL

 JUnit

 JUnit testing

 linux

 logging

 Maven

 MQ Series

 mysql

 object oriented programming

 oracle database

 performance

 programmers

 programming

 Scala

 spring

 SQL

 SQL Interview Questions

 SSL

 String

 Sybase and SQL Server

 thread

 tibco

 xml

 xslt
Sunday, January 1, 2012

Tomcat – java.lang.OutOfMemoryError:
PermGen space Cause and Solution
Tomcat web server often suffers from java.lang.OutOfMemoryError: PermGen space whenever
you deploy and undeploy your web application couple of time. No matter you are using tomcat6,
tomcat7 or using bundled tomcat in Netbeans or Eclipse you will face this error now and then while
developing web application on tomcat server. I thought about this article after writing 2 Solution of
OutOfMemoryError in Java. I have touched this issue there but then I thought to write separate
tutorial for tomcat outofmemoryerror because I am getting this error too frequently.

In this article we will see what causes java.lang.OutOfMemoryError: PermGen Space in tomcat
and how to fix java.lang.OutOfMemoryError: PermGen Space in tomcat server .

Tomcat – java.lang.OutOfMemoryError: PermGen space


Cause and Solution
Cause of OutOfMemoryError in PermGen space in Tomcat:

PermGen Space of heap is used to store classes and Meta data about classes in Java. When a
class is loaded by a classloader it got stored in PermGen space, it gets unloaded only when the
classloader which loaded this class got garbage collected. If any object retains reference of classloader
than its not garbage collected and Perm Gen Space is not freed up. This causes memory leak in
PermGen Space and eventually cause java.lang.OutOfMemoryError : PermGen space. Another
important point is that when you deploy your web application a new Clasloader gets created and it
loads the classes used by web application. So if Classloader doesn't get garbage collected when your
web application stops you will have memory leak in tomcat.

Solution of Tomcat: OutOfMemroyError:


1) Find the offending classes which are retaining reference of Classloader and preventing it from being
garbage collected. Tomcat provides memory leak detection functionality after tomcat 6 onwards which
can help you to find when particular library, framework or class is causing memory leak in tomcat.
Here are some of the common causes of java.lang.OutOfMemoryError: PermGen space in
tomcat server:

1) JDBC Drivers:
JDBC drivers are most common cause of java.lang.OutOfMemoryError: PermGen space in tomcat if
web app doesn't unregister during stop. One hack to get around this problem is that JDBC driver to be
loaded by common class loader than application classloader and you can do this by transferring
driver's jar into tomcat lib instead of bundling it on web application's war file.

2) Logging framework:

Similar solution can be applied to prevent logging libraries like Log4j causing
java.lang.OutOfMemoryError: PermGen space in tomcat.

3) Application Threads which have not stopped.

Check your code carefully if you are leaving your thread unattended and running in while loop that can
retain classloader's reference and cause java.lang.OutOfMemoryError: PermGen space in tomcat web
server. Another common culprit is ThreadLocal, avoid using it until you need it absolutely, if do you
make sure to set them null or free any object ThreadLocal variables are holding.

Another Simple Solution is to increase PermGen heap size in catalina.bat or catalina.sh of tomcat
server; this can give you some breathing space but eventually this will also return in
java.lang.OutOfMemoryError: PermGen space after some time.

Steps to increase PermGen Heap Space in Tomcat:

1) Go to Tomcat installation directory i.e C:\Program Files\Apache Software Foundation\Apache


Tomcat 7.0.14\bin in Windows and something similar in linux.

2) Add JAVA_OPTS in your catalina.bat or Catalina.sh

In Windows:

set JAVA_OPTS="-Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m


-XX:PermSize=256m -XX:MaxPermSize=356m"

In linux:
export JAVA_OPTS="-Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m
-XX:PermSize=256m -XX:MaxPermSize=356m"

You can change the actual heap size and PermGen Space as per your requirement.

3) Restart Tomcat.

As I said earlier increasing PermGen space can prevent java.lang.OutOfMemoryError: PermGen


in tomcat only for some time and it will eventually occur based on how many times you redeploy your
web application, its best to find the offending class which is causing memory leak in tomcat and fix it.

Related Java Tutorials

How to Solve Java.lang.ClassNotFoundException in Java

Difference between NoClassDefFoundError and ClassNotFoundException in Java

How to fix Bad version number in .class file

Difference between ArrayList and Vector in Java

How SubString works in Java

Difference between SynchronizedCollection and ConcurrentCollection in Java

Difference between Comparator and Comparable in Java

Share on email Share on delicious Share on linkedin Share on stumbleupon Share on reddit Share on digg
Share on dzone Share on hackernews More Sharing Services

You might like:

 What is Marker interfaces in Java and why required


 Difference between Serializable and Externalizable in Java Serialization

 What is Race Condition in multithreading – 2 Examples in Java

 Top 10 Servlet Interview Question Answers - J2EE


Recommended by
Posted by Javin Paul at 12:48 AM

Email This BlogThis! Share to Twitter Share to Facebook

Labels: core java , jsp-servlet

Location: United States

19 comments :

Anonymous said...

Why people so much afraid of java.lang.OutOfMemoryError in Tomcat, Eclipse or


whatsoever ?

January 24, 2012 at 4:35 AM

hemant said...

this is a gud explanation and we also had this error driving us mad recently...

February 18, 2012 at 9:10 PM

Anonymous said...

You shouldn't include JDBC driver in your classpath because its better to use Database
Connection pool provided by J2EE Server or Tomcat instead of Managing JDBC Pool on
code. This not only removes dependency like JDBC driver, DBCP or any other jar but
also get rid of this OutOfMemroy Error in Tomcat by effectively shifting driver jar into
tomcat lib folder.

February 19, 2012 at 9:20 PM

Anonymous said...

You are correct I have faced java.lang.OutOfMemoryError: PermGen space on both


Tomcact 6 and Tomcat 7. though tomcat print useful information like whether its
ThreadLocal which is causing OutOfMemory etc but for permgen space you need to do
this analysis. the step we have taken is to increase PermGen and stop frequent redeploy of
webapp without restarting server.

July 22, 2012 at 6:30 PM

Sanju said...
You are correct I have faced java.lang.OutOfMemoryError: PermGen space on both
Tomcact 6 and Tomcat 7. though tomcat print useful information like whether its
ThreadLocal which is causing OutOfMemory etc but for permgen space you need to do
this analysis. the step we have taken is to increase PermGen and stop frequent redeploy of
webapp without restarting server.

July 22, 2012 at 6:30 PM

Memory leak detector said...

To find the "offending class which is causing memory leak in tomcat", use Plumbr. It
gives you the details of the leak, and also teaches how to solve the leak in-process.

August 9, 2012 at 12:04 AM

Udo Kuehne said...

There is a better way to proof the consumed memory of the Tomcat server process on
java.lang.OutOfMemoryError, see here http://technohandle.blogspot.de/2012/05/using-
visualvm-profiler-in-tomcat.html

January 20, 2013 at 3:27 PM

Udo Kuehne said...

You have a mistake in your setup of JVM options (maximum JVM heap size) "-
Xmx10246m" is to much memory.

That could be correct, when it exists 16g RAM on the used computer system.
Note: ms-windows should be running on 64 bit system.

January 20, 2013 at 3:40 PM

Anonymous said...

I am getting java.lang.OutOfMemoryError PermGen Space in Jetty Server, does any one


has experience with Jetty here ?

February 14, 2013 at 12:23 AM

Anonymous said...

from Java 8, Oracle is removing PermGen space from JVM, which means no
java.lang.OutOfMemoryError: PermGen space, instead they are introducing metaspace
which will give berth to a new set of OutOfMemoryError in Java
java.lang.OutOfMemoryError: Metaspace

March 4, 2013 at 1:53 AM

XCoder said...

For all those who use the installer version of tomcat. You can set it(java_opts) through
running tomcat6w.exe (configuration manager) and under the java tab, in the java/jvm
options textbox.

April 19, 2013 at 7:46 AM

Steward said...

@Anonymous is right, Java 1.8 has no PermGen Space, means, you don't need to worry
about outofmemory error in permgen space, but question is how many organization will
use Java 1.8, I think Java 1.6 is still most popular JDK out there, programmers and
companies have not adopted Java 7 till date, it will take another five years, before
Industry start using Java 1.8, till then keep debugging permgen memory leak :)

April 21, 2013 at 7:27 PM

Anonymous said...

The -Xmx10246m variable should be -Xmx1024m. There is a '6' that should not be there.

June 14, 2013 at 8:27 AM

Anonymous said...

hello javin,
i have a question.At the time of undeploy that application what happens exactly ? is it
free the reserved space or not. can you please give the answer.

June 29, 2013 at 4:47 AM

Abu al-Sous said...

Worked for me as is, inside and outside eclipse with Tomcat 7.

Many thanks

July 30, 2013 at 6:56 AM

Anonymous said...
Great article Javin, Though I agree that JDBC drivers especially MySQL JDBC Drivers
cause some classloader memory leak in tomcat, I am not fully agree with solution of
putting JDBC drivers on Tomcat lib. MySQL JDBC driver has some bug in there earlier
versions, prior to 5.1.23, which creates threads for cleaning up abandoned connection, but
that outlive web application. A better solution to fix java.lang.OutOfMemoryError:
PermGen Space due to memory leak caused by JDBC drivers or Threads in general is
stopping them during Application redeploy. One way of doing this in web application is
by adding ServletContextListener, which defines contextDestroyed(ServletContext ctx)
method. This method is called during undeploy, stopping any cleanup thread e.g. MySQL
abandoned connection cleanup thread, can prevent this classloader memory leak. This is
the general approach for fixing memory leak, but in particular cases, like in this case you
can simply upgrade MySQL JDBC Driver to version 5.1.23 or above.

August 13, 2013 at 7:05 PM

Anonymous said...

Hello, I am getting following error on Tomcat Server's catalina.out file :

SEVERE: The web application registered the JDBC driver [oracle.jdbc.OracleDriver] but
failed to unregister it when the web application was stopped. To prevent a memory leak,
the JDBC Driver has been forcibly unregistered.

org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application appears to have started a thread named [Thread-10] but
has failed to stop it. This is very likely to create a memory leak.

and

SEVERE: The web application created a ThreadLocal with key of type


[java.lang.ThreadLocal] (value [java.lang.ThreadLocal@64b43\712c]) and a v
alue of type [org.apache.logging.log4j.core.async.AsyncLogger.Info] (value
[org.apache.logging.log4j.core.async.AsyncLogger$Info@3404e643e]) but failed
to remove it when the web application was stopped. This is very likely to create a
memory leak.

Any idea how to resolve these error and prevent them from coming again? I am using
Tomcat 6 installations.

September 30, 2013 at 2:09 AM

Anonymous said...
As per your suggestion, I have moved my driver JAR to tomcat's lib directly but now my
application is not starting any more, I always getting HTTP 404 error, whenever I access
my application, please help

September 30, 2013 at 2:15 AM

himanshu deriya said...

how add JAVA_OPTS please give me solution . it's very important

April 21, 2014 at 5:00 AM

Post a Comment

Newer Post Older Post Home

Subscribe to: Post Comments ( Atom )

Best of Javarevisited
 10 Examples of Lambda Expressions in Java 8
 9 Difference between TCP and UDP Protocol

 20 Java 8 Date and Time API Examples

 10 Points about NULL in Java

 Where is Java used in Real World

 10 Object Oriented Design Principle Every Programmer Should Know

 10 Articles Every Programmer Must Read

 Difference between Java and Scala Programming

 How Android App works, A Java Programmers Introduction

Followers
Follow Us

Follow @javinpaul
Subscribe by email:

By Javin Paul

Blog Archive

 ► 2015 ( 38 )

 ► 2014 ( 106 )

 ► 2013 ( 136 )

 ▼ 2012 ( 217 )

o ► December ( 52 )

o ► November ( 8 )

o ► October ( 14 )

o ► September ( 8 )

o ► August ( 9 )

o ► July ( 9 )

o ► June ( 12 )

o ► May ( 10 )

o ► April ( 14 )

o ► March ( 28 )

o ► February ( 18 )

o ▼ January ( 35 )

 How to reverse String in Java using Iteration and ...

 Sudden Drop in Traffic? Could be Google page layou...

 How to get and set default Character encoding or C...

 How to define Error page in Java Web Application -...

 How to fix java.sql.SQLException: Invalid column i...

 Difference between Thread vs Runnable interface in...


 Top 10 Google Interview Questions Answers for Soft...

 How to find if JVM is 32 or 64 bit from Java progr...

 What is Constructor overloading in Java with Examp...

 Difference between Serializable and Externalizable...

 Difference between URL-rewriting URL-encoding in S...

 How to get max memory, free memory and total memor...

 How to use Assertion in Java Code - When, Where

 How to enable or disable Assertion in Java

 JDBC Performance Tips - 4 Tips to improve performa...

 How to Sort Array in Java ascending and descending...

 What is Assertion in Java - Java Assertion Tutoria...

 How to hide file from Java Program with Code Examp...

 How to check if a File is hidden in Java with Exam...

 How to get current Date Timestamps in Java on GMT ...

 Difference between include directive and include a...

 10 Example of this keyword in Java

 How to Sort Java ArrayList in Descending Order - E...

 How to write Thread-Safe Code in Java

 How to create and initialize Anonymous array in Ja...

 How to convert ArrayList to Set in Java with Examp...

 What is FIX Engine in FIX Protocol

 REST Web services Framework interview questions an...

 How to Change or Set File Permissions in Java – Co...

 How to Use Code Point Methods of Java String get U...

 10 Example of Hashtable in Java – Java Hashtable T...

 Why use Memory Mapped File or MapppedByteBuffer in...

 How to check File Permission in Java with Example ...

 What is Marker interfaces in Java and why required...


 Tomcat – java.lang.OutOfMemoryError: PermGen space...

 ► 2011 ( 145 )

 ► 2010 ( 33 )

References

 Java API documentation JDK 6

 Spring framework doc

 Struts

 JDK 7 API

 MySQL

 Linux

 Eclipse

 jQuery

Copyright by Javin Paul 2012. Powered by Blogger.

 About Me
 Privacy Policy

AddThis Sharing

Read more: http://javarevisited.blogspot.com/2012/01/tomcat-javalangoutofmemoryerror-


permgen.html#ixzz3WEGvUJU8

Javarevisited
Blog about Java programming language, FIX Protocol, Tibco Rendezvous and related Java
technology stack.

 android
 ant tutorials
 Array
 Autosys
 Bash
 batch file
 best practices
 books
 cloud computing
 coding
 core java
 core java interview question
 data structure and algorithm
 database
 date and time tutorial
 debugging
 design patterns
 Eclipse
 error and exception
 FIX protocol tutorial
 general
 hibernate
 HTML and JavaScript
 interview questions
 J2EE
 java 5 tutorial
 Java 7
 Java 8
 Java Certification OCPJP SCJP
 java collection tutorial
 java IO tutorial
 Java JSON tutorial
 Java multithreading Tutorials
 java networking tutorial
 Java Programming Tutorials
 Java xml tutorial
 JDBC
 JQuery
 jsp-servlet
 JSTL
 JUnit
 JUnit testing
 linux
 logging
 Maven
 MQ Series
 mysql
 object oriented programming
 oracle database
 performance
 programmers
 programming
 Scala
 spring
 SQL
 SQL Interview Questions
 SSL
 String
 Sybase and SQL Server
 thread
 tibco
 xml
 xslt

Saturday, December 29, 2012

Difference between equals method and "=="


operator in Java - Interview Question
Both equals() and "==" operator in Java is used to compare objects to check equality but main difference
between equals method and == operator is that former is method and later is operator. Since Java doesn’t support
operator overloading, == behaves identical for every object but equals() is method, which can be overridden in
Java and logic to compare objects can be changed based upon business rules. Another notable difference between
== and equals method is that former is used to compare both primitive and objects while later is only used for objects
comparison. At the same time beginners struggle to find when to use equality operator (==) and when to use equals
method for comparing Java objects. In this tutorial we will see how equals() method and == operator works in
Java and what is difference between "==" and equals method in Java and finally when to use "==" and equals() to
compare objects.

What is "==" equality operator in Java

"==" or equality operator in Java is a binary operator provided by Java programming language and used to
compare primitives and objects. In terms of comparing primitives like boolean, int, float "==" works fine but
when it comes to compare objects it creates confusion with equals method in Java. "==" compare two objects based
on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly
same object otherwise "==" will return false. After introduction of Autoboxing and unboxing in Java 5, using == to
compare wrapper objects even become trickier because some time they can return unexpected result. See my post
what is problem with == operator in autoboxing world post Java 5 for more details.

What is equals method in Java


Equals() method is defined in Object class in Java and used for checking equality of two object defined by
business logic e.g. two Employees are considered equal if they have same empId etc. You can have your domain
object and than override equals method for defining condition on which two domain objects will be considered equal.
equal has contract with hashcode method in Java and whenever you override equals method you also need to
override hashcode() in Java. Default implementation of equals provided in Object class is similar to "==" equality
operator and return true if you are comparing two references of same object. It’s one of the Java best practice to
override equals in Java to define equality based on business requirement. It’s also worth noting that equals should be
consistent with compareTo in Java, So that when you store objects in TreeMap or TreeSet Collection, which uses
compareTo for checking equality, behavior remains consistent.

Difference between == and equals in Java


Main difference between == and equals in Java is that "==" is used to compare primitives while equals()
method is recommended to check equality of objects. Another difference between them is that, If both "==" and
equals() is used to compare objects than == returns true only if both references points to same object while
equals() can return true or false based on its overridden implementation.One of the popular case is comparing two
String in Java in which case == and equals() method return different results.

Comparing String with == and equals


String comparison is a common scenario of using both == and equals method. Since java.lang.String class
override equals method, It return true if two String object contains same content but == will only return true if two
references are pointing to same object. Here is an example of comparing two Strings in Java for equality using ==
and equals() method which will clear some doubts:

String personalLoan = new String("cheap personal loans");


String homeLoan = new String("cheap personal loans");

//since two strings are different object result should be false


boolean result = personalLoan == homeLoan;
System.out.println("Comparing two strings with == operator: " + result);

//since strings contains same content , equals() should return true


result = personalLoan.equals(homeLoan);
System.out.println("Comparing two Strings with same content using equals method: " +
result);

homeLoan = personalLoan;
//since both homeLoan and personalLoand reference variable are pointing to same object
//"==" should return true
result = (personalLoan == homeLoan);
System.out.println("Comparing two reference pointing to same String with == operator:
" + result);

Output:
Comparing two strings with == operator: false
Comparing two Strings with same content using equals method: true
Comparing two reference pointing to same String with == operator: true

Comparing two objects with "==" and equals.


Another scenario which creates confusion between == and equals method is when you compare two Objects. When
you compare two references pointing to object of type Object you should see same result from both == operator
and equals method because default implementation of equals method just compare memory address of two objects
and return true if two reference variable are pointing towards exactly same object. Here is example of == vs equals
method for comparing two objects:

Object obj1 = new Object();


Object obj2 = new Object();

// == should return false


result = (obj1==obj2);
System.out.println("Comparing two different Objects with == operator: " + result);
//equals should return false because obj1 and obj2 are different
result = obj1.equals(obj2);
System.out.println("Comparing two different Objects with equals() method: " + result);

// "==" should return true because both obj1 and obj2 points same object
obj1=obj2;
result = (obj1==obj2);
System.out.println("Comparing two reference pointing to same Object with == operator:
" + result);

Output:
Comparing two different Objects with == operator: false
Comparing two different Objects with equals() method: false
Comparing two reference pointing to same Object with == operator: true

Summary
1) use == to compare primitive e.g. boolean, int, char etc, while use equals() to compare objects in Java.
2) == return true if two reference are of same object. Result of equals() method depends on overridden
implementation.
3) For comparing String use equals() instead of == equality operator.

That’s all on difference between equals method and == operator in Java. As I said main difference between
them is that one of them is operator and other is method and == is used to compare both primitive and objects while
equals() method is used to check equality of objects only.

Other Java Interview question articles from Javarevisited blog


Why multiple inheritance is not supported in Java
Why wait and notify method called from synchronized block or method
Difference between start and run method in Java
Why main method is static in Java
Difference between transient and volatile in Java

Share on email Share on delicious Share on linkedin Share on stumbleupon Share on reddit
Share on digg Share on dzone Share on hackernews More Sharing Services
You might like:
 What is Autoboxing and Unboxing in Java – Example Tutorial and Corner cases
 Overriding equals() and hashCode() method in Java and Hibernate

 Difference between Method Overloading and Overriding in Java?


 How to Compare two String in Java - String Comparison Example

Recommended by
Posted by Javin Paul at 6:15 PM
Email This BlogThis! Share to Twitter Share to Facebook
Labels: core java , core java interview question , programming
Location: United States

2 comments :

Sagar said...
class Printdate
{
static int d,m,y;

public Printdate(int d,int m,int y)


{
this.d=d;
this.m=m;
this.y=y;
}

public static void disp()


{
System.out.println(d+"/"+m+"/"+y);
}

public static void main(String[] args)


{
Printdate p =new Printdate(28,11,14);
Printdate e =new Printdate(28,11,14);

if (p.equals(e))
{
System.out.println("Dates are same");
disp();
}
else
{
System.out.println("Dates are different");
System.out.println(p.hashCode());
System.out.println(e.hashCode());
}

}
}
for the above code m getting output as Dates are different.
kindly help me to find my mistake.

November 27, 2014 at 10:00 PM


Anonymous said...

@sagar if you dont override equals method in your class it behaves as == operator which
returns true if objects point same memory address.

January 15, 2015 at 12:55 AM


Post a Comment

Newer Post Older Post Home


Subscribe to: Post Comments ( Atom )
Top of Form

Top of Form

Best of Javarevisited
 10 Examples of Lambda Expressions in Java 8
 9 Difference between TCP and UDP Protocol
 20 Java 8 Date and Time API Examples
 10 Points about NULL in Java
 Where is Java used in Real World
 10 Object Oriented Design Principle Every Programmer Should Know
 10 Articles Every Programmer Must Read
 Difference between Java and Scala Programming
 How Android App works, A Java Programmers Introduction

Followers
Follow Us

Follow @javinpaul

Subscribe by email:

By Javin Paul

Blog Archive

 ► 2015 ( 38 )

 ► 2014 ( 106 )

 ► 2013 ( 136 )
 ▼ 2012 ( 217 )
o ▼ December ( 52 )

 Top 10 Oracle Interview Question and Answer - Dat...


 How to compare Arrays in Java – Equals vs deepEqua...
 How to append text into File in Java – FileWriter ...
 Difference between equals method and "==" operator...
 How to add, subtract days, months, years, hours fr...
 Difference between Primary key vs Foreign key in t...
 How to fix java.lang.classcastexception cannot be ...
 Difference between Class and Object in Java and OO...
 How to attach source in eclipse for Jars, debuggin...
 How to find middle element of LinkedList in Java i...
 Recursion in Java with example – Programming Techn...
 What is Referential Integrity in Database or SQL -...
 How to create thread safe Singleton in Java - Java...
 Oracle 10g Pagination Query - SQL Example for Java...
 How to convert milliseconds to Date in Java - tuto...
 3 Example to print array values in Java - toString...
 How to check if a number is a palindrome or not in...
 Inner class and nested Static Class in Java with E...
 How to add, modify and drop column with default va...
 What is Type Casting in Java - Casting one Class ...
 How to create auto incremented identity column in ...
 How to parse or convert String to long in Java - 4...
 How to fix java.io.NotSerializableException: org.a...
 How to initialize ArrayList with Array in Java | C...
 How to Create and Evaluate XPath Expression in Jav...
 How to Split String in SQL Server and Sybase
 How to get current date, month, year and day of we...
 How to create and modify Properties file form Java...
 How to Count Occurrences of a Character in String ...
 How to read input from command line in Java using ...
 How to remove duplicates elements from ArrayList i...
 How to find second highest or maximum salary of Em...
 XPath Tutorial - How to select elements in XPATH b...
 Constructor Chaining in Java - Calling one constru...
 How to escape String literal in Java using Eclipse...
 Invalid initial and maximum heap size in JVM - How...
 SQL query to copy, duplicate or backup table in My...
 How to sort HashMap by key and value in Java - Has...
 Does Java pass by value or pass by reference - Int...
 Mapping network drive in Windows XP and 7 – net us...
 Inversion of Control and Dependency Injection desi...
 Java Error : 'javac' is not recognized as an inter...
 How to find duplicate records in a table on databa...
 java.lang.ClassNotFoundException: oracle.jdbc.driv...
 What is Constructor in Java with Example – Constru...
 How to comment uncomment single line and block of ...
 Union and Intersection of two Set in Java - Google...
 How ClassLoader Works in Java
 Top 10 JDBC Interview questions answers for Java p...
 What is Object in Java Programming and OOPS - Exam...
 BlockingQueue in Java – ArrayBlockingQueue vs Link...
 Why getter and setter are better than public field...
o ► November ( 8 )

o ► October ( 14 )

o ► September ( 8 )

o ► August ( 9 )

o ► July ( 9 )

o ► June ( 12 )

o ► May ( 10 )

o ► April ( 14 )

o ► March ( 28 )

o ► February ( 18 )

o ► January ( 35 )

 ► 2011 ( 145 )

 ► 2010 ( 33 )

References

 Java API documentation JDK 6

 Spring framework doc

 Struts

 JDK 7 API

 MySQL

 Linux

 Eclipse
 jQuery

Copyright by Javin Paul 2012. Powered by Blogger.


 About Me
 Privacy Policy

AddThis Sharing

Read more: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-


equality-operator-java.html#ixzz3WEH1MELU

Javarevisited

Blog about Java programming language, FIX Protocol, Tibco Rendezvous and related Java
technology stack.

Ad by SalePlus | Close
 android
 ant tutorials
 Array
 Autosys
 Bash
 batch file
 best practices
 books
 cloud computing
 coding
 core java
 core java interview question
 data structure and algorithm
 database
 date and time tutorial
 debugging
 design patterns
 Eclipse
 error and exception
 FIX protocol tutorial
 general
 hibernate
 HTML and JavaScript
 interview questions
 J2EE
 java 5 tutorial
 Java 7
 Java 8
 Java Certification OCPJP SCJP
 java collection tutorial
 java IO tutorial
 Java JSON tutorial
 Java multithreading Tutorials
 java networking tutorial
 Java Programming Tutorials
 Java xml tutorial
 JDBC
 JQuery
 jsp-servlet
 JSTL
 JUnit
 JUnit testing
 linux
 logging
 Maven
 MQ Series
 mysql
 object oriented programming
 oracle database
 performance
 programmers
 programming
 Scala
 spring
 SQL
 SQL Interview Questions
 SSL
 String
 Sybase and SQL Server
 thread
 tibco
 xml
 xslt

Friday, January 16, 2015

Top 20 String Algorithm Questions from


Coding Interviews
In this article we are going to see top 20 String based coding interview question and their
solution to help programmers better prepare for interviews. String is one of the most important
data structure and available in almost every programming language e.g. Java, C, C++, Python,
Perl and Ruby. Though there implement differ but essence remain same e.g. String is NULL
terminated character array in C but String is object in Java, again backed by character array.
String is also available on weekly typed language e.g. Python and Perl. This is why, you will
always find some String based coding question on programming interview. Even in your college
days, you would have solved lots of coding problems based upon String like reversing String in
place, checking if String is palindrome, checking if two strings are anagram of each other,
calculating permutations of String etc. Coding questions asked on Programming interview is not
very different from that, but yes it gets slightly more difficult with your experience, For example,
in your first few programming job interview, you may find questions like removing duplicates
from String or replacing all spaces with %20, but as you get more experience and apply for
senior developer position, you can expect tough questions like how to find longest palindrome in
a string or printing all permutations of String etc. This article contains both easy and difficult
String coding questions for your preparation. I have not posted the solution right behind the
problem so that you can give it a shot before checking solution. You can solve these String based
coding question on any language of your choice e.g. C, C++, Java, Python or even Perl.

20 String Algorithm based Coding Interview Questions

Here is my collection of some of the most frequently asked String based coding questions from
programming interview. Remember, there are many algorithms to solve the same problem, and
you should know that, mainly to handle follow-up question better. Also remember to solve same
question using both recursion and iteration, as interviewer really like to ask iterative version if
you come up with recursive algorithm and vice-versa. Nevertheless, if you see your favorite
question is not included in list, feel free to suggest, I will include it. You can also post question
asked to you on your interview and you have not find its solution yet. Some questions are still
unsolved or solution is not yet posted on my blog. Also difficult level increases as you move
questions.

1) How to Print duplicate characters from String? (solution)


To start with, we have a simple String related coding question frequently asked in programming
interviews. You need to write a program in C, C++, Java or Python to print duplicate characters
from a given String, for example if String is "Java" then program should print "a". Bonus
points if your program is robust and handle different kinds of input e.g. String without duplicate,
null or empty String etc. Bonus points if you also write unit tests for normal and edge cases.

2) How to check if two Strings are anagrams of each other? (solution)

A simple coding problem based upon String, but could also be asked with numbers. You need to
write a Java program to check if two given strings are anagrams of Each other. Two strings are
anagrams if they are written using the same exact letters, ignoring space, punctuation and
capitalization. Each letter should have the same count in both strings. For
example, Army and Mary are anagram of each other.

3) How to program to print first non repeated character from String? (solution)

One of the most common string interview questions: Find the first non-repeated (unique)
character in a given string. for Example if given String is "Morning" then it should print "M".
This question demonstrates efficient use of Hashtable. We scan the string from left to right
counting the number occurrences of each character in a Hashtable. Then we perform a second
pass and check the counts of every character. Whenever we hit a count of 1 we return that
character, that’s the first unique letter. Be prepared for follow-up question for improving memory
efficiency, solving it without hash table as well.

4) How to reverse String in Java using Iteration and Recursion? (solution)

Your task is to write a program to reverse String in Java without using StringBuffer class. You
also need to provide both iterative and recursive algorithm for String reversal. You can use other
String utility methods
e.g. charAt(), toCharArray() or substring() from java.lang.String class.

5) How to check if a String contains only digits? (solution)

You need to write a program to check a String contains only numbers by using Regular
expression in Java. You can use Java API but a solution without using Java API will be better
because that is what interviewer can always ask.

6) How to find duplicate characters in a String? (solution)

You need to write a program to print all duplicate character and their count in Java. For example
if given String is "Programming" then your program should print
g:2
r:2
m:2

7) How to count number of vowels and consonants in a String? (solution)

One of easiest String question you will ever see. You have to write a Java program which will
take a String input and print out number of vowels and consonants on that String. For example if
input is "Java" then your program should print "2 vowels and 2 consonants". If you
get this question on Interview, you should clarify that whether String can contain numbers,
special characters or not e.g. anything other than vowels and consonants.

8) How to count occurrence of a given character in String? (solution)

If interviewer ask you to count occurrence of more than one character than you can either use an
array, hash table or any additional data structure. In order to solve this problem, you are not
allowed to do so. Your method must return count of given character, for example if input String
is "Java" and given character is 'a' then it should return 2. Bonus point if you handle case, null
and empty String and come up with unit tests.

9) How to convert numeric String to int? (solution)

A classical coding interview question based upon String. You need to write a method like atoi()
from C/C++, which takes a numeric String and return its int equivalent. For example, if you pass
"67263" to the program then it should return 67263. Make sure your solution is robust i.e. it
should be able to handle + and - character, null and empty String, integer overflow and other
corner cases. Bonus points if you come up with good unit test cases. By the way, if your
interviewer doesn't mention to you about atoi() then you can also use Java
API's parseInt() or valueOf() method to solve this problem.

10) How to replace each given character to other e.g. blank with %20? (solution)

Write a Java program to replace a given character in a String to other provided character, for
example if you are asked to replace each blank in a String with %20, similar to URL encoding
done by browser, so that Server can read all request parameters. For example if input is "Java is
Great" and asked to replace space with %20 then it should be "Java%20is%20Great".

11) How to find all permutations of String? (solution)

I have seen this String interview question on many interviews. It has a easy recursive solution
but thinks get really tricky when Interviewer ask you to solve this question without using
recursion. You can use Stack though. Write a program to print all permutations of a String in
Java, for example if input is "xyz" then it should
print "xyz", "yzx", "zxy", "xzy", "yxz", "zyx".

12) How to reverse words in a sentence without using library method? (solution)

Write a function, which takes a String word and return sentence on which words are reversed in
order e.g. if input is "Java is best programming language", output should be "language
programming best is Java".

13) How to check if String is Palindrome?(solution)

Another easy coding question based upon String, I am sure you must have done this numerous
time. Your program should return true if String is Palindrome, otherwise false. For example, if
the input is "radar", the output should be true, if input is "madam" output will be true, and if
input is "Java" output should be false.

14) How to remove duplicate characters from String? (solution)

This is one of the interesting String question, which also has lots of variants. You need to remove
duplicate characters from a given string keeping only the first occurrences. For example, if the
input is ‘bananas’ the output will be ‘bans’. Pay attention to what output could be, because
if you look closely original order of characters are retained in output. This is where many
developer make mistake of shorting character array of String and removing duplicates, similar
to how you remove duplicates from array. That destroys original order of characters and will not
be correct solution in this case.

15) How to check if a String is valid shuffle of two String? (solution)

One more difficult String algorithm based coding question for senior developers. You are given 3
strings: first, second, and third. third String is said to be a shuffle of first and second if
it can be formed by interleaving the characters of first and second String in a way that maintains
the left to right ordering of the characters from each string. For example, given first
= "abc" and second = "def", third = "dabecf" is a valid shuffle since it preserves the
character ordering of the two strings. So, given these 3 strings write a function that detects
whether third String is a valid shuffle of first and second String.

16) Write a program to check if a String contains another String e.g. indexOf()? (solution)
You need to write a function to search for the existence of a string (target) in another string
(source). The function takes two strings as the input and returns the index where the second
string is found. If the target string cannot be found, then return -1. If you are a Java developer,
then you can related its behavior to indexOf() method from java.lang.String class. This
question is also asked as Code and algorithm to check if a given short string is a substring of a
main string. Can you get a linear solution (O(n)) if possible?

17) How to return highest occurred character in a String? (solution)

You need to write a function to implement algorithm which will accept a string of characters and
should find the highest occurrence of the character and display it. For example if input is
"aaaaaaaaaaaaaaaaabbbbcddddeeeeee" it should return "a".

18) Write a program to remove a given characters from String? (solution)

One of my favorite coding question, when I interview Java developers. You need to write a Java
method which will accept a String and a character to be removed and return a String, which
doesn't has that character e.g remove(String word, char ch). You need to provide
both iterative and recursive solution of this method and also has to write JUnit tests to cover
cases like null and empty String, input which only contains letter to be removed, String which
doesn't contain given character etc.

19) Write a program to find longest palindrome in a string? (solution)

This is one of the tough coding question based upon String. It's hard to think about an algorithm
to solve this problem until you have practiced good. What makes it more difficult is the
constraint that your solution has O(n) time complexity and O(1) space complexity.

20) How to sort String on their length in Java? (solution)

Write a Program to sort String on their length in Java? Your method should accept an array of
String and return a sorted array based upon length of String. Don't forget to write unit tests for
your solution.

That's all on this list of 15 String Algorithm based coding questions. These are really good
question to prepare for programming interview, not only you can expect same question on real
interview but also it will prepare you how to tackle algorithmic coding interview questions. Even
if you don't find same question, you would be able to apply the knowledge you gain by solving
these question by yourself. Always remember, you are judged by the code you write, so always
write production quality code, which would pass general test, corner cases, invalid inputs,
robustness test and also pass performance test. Whenever asked to solve a coding problem,
always think about all possible input and write test for that.
Share on emailShare on deliciousShare on linkedinShare on stumbleuponShare on redditShare
on diggShare on dzoneShare on hackernewsMore Sharing Services
You might like:
 How to check if two String are Anagram in Java - Program Example
 How to Convert String to Integer to String in Java with Example

 Java Clone Tutorial Part 2 - Example to Override with Mutable field


 How to reverse String in Java using Iteration and Recursion

Recommended by
Posted by Javin Paul at 7:51 AM
Email This BlogThis! Share to Twitter Share to Facebook
Labels: coding , Coding Interview Question , core java , String

2 comments :

Anonymous said...

Can you also add some puzzles based on parent-child or recursion.

January 22, 2015 at 2:33 AM


Anonymous said...

What language would you advise as a monthly typed language?

February 18, 2015 at 3:56 AM

Post a Comment

Newer Post Older Post Home


Subscribe to: Post Comments ( Atom )
Top of Form

Top of Form

Best of Javarevisited
 10 Examples of Lambda Expressions in Java 8
 9 Difference between TCP and UDP Protocol
 20 Java 8 Date and Time API Examples
 10 Points about NULL in Java
 Where is Java used in Real World
 10 Object Oriented Design Principle Every Programmer Should Know
 10 Articles Every Programmer Must Read
 Difference between Java and Scala Programming
 How Android App works, A Java Programmers Introduction

Ad by SalePlus | Close

Followers
Follow Us

Follow @javinpaul

Subscribe by email:

By Javin Paul

Blog Archive

Ad by SalePlus | Close
 ▼ 2015 ( 40 )
o ► April ( 2 )

o ► March ( 10 )

o ► February ( 12 )

o ▼ January ( 16 )

 What is rt.jar in Java/JDK/JRE? Why it’s Important...


 How to convert Binary Number to Decimal in Java - ...
 How to use Future and FutureTask in Java Concurren...
 What is difference between Maven, ANT, Jenkins and...
 Solaris Command to Show Long argument list of a Ru...
 Difference between Functional and Non-Functional R...
 Java Clone Tutorial Part 2 - Example to Override w...
 Print Fibonacci Series in Java Using Recursion and...
 Top 20 String Algorithm Questions from Coding Inte...
 How to use Lambda Expression in Place of Anonymous...
 Top 5 Blogs Java EE developers should follow
 Why Override equals, hashcode and toString method ...
 Difference between Bitwsie and Logical Operator in...
 Top 5 Java Forums for Programmers
 3 Examples to Concatenate String in Java
 Adapter vs Decorator vs Facade vs Proxy Design Pat...

 ► 2014 ( 106 )

 ► 2013 ( 136 )

 ► 2012 ( 217 )

 ► 2011 ( 145 )

 ► 2010 ( 33 )

Ad by SalePlus | Close
Ad by SalePlus | Close

References

 Java API documentation JDK 6

 Spring framework doc

 Struts

 JDK 7 API

 MySQL
 Linux

 Eclipse

 jQuery

Copyright by Javin Paul 2012. Powered by Blogger.


 About Me
 Privacy Policy

AddThis Sharing

Ad by SalePlus | Close
Ad by SalePlus | Close

Read more: http://javarevisited.blogspot.com/2015/01/top-20-string-coding-interview-question-


programming-interview.html#ixzz3WgsQtuGi

How To Do In Java
Search

Skip to content

 Interview
o Java Interview Questions

o Core Java Interview Questions : Part 1

o Core Java Interview Questions : Part 3

o Core Java Interview Questions : Part 2

o Collections interview questions

o Interview Questions Asked in Oracle

o Spring Core Interview Questions

o Spring AOP Interview Questions

o Spring MVC Interview Questions


 Popular Tutorials

o Java Best Practices

o RESTEasy

o Spring

o Hibernate

o Regular Expressions

o New I/O

o Maven

o Log4j

o JUnit

o TestNG

o iBatis

 Design Patterns

o Creational

o Behavioral

o Structural

 Core Java

o Interview

o Cloning

o Collections

o Exception Handling

o Java I/O

o Serialization

o Multi Threading

o Garbage collection

o String class

o Generics
o Inner classes

o Related Concepts

o NIO

 Frameworks

o RESTEasy

o Spring

 Spring Hello World

 Spring AOP

 Spring Core

 Spring Integration

 Spring MVC

 Spring ORM

 Spring REST

 Spring Security

o Struts 2

o Maven

o Hibernate

o iBatis

o HornetQ

o JAXB

o Jersey

o JSTL

o Junit

o Log4j

o OSCache

 JDK Specific Features

o Java 8 Features
o Java 7 Features

o Java 5 Features

 More Topics

o Puzzles

o Best practices

o Object Oriented

o Scripting

o For fun only

o Optimization

o Apache commons

o XML

o Linux

o SQL

o Random Exceptions

o Regular Expressions

o Resource Loading

o Searching and Sorting

o Security

o Free Resources

You are here: Home > Core Java > Interview > Java interview question: Why Strings are
immutable?

Java interview question: Why Strings are


immutable?
Follow @HowToDoInJava, Read RSS Feed

This is no doubt, most asked beginner level java interview question. And sometimes you can
face at medium level interviews also. So, my suggestion is to learn it here and for ever.
Lets start with immutability itself. An immutable object is an object which state is
guaranteed to stay identical over its entire lifetime. This is really a good definition. Isn’t it? It
means that the state of object once initialized, can never be changed anyhow.

Normally immutability in java is achieved through following steps :

1. Don’t provide mutator methods for any field


2. Make all fields final and private

3. Don’t allow subclasses by declaring the class final itself

4. Return deep cloned objects with copied content for all mutable fields in class

Please note that while it is possible to implement immutability without


"final" keyword, its use
makes that purpose explicit, to the human (the software developer) and the
machine (the compiler).

Java also has its share of immutable classes which are primarily String class and wrapper
classes. In this post, we will understand the need of immutability for String class.

1) Security : The first and undeniably most important reason is security. Well, its not only about
your application, but even for JDK itself. Java class loading mechanism works on class names
passed as parameters, then these classes are searched in class path. Imagine for a minute,
Strings were mutable, then anybody could have injected its own class-loading mechanism with
very little effort and destroyed or hacked in any application in a minute.

[ Well, I think in this case java didn’t have got any popularity today… and nobody would be
using it]. It means Strings were immutable that’s why java is still around in the game.

2) Performance : I believe that it is not the immutability of String class that gives it
performance, rather it is string pool which works silently behind the scene. But at the same time,
string pool is not a possibility without making String class immutable. So, it all again comes
down to immutability of String class which allowed string pools, and thus better
performance.

3) Thread safety: Immutable objects are safe when shared between multiple threads in multi-
threaded applications. Just understand and learn it. There is no super logic. If something can’t be
changed, then even thread can not change it.

As String class is main building block of java programming language, because of its use in class
loading mechanism, it was indeed a must use case to prevent the String class from being dirty
in case of multiple thread. Immutability does the magic here.

I think its enough reasoning to satisfy the need of interviewer. If after these explanations he is not
satisfied, he never will be.

Happy Learning !!
Related posts:
1. Interview stuff about String class in java
2. How to make a java class immutable

3. Core java interview questions series : Part 3

4. Core java interview questions series : Part 1

5. Popular HashMap and ConcurrentHashMap interview questions

6. Core java interview questions series : Part 2

7. 4 ways to split/tokenize Strings in java

8. Useful java collection interview questions

immutabilityInterview QuestionJava StringString pool

12 thoughts on “Java interview question: Why Strings are


immutable?”
1. Sumit

February 11, 2015 at 10:58 am

If string is immutable then how can we create its object using new ,i.e, String a= new
String (“Test”);

Reply

1. Lokesh

February 11, 2015 at 11:09 am

Perhaps you are confusing with singleton and immutability. Singleton prevents
instance creation (allows only one). But immutability does not prevent creating
new instances, it just prevents the state of instance once it is fully created.

Reply

1. Sumit

February 11, 2015 at 2:21 pm

Thanks for the prompt response…


i got your point but string is both singleton and immutable and as i know
we cannot create instance of a singleton class using new operator but in
case of string we can, so i am bit confused .Please help!!!

Reply

1. Lokesh

February 11, 2015 at 2:25 pm

Where you read that String class is singleton. It’s incorrect.

Reply

2. shekhar

September 19, 2014 at 4:58 pm

could not understand about class loading , how does it break ?

Reply

3. sagar

November 19, 2013 at 9:08 pm

can u post something on class loading architecture and the diff types of loaders.

Reply

4. ankit sharma

October 25, 2013 at 12:32 pm

hey i’m freeshar i want know about java and future in java

Reply

1. Lokesh Gupta

October 25, 2013 at 10:59 pm

You will be secured for your lifetime if you managed to be a good programmer.

Reply
5. Anant

August 12, 2013 at 10:32 am

Hi, I didn’t understand this statement in above explainations about hacking , “Imagine for
a minute, Strings were mutable, then anybody could have injected its own class-loading
mechanism with very little effort and destroyed or hacked in any application in a minute”
Also ” string pool is not a possibility without making String class immutable” please
elaborate little more details on this discussions

Reply

1. Lokesh Gupta

August 12, 2013 at 10:33 pm

OK. So i got two things to explain. Lets make it clear one by one.

1) We know in java load classes using Class.forName(string). If Strings were


mutable, then someone wrote the code to load “java.io.Writer”. This string
variable will be in pool. Now, some evil code can access this pool and change the
string to “com.MakeHavocWriter” and now when code gets executed, one can
easily imagine the consequences.

2) String pool is there so that one String instance can be referred from multiple
reference variables. If string is mutable, then one object can change the string
content and other will see this undesired value.

See the fact is that String pool was designed for sake of performance, by
minimizing the total count of string instances (not references) in application
memory space. And as in above scenario, if pool makes the string values changing
undesirably, then no one will prefer to use it.

Reply

1. Francois

August 23, 2013 at 4:38 pm

security is not so obvious , it is mainly for performance, and thread safety i


would say/

about security , usually we done want to hack “Oracle java base class” but
applicative class
And there if you have a jar with for instance Checkpassword.class can can
use decompile it, look on the signature, and change the checkPass() to
return true, and wrap it to the jar (as very few jar are signed) and run the
application with it. so that you “hack” some how the class loader. and job
is done.

as a benefits to immutability and about performace


the hashcode of a string is computed only once (the first time you call
hashcode()) , that is a great point about perf ,( string is very often use in
hashmap.)

Reply

1. H Singh

October 14, 2013 at 6:51 pm

Hi Francois,

Can you please elaborate the last para from your reply.

Thanks.

Reply

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags
otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *

Email *

Website

Are you Human and NOT robot? Solve this to prove !! *


× 6 = thirty
Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title="">
<acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime="">
<em> <i> <q cite=""> <strike> <strong>

Notify me of follow-up comments by email.

Notify me of new posts by email.

Connect With Me
Recommended Reading
 10 Life Lessions
 How Web Servers Work?

 5 Class Design Principles

 32-bit Vs 64-bit JDK

 How IO works Internally?

 Signs of Bad Unit Testcases

 Unit Testing Best Practices

 Exception Handling Best Practices

 Complete AJAX Tutorial

Subscribe to Blog via Email


Email Address

References
 Oracle Java Docs
 Spring 3 Reference

 Spring 4 References

 Jboss RESTEasy JAX-RS

 Hibernate Developer Guide

 Junit Wiki

 Maven FAQs

 Dzone Dev Links

 JSP Homepage

 ANT Homepage

Meta Links
 Advertise
 Share your knowledge

 Privacy policy

 Contact Us

 About Us

Popular Posts
 Spring 3 and hibernate integration tutorial with example
 Reading/writing excel files in java : POI tutorial

 How hashmap works in java

 Singleton design pattern in java

 Useful java collection interview questions

 Working with hashCode and equals methods in java

 Understanding hibernate first level cache with example

 How hibernate second level cache works?

 How to make a java class immutable

 JAX-RS 2.0 RESTEasy 3.0.2.Final security tutorial


© 2012-2015 Lokesh Gupta All Rights Reserved

Stack Exchange
sign up log in tour help stack overflow careers

Stack Overflow
 Questions
 Tags

 Users
 Badges
 Unanswered

 Ask Question

Take the 2-minute tour ×


Stack Overflow is a question and answer site for professional and enthusiast programmers. It's
100% free, no registration required.

Tricky Java Strings Interview Q. Given


List<String> and char [] return longest string
containing only char []
Given a List of Strings and an array of characters, return the longest String that
contains only characters in the array.

I'm pretty sure I hosed it up. My first instinct was to use a regular expression but I
don't think anybody gets those right the first time and without looking anything up.

up vote 3 Is there a tricky way of doing this using bitwise operators or something?
down vote
favorite java string algorithm list char
2 edited Jul 16 '14 at 21:07 asked Jul 16 '14 at 20:55

shareimprove this question

Adam Stelmaszczyk user447607


9,06812253 449618
the easiest solution I can imagine is 2 nested loops – nikis Jul 16 '14 at 20:58
how large is the List of strings? And how long on average is each word?
There's these and many other questions you can ask before you try to be clever
and realize nothing's wrong with brute forcing it – Ben Jul 16 '14 at 20:58
I did use brute force, i.e. a double loop. It's a Q from one of the Ivy League
.coms out here in the Seattle area so I'm thinking it's trickier than that. –
user447607 Jul 16 '14 at 20:59
Can the result string contain repeated characters from the char array? –
user3790568 Jul 16 '14 at 21:22
I'd suggest either of the two: 1) convert char[] into set of chars which leads to
1 O(n) solution; 2) sort char[] and use binary search which leads to O(n log m)
solution. – Andrew Logvinov Jul 16 '14 at 21:36
add a comment

4 Answers
active oldest votes
up vote 2 The following code uses binary search on a sorted char array to efficiently check,
down vote if all characters of the string exist in the char[]. Note that binary search on an
accepted array is pretty fast due to cache locality.
public String longest(char[] chars, List<String> strings) {
char[] sorted = Arrays.copyOf(chars, chars.length);
Arrays.sort(sorted);
String result = null;
for (String string : strings) {
if (containsAll(sorted, string)
&& (result == null || string.length() >
result.length())) {
result = string;
}
}
return result;
}
public boolean containsAll(char[] sorted, String string) {
int length = string.length();
for (int i = 0; i < length; ++i) {
if (Arrays.binarySearch(sorted, string.charAt(i)) < 0) {
return false;
}
}
return true;
}
shareimprove this answer answered Jul 16 '14 at 21:12

nosid
22.2k22870
This definitely looks more like what I think we are looking for. –
user447607 Jul 16 '14 at 21:18
There's an optimization to be had here to in that if char [] is longer than the
String, skip it. – user447607 Jul 16 '14 at 21:28
@user447607: That doesn't work if the char[] contains duplicates. – nosid
1
Jul 16 '14 at 21:40
True. Unfortunately I didn't think to ask so I don't know if it does or not. –
user447607 Jul 16 '14 at 21:58
On second thought I think it actually does work, you are just not guaranteed
which of the duplicates is selected... but this is irrelevant. If it's in there, it's
in there. – user447607 Feb 24 at 22:29
add a comment

up vote One idea would be to convert the char[] to a Set<Character> for O(1) containment
3 down tests, then simply loop over the list of strings and check if each particular string has only
vote characters contained in the aforementioned set, keeping track of the longest string you
find with this property.

If you have more information, you could make more optimizations. For example, if the
strings themselves are very long but the list isn't, it might be beneficial to sort the list by
length first, then start processing the strings longest first.

Is there a tricky way of doing this using bitwise operators or something?

If you have some sort of (small-ish) limit on the range of character that can be included
in the char[], then you could potentially encode the whole thing in a single int/long,
which would be a substitute for the Set<Character> I mentioned above. For example,
let's say that only the characters from 'a' to 'z' will be included, then we can perform
the encoding as follows:

long charset = 0;

for (char c : chars) {


charset |= (1 << (c - 'a'));
}

Now, to check if some character c was contained in the original char[], we can simply
use:
if ((charset & (1 << (c - 'a'))) != 0) {
// c was in the original char[]
}
answered Jul 16 '14 at 21:02

edited Jul 16 '14 at 21:11


shareimprove this answer

arshajii
69.1k1195155
Well this means copying at least N char's where N = the length of the char array. It
also means instantiating N Char object wrappers so that they can be placed in a
Collection. ...and that is before you consider the copying around during sorting. As
for the bitwise operation, that seems a little TO tricky by comparison to the other
solution. It's a neat idea though considering some other problems I've come across
recently. – user447607 Jul 16 '14 at 21:45
@user447607 Well your questions puts no limits on what N could be, so how can I
factor that into my answer? Presumably N is not very large, in which case the pre-
processing stage I describe should be very cheap and beneficial in terms of the time
it saves you down the road. Regarding the second part of your comment, I think the
long encoding is simpler than the Set solution in many ways (assuming your
situation allows for it). I'm not sure how I could possibly tell if a solution is "tricky"
(as you ask for) but not "too tricky". – arshajii Jul 16 '14 at 22:29
Agree that the point is actually moot, since I didn't ask the question, "How large is
'N'?". However with the Seattle area Ivy League dot coms, one usually expects very
large N's or perhaps many repetitious instances of the premise, i.e. small N's but
millions of instances thereof. For example a million users, with 2-3 occurrences
each. Either way, smaller memory footprint with fewer objects. Agree that finding a
way to eliminate duplicates is wise in production but I don't think this was the main
focus of the problem. – user447607 Jul 17 '14 at 15:15
add a comment
up vote arshajii's first solution implementation:
0 down
/**
vote * @param list List of Strings.
* @param array Array of characters.
* @return The longest String from list that contains only characters
in the array.
* If there is no such String, "" will be returned.
*/
private static String getLongest(List<String> list, Character[] array)
{
String longest = "";
if (list == null || list.isEmpty() || array == null
|| array.length == 0) {
return longest;
}
Set<Character> set = new HashSet<Character>(Arrays.asList(array));
for (String word : list) {
boolean valid = true;
for (Character c : word.toCharArray()) {
if (!set.contains(c)) {
valid = false;
break;
}
}
if (valid && longest.length() < word.length()) {
longest = word;
}
}
return longest;
}
answered Jul 16 '14 at 21:45

shareimprove this answer

Adam Stelmaszczyk
9,06812253
add a comment
In case you are allowed to use Java 8:
public static Optional<String> longestValidWord(List<String> words,
char[] validCharacters){

String allValidCharacters = new String(validCharacters);

return words.stream()
.filter(word -> word.chars().allMatch(c ->
up vote 0 allValidCharacters.indexOf(c) > -1))
.max((s1, s2) -> Integer.compare(s1.length(), s2.length()));
down vote
}
answered Jul 16 '14 at 21:12

edited Jul 17 '14 at 1:48


shareimprove this answer

Marlon Bernardes
3,39321128
I've not had an opportunity to use Java 8 yet, so there's no way I could have
come up with this. – user447607 Jul 16 '14 at 21:22
add a comment

Your Answer


Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Stack Exchange

Post as a guest
Name
Email

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions


tagged java string algorithm list char or ask your own
question.
asked 8 months ago
viewed 309 times
active 8 months ago
Upcoming Events

2015 Community Moderator Election


ends Apr 21

Blog

Stack Overflow Developer Survey 2015: The Results

Related

561
Finding the index of an item given a list containing it in Python

49
In Java how does one turn a String into a char or a char into a String?

14
Given two strings, find the longest common bag of chars

113
How to convert a char array back to a string? (Java)

43
How to convert/parse from String to char in java?
261
How to convert a char to a string in Java?

0
List of Strings to char[] in Java

8
Java, return if List contains String

3
Alphabetize individual strings from list - Java

-3
Given a list of subsrings and a string, print out the item in the list if it is a substring

Hot Network Questions

 Why does Trinity's kiss revive Neo in The Matrix?


 How much work should I place inside a lock statement?
 which way should I handle a little boy who likes girls toys!
 Would 100-200 years be sufficient to "erase" past atrocities?
 Is there no crossover point where shutter speed overtakes flash duration?
 How is the number of electrons in an atom found?
 Do we already know how the Doctor gets his bodies or faces?
 Project Euler -problem 1
 How to report a "toxic" player in Heroes of the Storm?
 What are the possible downsides of answering an "anonymous" employee survey
truthfully?
 "I am looking for a job" on a student website, a good thing or a desperate sentence?
 Downloading US Census data?
 What is a clove of garlic?
 Programming Languages Through The Years
 Our babygirl doesn't say mommy
 Generate analog clock with numbered face, add seconds, Roman numerals
 Confidence intervals when the sample size is very large
 Why do showers have "hot" and "cold" knobs rather than "temperature" and "quantity"
knobs?
 Vegas Street Magician Math Trick
 Is it acceptable to include footnotes in mathematical proofs?
 vSphere Datastore for specific datatypes: NFS or iSCSI
 What is the best way of determining that two file paths are referring to the same file
object?
 How can I attach a solid table top to perpendicular cross rails?
 Is there any English word in which "ph" is not pronounced as "f"?

question feed
tour help blog chat data legal privacy policy work here advertising info mobile contact us
feedback
Culture /
Technology Life / Arts Science Other
Recreation
1. Stack 1. Progra 1. Datab 1. Photo 1. Engli 1. Mathe 1. St
Overfl mmers ase graph sh matics ac
ow Admi y Lang k
2. Unix nistrat uage 2. Cross A
2. Server & ors 2. Scienc & Validat pp
Fault Linux e Usag ed s
2. Drupa Fictio e (stats)
3. Super 3. Ask l n& 2. M
User Differ Answ Fantas 2. Skept 3. Theoret et
ent ers y ics ical a
4. Web (Apple Compu St
Appli ) 3. Share 3. Graph 3. Mi ter ac
cation Point ic Yode Science k
s 4. WordP Desig ya E
ress 4. User n (Juda 4. Physics
5. Ask xc
Devel Experi ism)
Ubunt 5. MathO ha
opmen ence 4. Seaso
u verflow ng
t ned 4. Trave
5. Mathe e
Advic l
6. Webm 5. Geogr matica 6. more
e 3. Ar
asters aphic 5. Chris (7)
(cooki ea
Inform 6. Salesf tianit
7. Game ng) 51
ation orce y
Devel
Syste 5. Home
opme 7. more 6. Arqa 4. St
ms Impro
nt (14) de ac
vemen
6. Electri (gami k
t
8. TeX - cal O
Engin 6. Perso ng)
eering nal 7. Bicyc
Finan ve
7. Andro les
ce & rfl
id Mone 8. Role- o
LaTe Enthus y playi w
X iasts ng C
7. Acade Game ar
8. Inform mia s ee
ation rs
Securi 8. more 9. more
ty (10) (21)
site design / logo © 2015 stack exchange inc; user contributions licensed under cc by-sa 3.0 with
attribution required
rev 2015.4.8.2455

 HOME
 CONTACT US

 ABOUT US

 DISCLAIMER

 PRIVACY POLICY

 Advertise Here

Javaaster

 HiberNate
 struts

 WordPress

 Interview Questions

 Tech News

 forum

Ad by SalePlus | Close
Ad by SalePlus | Close
15 String StringBuffer interview Question
and Answer
March 27, 2013 by Tarun Soni at 3:48 pm Leave a Comment

IN This Post I Show You Most Ask String and StringBuffer


interview Question and answer in Java I Shore That will
help You .
1) What is String in Java? Is String is data type?

String is a class in java.lang package but in java all classes are also considered as a data types. So
we can take String as a data type also.

2) Can we call a class as a data type?

Yes a class is a User Defined data type.

3) What is object reference?

Object reference is a unique hexadecimal number representing the memory address of the
object .It is useful to access the member of the object.

4) What is String Constant pool (String retrial pool)?

String Constant pool is separate block of memory where the string object is held by Jvm.

5) Explain the difference between following statement

String s=”World”;

String s=new String (“world”);

.In First Statement assignment operator is used to assign the string .In this case Jvm first check
the String pool whether the some vale already available in the String container or notify it
available then it create another reference to it if not available than create it.

In Second case each and every time it creates a new object of string.

6.) How to concept two different String?

That is another simple question this is ask by fresher level .we can concept two different String
with the help of “+” assignment operator or concept () method of String class.
7) What do you mean by immutability?

Immutability means when object is inline once it never be change.

8) How to make a class immutable in java?

1. Make a class final or private

2. Remove constructer

3 allow only getter method in your class

9) What is the difference between String and Strigbuffer classes?

String String Buffer

String class object are immutablehanse there String Buffer object are mutable so they can be
contain cannot be modify. modified.

Moreover the methods that direct manipulate data Such Method are are available in string class
of the object in String Class.

Append(),reverse() Method Not Available in String Append(),reverse() Method Available in String


Class buffer Class

10) There are any other classes in java that is immutable?

All the wapper classes in java are immutable like. Integer, Flot.Double, etc

11) What is StringTokenizer Class?

String Tokenizer Class is Use to Break the String in the form of Tokens.

12) There is any alternative of StringTokenizer?

This type of question ask by experienced people but you know about it

String Class is Alternative of String Tokenizer.with the help of split () Method of String.

13) What is the difference between String Buffer and String Builder?

String Buffer is synchronized and String Builder is not.


14) How to convert object to String.

With the help of two String () method of String Class.

15) How to Convert Integer to String

There is many way but I show you two way

1. String s=10+” ”;

2. String s=String.valuOf (10);

In First case Jvm consume lot of memory for Space

In Second case jvm not consume memory

16) Out put of following program

<b>public</b> <b>class</b> Test {

<b>public</b> <b>static</b> <b>void</b> main (String [] args) {

String s = “Hello”;

String s1 = <b>new</b> String (“Hello”);

System.<I>out</I>.println(“s = s1 “+(s == s1));

System.<i>out</i>.println(“s.equels(s1)”+(s.equals(s1)));

}
}

Output

False

True

17) String is Thread Safe or not?

Yes String is thread Safe because String object are immutable that’s way String is thread safe.

18) What is difference between Compare to and equals method?

ComapareTo () method is provided by java.lang.string package that check the two different
String to character by character if both the String are same than return 0 otherwise it return (-
vale) for each character.

Equals () Method is java. Object package Object Class Method that Check the two Different
object and return true or false

Ex.

<b>public</b> <b>class</b> sad {

<b>public</b> <b>static</b> <b>void</b> main(String[] args) {

String s = “Hello”;

String s1 = <b>new</b> String (“Hello1″);

System.<i>out</i>.println(s.compareTo(s1));
System.<i>out</i>.println(s.equals(s1));

OutPut

-1

False

Share this:
 Share

Join Our Newsletter

Join over 5,000 people who get free and fresh content delivered automatically each time we
publish.

- See more at: http://javaaster.com/2013/03/27/15-string-stringbuffer-interview-question-and-


answer/#sthash.QzYyFE7b.dpuf

Vous aimerez peut-être aussi