Thursday, November 22, 2018
Home > java > string handling in java

string handling in java

String handling in java

String handling in Java is one of the import topics to study which will help us to manage String data and their manipulation related to this.

1)  A character is an identifier enclosed within a single quote(‘ ‘). Example: ‘A’, ‘$’, ‘9’ etc.
2) To store character data we have a data type called char.
3) the sequence or collection of character enclosed within the double quote(” “)  is called string. Example: “John”, “jazz”, “A”, “123”

Did you know

In order to Store or deal with string data, we have three predefined classes.

a) java.lang.String
b) java.lang.StringBuffer
c) java.lang.StringBuilder

Difference String and StringBuffer


StringStringBuffer
1) The data which is enclosed within the double quote is by default treated as an object of String class. 1) The data which is enclosed within the double quote is not by default treated as an object of StringBuffer.
2) When we created an object of string class then there is no additional character memory space is created.2) if we creating an object of a StringBuffer then we get 16 additional characters memory space along with the regular data.
3) On String class object in the same memory space, we cannot perform any modification. if we do any modification on the String class object then their existing memory space is destroyed and new memory space is created and placing the modified value.3) one StringBuffer class object we can perform modification in the same memory space (memory space will not be recreated).
4) history class subject is also known as an immutable object. Immutable means change the value memory(reference).4) StringBuffer class is also known as a mutable object. (mutable means not change the value of memory/reference).

The similarity of all the three classes is that they belong to the public final. Hence these three classes never participate in inheritance and indirectly not participate in “is a relationship” and they always a participant in “has a” and “uses a” relationship.

Profile of Java.lang.String


Constructors of String

 

String(): This constructor is used for creating empty in String class object.

Example:

String s=new String(); 
System.out.println(s);

It will print empty space but not null it means it really twisted the value.

String(String): This is one of the object parameterized constructor this constructor is used for creating an object of String class with some string data.

Example:

String s="String handling in Java" 
String s1=new String(s); 
System.out.println(s2); //String handling in Java

or,

String s2=new String("String handling in Java"); 
System.out.println(s2); //String handling in Java

String(char[]): This constructor is used for converting an array of character into String type data.

Example:

Char ch[]={'j','a','v','a'}; 
String s=new String(ch); 
System.out.println(s); //java

String(StringBuffer): This constructor is used for converting StringBuffer class object into String class object. In other words, this constructor also used for converting a mutable object into an immutable object.

Example:

StringBuffer sb=new StringBuffer("Java"); 
//Object of StringBuffer (sb) contain java+16 additional characters

String s=new String(sb); 
// object of Stringbuffer class which is convert into object of String class.

System.out.println(sb); //java+16 additional characters memory 
System.out.println(s); //java

String(StringBuilder): It is used for converting StringBuilder class into String class object.

Example:

StringBuilder sb=new StringBuilder("java"); 
String s=new String(sb);

System.out.println(sb); //java+16 additional characters memory 
System.out.println(s); //java

Instance method of String

 

Public int length(): This method is used for finding the number of character present in a string object or it determines the number of character in the String.

Example:

String s="java"; 
System.out.println(s); //java

int noc1=s.length(); 
System.out.println(noc1); //4

int noc2="T4Tution".length(); 
System.out.println(noc2); //8

String books[]={"java","oracle","cpp"};
System.out.println("Number of books:"+books.length()); //3 
int noc=books[0].length(); 
System.out.println(noc);//4

public char charAt(int): This method is used for finding the character by passing a specific value exist in position otherwise we get a predefined exception called a stringIndexOutOfBoundException.

Exapmle:

Strig s="java";//{j-0,a-1,v-2,a-3}
char ch=s.charAt(2); 
System.out.println(ch);//v

char ch=s.charAt(10); //invaid position
System.out.println(ch);// throws stringIndexOutOfBoundException

public String trim(): This method is used for eliminating leading and trailing spaces but not the spaces between the words.

Exapmle:

String s=" String handling in Java "; 
String ts=s.trim();
System.out.println(s.length()); //30
System.out.println(ts.length()); //23

public boolean equals(String): This method is used for comparing the content of source and destination string. This method returns true if the content of source and destination string must be the same in case-sensitive and meaning otherwise it will return false.

In Real world application, we use always this method for evaluating password.

public boolean equalsIgnoreCase(String): This method is used for comparing the content of source and destination string by ignoring their case. This method returns true if a content of source and destination string must be same in meaning(case is ignored) otherwise it returns false.

In the Real world, this method is used for username evaluation.

Example:

String s1="java";
String s2="JAVA";
boolean b=s1.equals(s2);
System.out.println(b);  //False
b=s1.equals("java");
System.out.println(b); //True
b=s1.s1.equalsIgnaoreCase(s2);
System.out.println(b); //True
b=s1.s1.equalsIgnaoreCase("java1");
System.out.println(b); //False

Definition of String Constant Pool


The number of string class object created without any operator and contain Same data with the same case and same meaning then those number of the string class object are called string constant pool.

Example:

String s1="JAVA";

String s2="JAVA";

String s3="java";

String s4="java";

String s5=new String("JAVA");

String s6=new String("JAVA");
String Constant pool

What are the difference between “==” operator and “.equals()” method.


“==” operator is used for comparing the reference of two objects but it cannot be used for comparing the content of two objects.

.equals() method is used for comparing the content of source and destination strings.

String s1="JAVA";
String s2="JAVA"; 
String s5=new String("JAVA"); 
String s6=new String("JAVA");
if(s1==s2)
  System.out.println("Both object contain same reference and same data");
else
  System.out.println("Different reference");
if(s5==s6)
System.out.println("same reference");
else
System.out.println("Different reference");

public String concat(String): This method is used for concating the content of source string with the day special string and place the resultant String.

Example:

String s1="JAVA"; 
String s2="program";
String cs1=s1.concat(s2);
System.out.println("s1"); //JAVA
System.out.println("s2"); //Program
System.out.println("cs2"); //JAVAProgram

String cs2=s1+s2+"Language";
System.out.println("cs2"); //JAVAProgramLanguage

Note: The operator ‘+’ can be used for concating any number of string object contains whereas concat() method will concatenate only two string object content at a time.

public String subString(int)This method is used for obtaining the part of the string from an original string from the position what we specify and it takes up to last.

public String subString(int start, int end)This method is also used for obtaining the range of character faces find the position where to start and where to end(end-1).

Example:

String s="JAVA PROGRAM";
String ss1=s.subString(5);
System.out.println("ss1"); //PROG
String ss2=s.subString(2,7); 
System.out.println("ss2");//VA PR
String ss3=s.subString(5,s.length()); 
System.out.println("ss3"); //PROGRAM

Static method of String

 

public static string valueOf(*******): here “*******” represent any datatype and it is one of the static overloaded factory methods and it is used for converting fundamental datatype to string type data.

Example:

int a=10;
String s1=String.valueOf(a); // "10"
System.out.println(a);
char ch='A';
String s2=String.valueOf(ch); //"A"
System.out.println(s2);

java.lang.StringBuffer


StringBuffer is one of the predefined class present in java.lang.* package. When we create an object of StringBuffer by default 16 additional character memory space is created and whose object is known as a mutable object.

By default StringBuffer class is one of the public final class and it never participates in inheritance by default the string data cannot be created as an object of StringBuffer.

profile of java.lang.StringBuffer


Constructors of StringBuffer

 

StringBuffer() // default constructor
StringBuffer(StringBuffer) // object parameterized constructor
StringBuffer(char[])
StringBuffer(String)
StringBuffer(StringBuilder)

Instance method of StringBuffer

 

public int length(): Find no. of character in StringBuffer object
public int capacity(): Find the capacity in StringBuffer object

Example:

StringBuffer sb="java"; //Invalid
StringBuffer sb=new StringBuffer("java"); //java+16 additional characters
int noc=sb.length();
System.out.println(noc); //4
int cap=sb.capacity();
System.out.println(cap); //20(4+16)

public StringBuffer reverse(): This method is used for obtaining a sentence of StringBuffer object in reverse order.

Example:

StringBuffer sb1=new StringBuffer("java");
System.out.println(sb1); //java
StringBuffer sb2=sb1.reverse();
System.out.println(sb2); //avaj

public StringBuffer append(****): Here **** represent in fundamental data type and String value. This method is used for adding the new data at the end of existing data StringBuffer object.

Example:

StringBuffer sb1=new StringBuffer("String handling in Java");
System.out.println(sb1); //String handling in Java
StringBuffer sb2=sb1.append("by T4Tution.com");
System.out.println(sb2); //String handling in Java by T4Tution.com

Note: If you want to perform any operation on StringBuffer object data and if the methods are not found in StringBuffer class but it is found in a String class then we can convert is StringBuffer object data into String object and apply the method and vice versa.

StringBuffer class is not containing in a static method.

java.lang.StringBuilder


StringBuilder is one of the predefined class present in java.lang.* package and it is available from JDK 1.5 onwards.
The concept of StringBuilder is exactly similar to StringBuffer but StringBuffer methods are belongs to synchronized and StringBuilder methods belong to non-synchronized.

In other word StringBuilder is containing mixing characteristics of non-synchronized and StringBuffer 16 additional character memory space.

synchronization provides thread safety and non-synchronization provide non-thread safety.

In the Real world, we use String and StringBuilder in J2EE server-side application(Web application, distributed application, enterprise application) because thread safety will be provided by server software and they are not recommended to use in JSE application(standalone GUI and 2 tier application).

StringBuffer class object is recommended to use in JSE application and not recommended to use in JEE application.

All the methods of StringBuffer as available as it is available in StringBuilder including the constructor.

String Handling Interview Question


Q. What is String in Java? String is a data type ?

1)  A character is an identifier enclosed within a single quote(‘ ‘). Example: ‘A’, ‘$’, ‘9’ etc.
2) To store character data we have a data type called char.
3) the sequence or collection of character enclosed within the double quote(” “)  is called string. Example: “John”, “jazz”, “A”, “123″.

Q. How can we make String upper case or lower case?

By using toUpperCase() and toLowerCase() method

Q. How to compare two Strings in java program?

Java String implements Comparable interface and it has two variants of compareTo() methods.

compareTo(String anotherString) equals(String str) method will also return true.

compareToIgnoreCase(String str):It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero then equalsIgnoreCase(String str) will also return true.

Q. How to convert String to char and vice versa?

This is a tricky question because String is a sequence of characters, so we can’t convert it to a single character. We can use use charAt method to get the character at given index or we can use toCharArray()method to convert String to character array.
Check this post for sample program on converting String to character array to String.

How to convert String to byte array and vice versa?

We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.
Check this post for String to byte array example.

Can we use String in switch case?

This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn’t support this.
If you are implementing conditional flow for Strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions.

Check this post for Java Switch Case String example.

Write a program to print all permutations of String?

This is a tricky question and we need to use recursion to find all the permutations of a String, for example “AAB” permutations will be “AAB”, “ABA” and “BAA”.
We also need to use Set to make sure there are no duplicate values.
Check this post for complete program to find all permutations of String.

Write a function to find out longest palindrome in a given string?

A String can contain palindrome strings in it and to find longest palindrome in given String is a programming question.
Check this post for complete program to find longest palindrome in a String.

Difference between String, StringBuffer and StringBuilder?

String is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations – StringBuffer and StringBuilder.
StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder.
StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.

Check this post for extensive details about String vs StringBuffer vs StringBuilder.
Read this post for benchmarking of StringBuffer vs StringBuilder.

Why String is immutable or final in Java

There are several benefits of String because it’s immutable and final.

  • String Pool is possible because String is immutable in java.
  • It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password etc.
  • Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.
  • Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

 

How to Split String in java?

We can use split(String regex) to split the String into String array based on the provided regular expression.

Why Char array is preferred over String for storing password?

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.
If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

How do you check if two Strings are equal in Java?

There are two ways to check if two Strings are equal or not – using “==” operator or using equals method. When we use “==” operator, it checks for value of String as well as reference but in our programming, most of the time we are checking equality of String for value only. So we should use equals method to check if two Strings are equal or not.
There is another function equalsIgnoreCase that we can use to ignore case.


        String s1 = "abc";
        String s2 = "abc";
        String s3= new String("abc");
        System.out.println("s1 == s2 ? "+(s1==s2)); //true
        System.out.println("s1 == s3 ? "+(s1==s3)); //false
        System.out.println("s1 equals s3 ? "+(s1.equals(s3))); //true

What is String Pool?

As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String is special class in java and we can create String object using new operator as well as providing values in double quotes.
Check this post for more details about

What does String intern() method do?

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.
This method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Does String is thread-safe in Java?

Strings are immutable, so we can’t change it’s value in program. Hence it’s thread-safe and can be safely used in multi-threaded environment.

Why String is popular HashMap key in Java?

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

String Programming Questions

  1. What is the output of below program?
    
    package com.journaldev.strings;
    
    public class StringTest {
    
    	public static void main(String[] args) {
    		String s1 = new String("pankaj");
    		String s2 = new String("PANKAJ");
    		System.out.println(s1 = s2);
    	}
    
    }
    

    It’s a simple yet tricky program, it will print “PANKAJ” because we are assigning s2 String to s1. Don’t get confused with == comparison operator.

  2. What is the output of below program?
    
    package com.journaldev.strings;
    
    public class Test {
    
    	 public void foo(String s) {
    	 System.out.println("String");
    	 }
    
    	 public void foo(StringBuffer sb){
    	 System.out.println("StringBuffer");
    	 }
    
    	 public static void main(String[] args) {
    		new Test().foo(null);
    	}
    
    }
    

    The above program will not compile with error as “The method foo(String) is ambiguous for the type Test”.

  3. What is the output of below code snippet?
    
    String s1 = new String("abc");
    String s2 = new String("abc");
    System.out.println(s1 == s2);
    

    It will print false because we are using new operator to create String, so it will be created in the heap memory and both s1, s2 will have different reference. If we create them using double quotes, then they will be part of string pool and it will print true.

  4. What will be output of below code snippet?
    
    String s1 = "abc";
    StringBuffer s2 = new StringBuffer(s1);
    System.out.println(s1.equals(s2));
    

    It will print false because s2 is not of type String. If you will look at the equals method implementation in the String class, you will find a check using instanceof operator to check if the type of passed object is String? If not, then return false.

  5. What will be output of below program?
    
    String s1 = "abc";
    String s2 = new String("abc");
    s2.intern();
    System.out.println(s1 ==s2);
    

    It’s a tricky question and output will be false. We know that intern() method will return the String object reference from the string pool, but since we didn’t assigned it back to s2, there is no change in s2 and hence both s1 and s2 are having different reference. If we change the code in line 3 to s2 = s2.intern(); then output will be true.


Q. Is String a keyword in java?

String is not a keyword in java. String is a final class present in java.lang package.Its used to create the set of characters in java.

Q. Is String a primitive type or derived type?

String is a derived type.

Q. In how many ways you can create string objects in java?

There are two ways to create string objects in java. One is using new operator and another one is using string literals. The objects created using new operator are stored in the heap memory and objects created using string literals are stored in string constant pool.

1
2
3
String s1 = new String("abc");          //Creating string object using new operator
String s2 = "abc";        //Creating string object using string literal

Q. What is string constant pool?

The number of string class object created without any operator and contain Same data with the same case and same meaning then those number of the string class object are called string constant pool.

Q. What is special about string objects as compared to objects of other derived types?

One special thing about string objects is that you can create string objects without using new operator i.e using string literals. This is not possible with other derived types (except wrapper classes). One more special thing about strings is that you can concatenate two string objects using ‘+’. This is the relaxation java gives to string objects as they will be used most of the time while coding. And also java provides string constant pool to store the string objects.

Q. What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can’t modify them once they are created. They are final in nature. Where as mutable objects are concerned, you can perform modifications to them.

Q. Which is the final class in these three classes – String, StringBuffer and StringBuilder?

All three are final. (Interviewer will ask this type of questions to confuse you)

Q. Why StringBuffer and StringBuilder classes are introduced in java when there already exist String class to represent the set of characters?

The objects of String class are immutable in nature. i.e you can’t modify them once they are created. If you try to modify them, a new object will be created with modified content. This may cause memory and performance issues if you are performing lots of string modifications in your code. To overcome these issues, StingBuffer and StringBuilder classes are introduced in java.

Q. How many objects will be created in the following code and where they will be stored in the memory?

1
2
3
String s1 = "abc";
String s2 = "abc";

Only one object will be created and this object will be stored in the string constant pool.

Q. How do you create mutable string objects?

By Using StringBuffer and StringBuilder classes. These classes gives us mutable string objects.

Q. Which one will you prefer among “==” and equals() method to compare two string objects?

I prefer equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations. So, rather stick to equals() method to compare two string objects. [more]

Q. Which class will you recommend among String, StringBuffer and StringBuilder classes if I want mutable and thread safe objects?

StringBuffer 

Q. How do you convert given string to char array?

by using  toCharArray() method.

Q. How many objects will be created in the following code and where they will be stored?

1
2
3
String s1 = new String("abc");
String s2 = "abc";

Here, two string objects will be created. Object created using new operator(s1) will be stored in the heap memory. The object created using string literal(s2) is stored in the string constant pool.

Q. Where exactly string constant pool is located in the memory?

In heap memory.

Q. What is string intern?

String object in the string constant pool is called as String Intern. You can create an exact copy of heap memory string object in string constant pool. This process of creating an exact copy of heap memory string object in the string constant pool is called interning. intern() method is used for interning.

Q. What is the main difference between Java strings and C, C++ strings?

In C and C++, String is terminated with null value. But in java, string is not terminated with null value. In java String is treated as object.

Q. Can we call String class methods using string literals?

Q. do you have any idea why strings have been made immutable in java?

 

Q. What is string constant pool? Why they have provided this pool as we can store string objects in the heap memory itself?

 

Q. What is the similarity and difference between String and StringBuffer class?

 

Q. What is the similarity and difference between StringBuffer and StringBuilder class?

.

I hope that the questions listed here will help you in java interviews, please let me know if I have missed anything.

Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

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