Académique Documents
Professionnel Documents
Culture Documents
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
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.
if(name.equals(name_1)){
System.out.println("name and name_1 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.
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");
}
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.
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.
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.
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.
"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.
String str1="abc"
str1="xyz";
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
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.
You force the creation of a new String object, this takes up some time and memory.
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:
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)
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.
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
database
debugging
design patterns
Eclipse
general
hibernate
interview questions
J2EE
java 5 tutorial
Java 7
Java 8
java IO tutorial
JDBC
JQuery
jsp-servlet
JSTL
JUnit
JUnit testing
linux
logging
Maven
MQ Series
mysql
oracle database
performance
programmers
programming
Scala
spring
SQL
SSL
String
thread
tibco
xml
xslt
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.
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.
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.
7. ailHow SubString method works in Java - Memory Leak Fixed in JDK 1.7
Why character array is better than String for Storing password in Java
->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?
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
}
March 8, 2014 at 2:58 AM
madnorb said...
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)
my question is
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
How substring method work in Java ? , Answer for this question need an attention. The
new JDK provided the fix for memory leak.
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.
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]);
}
}
}
Anonymous said...
@ Anonymous: Yes in Java 7 we can use String in Switch. but We can achieve it using
Enum.
switch(fruit) {
case apple:
method1;
break;
case carrot:
method2;
break;
// etc...
}
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
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 :
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
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 :)
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".
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.
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.
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.
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.
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
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/
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.
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.
@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
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 ?
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.
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:)
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.
http://javaved.blogspot.com
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.
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 ?
Java strings are immutable due to flawed design. Witness the [lethora of mutable string-
like classes since added to Java.
can you please explain more about how string is useful for security reasons and how can
we modify the string if it is mutable.
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..
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).
@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.
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[].
not to worry Andrew, I understand :) By the way glad to welcome here and hope to see
some interesting comments :)
Javin
package com.verhas.elrettentopelda;
import java.lang.reflect.Field;
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'
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.
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
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.
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.
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.
@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 ?
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 ...
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;
}
}
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.
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
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).
@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.
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.
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.
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
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.
@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.
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
Post a Comment
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 )
References
Struts
JDK 7 API
MySQL
Linux
Eclipse
jQuery
AddThis Sharing
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
database
debugging
design patterns
Eclipse
general
hibernate
interview questions
J2EE
java 5 tutorial
Java 7
Java 8
java IO tutorial
JDBC
JQuery
jsp-servlet
JSTL
JUnit
JUnit testing
linux
logging
Maven
MQ Series
mysql
oracle database
performance
programmers
programming
Scala
spring
SQL
SSL
String
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 .
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.
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.
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.
In Windows:
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.
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
19 comments :
Anonymous said...
hemant said...
this is a gud explanation and we also had this error driving us mad recently...
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.
Anonymous said...
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.
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.
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
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.
Anonymous said...
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
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.
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 :)
Anonymous said...
The -Xmx10246m variable should be -Xmx1024m. There is a '6' that should not be there.
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.
Many thanks
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.
Anonymous said...
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
Any idea how to resolve these error and prevent them from coming again? I am using
Tomcat 6 installations.
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
Post a Comment
Best of Javarevisited
10 Examples of Lambda Expressions in Java 8
9 Difference between TCP and UDP Protocol
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 )
► 2011 ( 145 )
► 2010 ( 33 )
References
Struts
JDK 7 API
MySQL
Linux
Eclipse
jQuery
About Me
Privacy Policy
AddThis Sharing
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
"==" 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.
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
// "==" 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.
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
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;
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.
@sagar if you dont override equals method in your class it behaves as == operator which
returns true if objects point same memory address.
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 )
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
Struts
JDK 7 API
MySQL
Linux
Eclipse
jQuery
AddThis Sharing
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
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.
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.
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.
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.
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
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.
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.
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".
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".
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.
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.
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?
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".
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.
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.
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
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...
Post a Comment
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 )
► 2014 ( 106 )
► 2013 ( 136 )
► 2012 ( 217 )
► 2011 ( 145 )
► 2010 ( 33 )
Ad by SalePlus | Close
Ad by SalePlus | Close
References
Struts
JDK 7 API
MySQL
Linux
Eclipse
jQuery
AddThis Sharing
Ad by SalePlus | Close
Ad by SalePlus | Close
How To Do In Java
Search
Skip to content
Interview
o Java Interview Questions
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 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
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 Optimization
o Apache commons
o XML
o Linux
o SQL
o Random Exceptions
o Regular Expressions
o Resource Loading
o Security
o Free Resources
You are here: Home > Core Java > Interview > Java interview question: Why Strings are
immutable?
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.
4. Return deep cloned objects with copied content for all mutable fields in class
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
If string is immutable then how can we create its object using new ,i.e, String a= new
String (“Test”);
Reply
1. Lokesh
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
Reply
1. Lokesh
Reply
2. shekhar
Reply
3. sagar
can u post something on class loading architecture and the diff types of loaders.
Reply
4. ankit sharma
hey i’m freeshar i want know about java and future in java
Reply
1. Lokesh Gupta
You will be secured for your lifetime if you managed to be a good programmer.
Reply
5. Anant
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
OK. So i got two things to explain. Lets make it clear one by one.
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
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.
Reply
1. H Singh
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
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>
Connect With Me
Recommended Reading
10 Life Lessions
How Web Servers Work?
References
Oracle Java Docs
Spring 3 Reference
Spring 4 References
Junit Wiki
Maven FAQs
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
Stack Exchange
sign up log in tour help stack overflow careers
Stack Overflow
Questions
Tags
Users
Badges
Unanswered
Ask Question
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
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.
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;
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
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
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){
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
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
Post as a guest
Name
Email
By posting your answer, you agree to the privacy policy and terms of service.
Blog
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
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
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.
Object reference is a unique hexadecimal number representing the memory address of the
object .It is useful to access the member of the object.
String Constant pool is separate block of memory where the string object is held by Jvm.
String s=”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.
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?
2. Remove constructer
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.
All the wapper classes in java are immutable like. Integer, Flot.Double, etc
String Tokenizer Class is Use to Break the String in the form of Tokens.
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?
1. String s=10+” ”;
String s = “Hello”;
System.<i>out</i>.println(“s.equels(s1)”+(s.equals(s1)));
}
}
Output
False
True
Yes String is thread Safe because String object are immutable that’s way String is thread safe.
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.
String s = “Hello”;
System.<i>out</i>.println(s.compareTo(s1));
System.<i>out</i>.println(s.equals(s1));
OutPut
-1
False
Share this:
Share
Join over 5,000 people who get free and fresh content delivered automatically each time we
publish.