We are hosting this site in another domain. Checkout
http://www.techpitcher.com/java/string.html
1. Describe String in Java.
String can be created by assigning string literals:
String stringLiteral = "Java";
String secondString = "I am a String Literal"; // Points to the same object as firstString
String thirdString = new String("I am another String Literal"); // By using constructor, will create a new Objet in JVM
-----------------------------------------------------------------------------
2. What are the differences between the == operator and the equals() method?
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
From the example, we can see that reference and value for s1 & s2 are same. At the same time s3 is a newly created instance which has same value as of s1 and s2 but reference is different.
-----------------------------------------------------------------------------
3. What is String.intern()?
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
By using intern one can get better performance as compared to equals method in String class. equals does the character by character that you probably want.
There are some disadvantages of intern. If we start using intern with every string then pool size will increase and could lead to memory problem. Secondly in case of bigger pool, finding a string could be more costly that having character by character comparison.
-----------------------------------------------------------------------------
4. Which one of the following is more efficient?
a. String str1 = "Hello " + "Guest";
b. String str2 = (new StringBuffer().append("Hello ")).append("Guest").toString();
str1 is resolved at compile time, while str2 is resolved at runtime time with an extra StringBuffer and String. The version that can be resolved at compile time is more efficient. It avoids the overhead of creating a String and an extra StringBuffer, as well as avoiding the runtime cost of several method calls.
-----------------------------------------------------------------------------
You can also find links related to these topics on ads section provided by Google.
Please provide your comment to make this forum better.
No comments:
Post a Comment