hereral/Clara-Training-Data huggingface dataset:
Question: Can you provide Java Method Overloading example?
Answer: class OverloadingExample{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}  
}
Question: Can you provide Java Method Overriding example?
Answer: class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void eat(){System.out.println("eating bread...");}  
}
Question: What is Java String?
Answer: n Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
String s=new String(ch);  
is same as:

String s="javatpoint";  
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
Question: CharSequence Interface
Answer: The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let's first understand what String in Java is and how to create the String object.
Question: What is String in Java?
Answer: Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
Question: How to create a string object?
Answer: There are two ways to create String object:

1.By string literal
2.By new keyword
Question: What is String Literal?
Answer: Java String literal is created by using double quotes. For Example:

String s="welcome";  
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";  
String s2="Welcome";//It doesn't create a new instance  

In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in string constant pool that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.
Question: By new keyword
Answer: String s=new String("Welcome");//creates two objects and one reference variable  
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
Question: Can you provide Java String Example?
Answer: public class StringExample{    
public static void main(String args[]){    
String s1="java";//creating string by Java string literal    
char ch[]={'s','t','r','i','n','g','s'};    
String s2=new String(ch);//converting char array to string    
String s3=new String("example");//creating Java string by new keyword    
System.out.println(s1);    
System.out.println(s2);    
System.out.println(s3);    
}}    
Output:

java
strings
example
Question: Java String class methods
Answer: The java.lang.String class provides many useful methods to perform operations on sequence of char values.


char charAt(int index) - It returns char value for the particular index
int length() - It returns string length
static String format(String format, Object... args) - It returns a formatted string.
static String format(Locale l, String format, Object... args)  - It returns formatted string with given locale
String substring(int beginIndex) - It returns substring for given begin index.
String substring(int beginIndex, int endIndex) - It returns substring for given begin index and end index.
boolean contains(CharSequence s) - It returns true or false after matching the sequence of char value.
static String join(CharSequence delimiter, CharSequence... elements) - It returns a joined string.
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) - It returns a joined string.
boolean equals(Object another) - It checks the equality of string with the given object.
boolean isEmpty() - It checks if string is empty
String concat(String str) - It concatenates the specified string.
String replace(char old, char new) - It replaces all occurrences of the specified char value.
String replace(CharSequence old, CharSequence new) - It replaces all occurrences of the specified CharSequence.
static String equalsIgnoreCase(String another) - It compares another string. It doesn't check case.
String[] split(String regex) - It returns a split string matching regex.
String[] split(String regex, int limit) - It returns a split string matching regex and limit
String intern() - It returns an interned string. 
int indexOf(int ch) -  It returns the specified char value index.
int indexOf(int ch, int fromIndex) - It returns the specified char value index starting with given index
int indexOf(String substring) - It returns the specified substring index.
int indexOf(String substring, int fromIndex) - It returns the specified substring index starting with given index
String toLowerCase() - It returns a string in lowercase.
String toLowerCase(Locale l) - It returns a string in lowercase using specified locale.
String toUpperCase() - It returns a string in uppercase.
String toUpperCase(Locale l) - It returns a string in uppercase using specified locale. 
String trim() - It removes beginning and ending spaces of this string.
static String valueOf(int value) - It converts given type into string. It is an overloaded method
Question: What is Immutable String in Java?
Answer: A String is an unavoidable type of variable while writing any application program. String references are used to store various attributes like username, password, etc. In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once String object is created its data or state can't be changed but a new String object is created.
Question: Testimmutablestring.java
Answer: class Testimmutablestring{  
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
}  
Output:

Sachin
Question: Why String objects are immutable in Java?
Answer: As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one object "Sachin". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why String objects are immutable in Java.

Following are some features of String which makes String objects immutable.

1. ClassLoader:

A ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different.

To avoid this kind of misinterpretation, String is immutable.

2. Thread Safe:

As the String object is immutable we don't have to take care of the synchronization that is required while sharing an object across multiple threads.

3. Security:

As we have seen in class loading, immutable String objects avoid further errors by loading the correct class. This leads to making the application program more secure. Consider an example of banking software. The username and password cannot be modified by any intruder because String objects are immutable. This can make the application program more secure.

4. Heap Space:

The immutability of String helps to minimize the usage in the heap memory. When we try to declare a new String object, the JVM checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows Java to use the heap space efficiently.
Question: Why String class is Final in Java?
Answer: The reason behind the String class being final is because no one can override the methods of the String class. So that it can provide the same features to the new String objects as well as to the old ones.
Question: What is Java String compare?
Answer: We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare String in Java:

1.By Using equals() Method
2.By Using == Operator
3.By compareTo() Method
Question: How to use Java string compares By Using equals() Method?
Answer: The String class equals() method compares the original content of the string. It compares values of string for equality. String class provides the following two methods:

-public boolean equals(Object another) compares this string to the specified object.
-public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring case.
Question: How to use By Using compareTo() method?
Answer: The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

-s1 == s2 : The method returns 0.
-s1 > s2 : The method returns a positive value.
-s1 < s2 : The method returns a negative value.
Question: What is String Concatenation in Java?
Answer: In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java:

1.By + (String concatenation) operator
2.By concat() method
Question: Can you provide String Concatenation by + (String concatenation) operator?
Answer: Java String concatenation operator (+) is used to add strings. For Example:

TestStringConcatenation1.java

class TestStringConcatenation1{  
 public static void main(String args[]){  
   String s="Sachin"+" Tendulkar";  
   System.out.println(s);//Sachin Tendulkar  
 }  
}  
Output:
Sachin Tendulkar
Question: How to concatenate string by concat() method?
Answer: The String concat() method concatenates the specified string to the end of current string. Syntax:

public String concat(String another)  
Let's see the example of String concat() method.

TestStringConcatenation3.java

class TestStringConcatenation3{  
 public static void main(String args[]){  
   String s1="Sachin ";  
   String s2="Tendulkar";  
   String s3=s1.concat(s2);  
   System.out.println(s3);//Sachin Tendulkar  
  }  
}  The String concat() method concatenates the specified string to the end of current string. Syntax:

public String concat(String another)  
Let's see the example of String concat() method.

TestStringConcatenation3.java

class TestStringConcatenation3{  
 public static void main(String args[]){  
   String s1="Sachin ";  
   String s2="Tendulkar";  
   String s3=s1.concat(s2);  
   System.out.println(s3);//Sachin Tendulkar  
  }  
}  
Output:

Sachin Tendulkar
Question: Can you provide String concatenation example using StringBuilder class?
Answer: StringBuilder is class provides append() method to perform concatenation operation. The append() method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double. StringBuilder is the most popular and fastet way to concatenate strings in Java. It is mutable class which means values stored in StringBuilder objects can be updated or changed.

StrBuilder.java
public class StrBuilder  
{  
    /* Driver Code */  
    public static void main(String args[])  
    {  
        StringBuilder s1 = new StringBuilder("Hello");    //String 1  
        StringBuilder s2 = new StringBuilder(" World");    //String 2  
        StringBuilder s = s1.append(s2);   //String 3 to store the result  
            System.out.println(s.toString());  //Displays result  
    }  
}  

Output:
Hello World

In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the result of concatenation of s1 and s2 using append() method.
Question: Can you provide String concatenation using format() method?
Answer: String.format() method allows to concatenate multiple strings using format specifier like %s followed by the string values or objects.


StrFormat.java
public class StrFormat  
{  
    /* Driver Code */  
    public static void main(String args[])  
    {  
        String s1 = new String("Hello");    //String 1  
        String s2 = new String(" World");    //String 2  
        String s = String.format("%s%s",s1,s2);   //String 3 to store the result  
            System.out.println(s.toString());  //Displays result  
    }  
}  

Output:
Hello World

Here, the String objects s is assigned the concatenated result of Strings s1 and s2 using String.format() method. format() accepts parameters as format specifier followed by String objects or values.
Question: Can you provide an example of String concatenation using String.join() method (Java Version 8+)?
Answer: The String.join() method is available in Java version 8 and all the above versions. String.join() method accepts arguments first a separator and an array of String objects.

StrJoin.java:
public class StrJoin  
{  
    /* Driver Code */  
    public static void main(String args[])  
    {  
        String s1 = new String("Hello");    //String 1  
        String s2 = new String(" World");    //String 2  
        String s = String.join("",s1,s2);   //String 3 to store the result  
            System.out.println(s.toString());  //Displays result  
    }  
}  

Output:
Hello World

In the above code snippet, the String object s stores the result of String.join("",s1,s2) method. A separator is specified inside quotation marks followed by the String objects or array of String objects.
Question: Can you provide an example of String concatenation using StringJoiner class (Java Version 8+)?
Answer: StringJoiner class has all the functionalities of String.join() method. In advance its constructor can also accept optional arguments, prefix and suffix.

StrJoiner.java
public class StrJoiner  
{  
    /* Driver Code */  
    public static void main(String args[])  
    {  
        StringJoiner s = new StringJoiner(", ");   //StringeJoiner object  
        s.add("Hello");    //String 1   
        s.add("World");    //String 2  
        System.out.println(s.toString());  //Displays result  
    }  
}  

Output:
Hello, World

In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner() accepts a separator value. A separator is specified inside quotation marks. The add() method appends Strings passed as arguments.
Question: Can you provide an example of String concatenation using Collectors.joining() method (Java (Java Version 8+)?
Answer: The Collectors class in Java 8 offers joining() method that concatenates the input elements in a similar order as they occur.

ColJoining.java

import java.util.*;  
import java.util.stream.Collectors;  
public class ColJoining  
{  
    /* Driver Code */  
    public static void main(String args[])  
    {  
        List<String> liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array  
    String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operation  
        System.out.println(str.toString());  //Displays result  
    }  
}  

Output:
abc, pqr, xyz

Here, a list of String array is declared. And a String object str stores the result of Collectors.joining() method.
Question: What is Substring in Java?
Answer: A part of String is called substring. In other words, substring is a subset of another String. Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive.

Suppose the string is "computer", then the substring will be com, compu, ter, etc.

You can get substring from the given String object by one of the two methods:

public String substring(int startIndex):
This method returns new String object containing the substring of the given string from specified startIndex (inclusive). The method throws an IndexOutOfBoundException when the startIndex is larger than the length of String or less than zero.

public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from specified startIndex to endIndex. The method throws an IndexOutOfBoundException when the startIndex is less than zero or startIndex is greater than endIndex or endIndex is greater than length of String.

In case of String:
-startIndex: inclusive
-endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

String s="hello";    
System.out.println(s.substring(0,2)); //returns he  as a substring 
 
In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end index is exclusive).
Question: Can you provide Example of Java substring() method?
Answer: TestSubstring.java
public class TestSubstring{    
 public static void main(String args[]){    
 String s="SachinTendulkar";    
 System.out.println("Original String: " + s);  
 System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar    
 System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin  
 }  
}    

Output:
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin

The above Java programs, demonstrates variants of the substring() method of String class. The startindex is inclusive and endindex is exclusive.
Question: Can you provide an example of using String.split() method?
Answer: The split() method of String class can be used to extract a substring from a sentence. It accepts arguments in the form of a regular expression.

TestSubstring2.java
import java.util.*;  
  
public class TestSubstring2  
{    
    /* Driver Code */  
    public static void main(String args[])  
    {    
        String text= new String("Hello, My name is Sachin");  
        /* Splits the sentence by the delimeter passed as an argument */  
        String[] sentences = text.split("\\.");  
        System.out.println(Arrays.toString(sentences));  
    }  
}    

Output:
[Hello,  My name is Sachin]

In the above program, we have used the split() method. It accepts an argument \\. that checks a in the sentence and splits the string into another string. It is stored in an array of String objects sentences.
Question: What are Java String Class Methods?
Answer: The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java. By the help of these methods, we can perform operations on String objects such as trimming, concatenating, converting, comparing, replacing strings etc.


Java String is a powerful concept because everything is treated as a String if you submit any form in window based, web based or mobile application.
Question: Can you provide example of Java String toUpperCase() and toLowerCase() method?
Answer: The Java String toUpperCase() method converts this String into uppercase letter and String toLowerCase() method into lowercase letter.

Stringoperation1.java

public class Stringoperation1  
{  
public static void main(String ar[])  
{  
String s="Sachin";    
System.out.println(s.toUpperCase());//SACHIN    
System.out.println(s.toLowerCase());//sachin    
System.out.println(s);//Sachin(no change in original)    
}  
}  

Output:

SACHIN
sachin
Sachin
Question: Can you provide example of Java String trim() method?
Answer: The String class trim() method eliminates white spaces before and after the String
.
Stringoperation2.java
public class Stringoperation2  
{  
public static void main(String ar[])  
{  
String s="  Sachin  ";    
System.out.println(s);//  Sachin      
System.out.println(s.trim());//Sachin    
}  
}  

Output:
Sachin  
Sachin
Question: Can you provide an example of Java String startsWith() and endsWith() method?
Answer: The method startsWith() checks whether the String starts with the letters passed as arguments and endsWith() method checks whether the String ends with the letters passed as arguments.

Stringoperation3.java
public class Stringoperation3  
{  
public static void main(String ar[])  
{  
String s="Sachin";    
 System.out.println(s.startsWith("Sa"));//true    
 System.out.println(s.endsWith("n"));//true    
}  
}  

Output:
true
true
Question: Can you provide an example of  Java String charAt() Method?
Answer: The String class charAt() method returns a character at specified index.

Stringoperation4.java
public class Stringoperation4  
{  
public static void main(String ar[])  
{  
String s="Sachin";    
System.out.println(s.charAt(0));//S    
System.out.println(s.charAt(3));//h    
}  
}  

Output:
S
h
Question: Can you provide an example of Java String length() Method?
Answer: The String class length() method returns length of the specified String.

Stringoperation5.java
public class Stringoperation5  
{  
public static void main(String ar[])  
{  
String s="Sachin";    
System.out.println(s.length());//6    
}  
}  

Output:
6
Question: Can you provide an example of Java String intern() Method?
Answer: A pool of strings, initially empty, is maintained privately by the class String.
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.

Stringoperation6.java
public class Stringoperation6  
{  
public static void main(String ar[])  
{  
String s=new String("Sachin");    
String s2=s.intern();    
System.out.println(s2);//Sachin    
}  
}  

Output:
Sachin
Question: Can you provide an example of Java String valueOf() Method?
Answer: The String class valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into String.

Stringoperation7.java
public class Stringoperation7  
{  
public static void main(String ar[])  
{  
int a=10;    
String s=String.valueOf(a);    
System.out.println(s+10);    
}  
} 
 
Output:
1010
Question: Can you provide an example of  Java String replace() Method?
Answer: The String class replace() method replaces all occurrence of first sequence of character with second sequence of character.

Stringoperation8.java
public class Stringoperation8  
{  
public static void main(String ar[])  
{  
String s1="Java is a programming language. Java is a platform. Java is an Island.";      
String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"      
System.out.println(replaceString);    
}  
}     

Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Question: What is Java StringBuffer Class?
Answer: Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.
Question: What is Important Constructors of StringBuffer Class?
Answer: Important Constructors of StringBuffer Class
Constructor: StringBuffer()
Description: It creates an empty String buffer with the initial capacity of 16.


Constructor: StringBuffer(String str)
Description: It creates a String buffer with the specified string.


Constructor: StringBuffer(int capacity)
Description: It creates an empty String buffer with the specified capacity as length.
Question: What are the Important methods of StringBuffer class?
Answer: Important methods of StringBuffer class
Modifier and Type: public synchronized StringBuffer
Method: append(String s)
Description: It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

Modifier and Type: public synchronized StringBuffer
Method: insert(int offset, String s)
Description: It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.

Modifier and Type: public synchronized StringBuffer
Method: replace(int startIndex, int endIndex, String str)
Description: It is used to replace the string from specified startIndex and endIndex.

Modifier and Type: public synchronized StringBuffer
Method: delete(int startIndex, int endIndex)
Description: It is used to delete the string from specified startIndex and endIndex.

Modifier and Type: public synchronized StringBuffer
Method: reverse()
Description: is used to reverse the string.

Modifier and Type: public int
Method: capacity()
Description: It is used to return the current capacity.

Modifier and Type: public void
Method: ensureCapacity(int minimumCapacity)
Description: It is used to ensure the capacity at least equal to the given minimum.

Modifier and Type: public char
Method: charAt(int index)
Description: It is used to return the character at the specified position.

Modifier and Type: public int
Method: length()
Description: It is used to return the length of the string i.e. total number of characters.

Modifier and Type: public String
Method: substring(int beginIndex)
Description: It is used to return the substring from the specified beginIndex.

Modifier and Type: public String
Method: substring(int beginIndex, int endIndex)
Description: It is used to return the substring from the specified beginIndex and endIndex.
Question: What is a mutable String?
Answer: A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for creating mutable strings.
Question: Can you provide an example of StringBuffer Class append() Method?
Answer: The append() method concatenates the given argument with this String.

StringBufferExample.java
class StringBufferExample{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}  

Output:
Hello Java
Question: Can you provide an example of StringBuffer insert() Method?
Answer: The insert() method inserts the given String with this string at the given position.

StringBufferExample2.java
class StringBufferExample2{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.insert(1,"Java");//now original string is changed  
System.out.println(sb);//prints HJavaello  
}  
}  


Output:
HJavaello
Question: Can you provide an example of StringBuffer replace() Method?
Answer: The replace() method replaces the given String from the specified beginIndex and endIndex.

StringBufferExample3.java
class StringBufferExample3{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.replace(1,3,"Java");  
System.out.println(sb);//prints HJavalo  
}  
}  

Output:
HJavalo
Question: Can you provide an example of StringBuffer delete() Method?
Answer: The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.

StringBufferExample4.java
class StringBufferExample4{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.delete(1,3);  
System.out.println(sb);//prints Hlo  
}  
}  

Output:
Hlo
Question: Can you provide an example of StringBuffer reverse() Method?
Answer: The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java
class StringBufferExample5{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.reverse();  
System.out.println(sb);//prints olleH  
}  
}
  
Output:
olleH
Question: Can you provide an example of StringBuffer capacity() Method?
Answer: The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

StringBufferExample6.java
class StringBufferExample6{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
}  
}  

Output:
16
16
34
Question: Can you provide an example of StringBuffer ensureCapacity() method?
Answer: The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

StringBufferExample7.java
class StringBufferExample7{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
sb.ensureCapacity(10);//now no change  
System.out.println(sb.capacity());//now 34  
sb.ensureCapacity(50);//now (34*2)+2  
System.out.println(sb.capacity());//now 70  
}  
}  

Output:
16
16
34
34
70
Question: What is Java StringBuilder Class?
Answer: Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Question: What are Important Constructors of StringBuilder class?
Answer: Constructor: 

StringBuilder()
Description: It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String str)
Description: It creates a String Builder with the specified string.

StringBuilder(int length)  
Description: It creates an empty String Builder with the specified capacity as length.
Question: What are the Important methods of StringBuilder class?
Answer: Method

public StringBuilder append(String s) 
Description: It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

public StringBuilder insert(int offset, String s)
Description: It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.

public StringBuilder replace(int startIndex, int endIndex, String str)
Description: It is used to replace the string from specified startIndex and endIndex.

public StringBuilder delete(int startIndex, int endIndex)
Description: It is used to delete the string from specified startIndex and endIndex.

public StringBuilder reverse()
Description: It is used to reverse the string.

public int capacity()
Description: It is used to return the current capacity.

public void ensureCapacity(int minimumCapacity)
Description:It is used to ensure the capacity at least equal to the given minimum.

public char charAt(int index)
Description:It is used to return the character at the specified position.

public int length()
Description:It is used to return the length of the string i.e. total number of characters.


public String substring(int beginIndex)
Description:It is used to return the substring from the specified beginIndex.

public String substring(int beginIndex, int endIndex)
Description:It is used to return the substring from the specified beginIndex and endIndex.
Question: What are the Difference of String between StringBuffer?
Answer: There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:

1) The String class is immutable while the StringBuffer class is mutable. 
2) String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance while StringBuffer is fast and consumes less memory when we concatenate t strings.
3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method while StringBuffer class doesn't override the equals() method of Object class
4) String class is slower while performing concatenation operation while StringBuffer class is faster while performing concatenation operation.
5) String class uses String constant pool while StringBuffer uses Heap memory.
Question: Can you provide an example of Performance Test of String and StringBuffer?
Answer: ConcatTest.java

public class ConcatTest{  
    public static String concatWithString()    {  
        String t = "Java";  
        for (int i=0; i<10000; i++){  
            t = t + "Tpoint";  
        }  
        return t;  
    }  
    public static String concatWithStringBuffer(){  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Tpoint");  
        }  
        return sb.toString();  
    }  
    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        concatWithString();  
        System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");  
        startTime = System.currentTimeMillis();  
        concatWithStringBuffer();  
        System.out.println("Time taken by Concating with  StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");  
    }  
}  

Output:
Time taken by Concating with String: 578ms
Time taken by Concating with  StringBuffer: 0ms
Question: Can you providean example of String and StringBuffer HashCode Test?
Answer: As we can see in the program given below, String returns new hashcode while performing concatenation but the StringBuffer class returns same hashcode.

InstanceTest.java
public class InstanceTest{  
    public static void main(String args[]){  
        System.out.println("Hashcode test of String:");  
        String str="java";  
        System.out.println(str.hashCode());  
        str=str+"tpoint";  
        System.out.println(str.hashCode());  
   
        System.out.println("Hashcode test of StringBuffer:");  
        StringBuffer sb=new StringBuffer("java");  
        System.out.println(sb.hashCode());  
        sb.append("tpoint");  
        System.out.println(sb.hashCode());  
    }  
}  

Output:
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462
Question: What are the Difference between StringBuffer and StringBuilder?
Answer: Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5.

A list of differences between StringBuffer and StringBuilder is given below:
1)  StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously while StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder while StringBuilder is more efficient than StringBuffer.
3) StringBuffer was introduced in Java 1.0 while StringBuilder was introduced in Java 1.5
Question: Can you provide StringBuffer Example?
Answer: BufferTest.java
//Java Program to demonstrate the use of StringBuffer class.  
public class BufferTest{  
    public static void main(String[] args){  
        StringBuffer buffer=new StringBuffer("hello");  
        buffer.append("java");  
        System.out.println(buffer);  
    }  
}  

Output:
hellojava
Question: Can you provide StringBuilder Example?
Answer: BuilderTest.java
//Java Program to demonstrate the use of StringBuilder class.  
public class BuilderTest{  
    public static void main(String[] args){  
        StringBuilder builder=new StringBuilder("hello");  
        builder.append("java");  
        System.out.println(builder);  
    }  
}  

Output:
hellojava
Question: Can you provide Performance Test of StringBuffer and StringBuilder?
Answer: Let's see the code to check the performance of StringBuffer and StringBuilder classes.

ConcatTest.java
//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.  
public class ConcatTest{  
    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Tpoint");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
        startTime = System.currentTimeMillis();  
        StringBuilder sb2 = new StringBuilder("Java");  
        for (int i=0; i<10000; i++){  
            sb2.append("Tpoint");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
    }  
}  

Output:
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
Question: How to create Immutable class?
Answer: There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members
Question: Can you provide Example to create Immutable class?
Answer: In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.

ImmutableDemo.java
public final class Employee  
{    
final String pancardNumber;    
public Employee(String pancardNumber)  
{    
this.pancardNumber=pancardNumber;    
}  
public String getPancardNumber(){    
return pancardNumber;    
}    
}    
public class ImmutableDemo  
{  
public static void main(String ar[])  
{  
Employee e = new Employee("ABC123");  
String s1 = e.getPancardNumber();  
System.out.println("Pancard Number: " + s1);  
}  
}  

Output:
Pancard Number: ABC123


The above class is immutable because:
-The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
-The class is final so we cannot create the subclass.
-There is no setter methods i.e. we have no option to change the value of the instance variable.

These points makes this class as immutable.
Question: What is Java toString() Method?
Answer: If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the String representation of the object.

If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation.
Question: What is the Advantage of Java toString() method?
Answer: By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
Question: Can you provide an example of Understanding problem without toString() method?
Answer: Let's see the simple code that prints reference.

Student.java
class Student{  
 int rollno;  
 String name;  
 String city;  
  
 Student(int rollno, String name, String city){  
 this.rollno=rollno;  
 this.name=name;  
 this.city=city;  
 }  
  
 public static void main(String args[]){  
   Student s1=new Student(101,"Raj","lucknow");  
   Student s2=new Student(102,"Vijay","ghaziabad");  
     
   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
}  

Output:
Student@1fee6fc
Student@1eed786


As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since Java compiler internally calls toString() method, overriding this method will return the specified values.
Question: Can you provide an Example of Java toString() method?
Answer: Let's see an example of toString() method.

Student.java
class Student{  
 int rollno;  
 String name;  
 String city;  
  
 Student(int rollno, String name, String city){  
 this.rollno=rollno;  
 this.name=name;  
 this.city=city;  
 }  
   
 public String toString(){//overriding the toString() method  
  return rollno+" "+name+" "+city;  
 }  
 public static void main(String args[]){  
   Student s1=new Student(101,"Raj","lucknow");  
   Student s2=new Student(102,"Vijay","ghaziabad");  
     
   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
}  

Output:
101 Raj lucknow
102 Vijay ghaziabad


In the above program, Java compiler internally calls toString() method, overriding this method will return the specified values of s1 and s2 objects of Student class.
Question: What is StringTokenizer in Java?
Answer: The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens.

Example of String Tokenizer class in Java

Input:
Hello welcome to JavaTpoint -> String Tokenizer -> Tokens -> “hello”,”welcome”,”to”, “JavaTpoint”
Question: What are the Constructors of the StringTokenizer Class?
Answer: There are 3 constructors defined in the StringTokenizer class.

Constructor

StringTokenizer(String str)
Description: It creates StringTokenizer with specified string.

StringTokenizer(String str, String delim)
Description: It creates StringTokenizer with specified string and delimiter.

StringTokenizer(String str, String delim, boolean returnValue)
Description:It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.
Question: What are the Methods of the StringTokenizer Class?
Answer: The six useful methods of the StringTokenizer class are as follows:

boolean hasMoreTokens()
Description: It checks if there is more tokens available.

String nextToken()
Description: It returns the next token from the StringTokenizer object.

String nextToken(String delim)
Description: It returns the next token based on the delimiter.

boolean hasMoreElements()
Description: It is the same as hasMoreTokens() method.

Object nextElement()
Description: It is the same as nextToken() but its return type is Object.

int countTokens()
Description: It returns the total number of tokens.
Question: Can you provide an Example of StringTokenizer Class?
Answer: Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.

Simple.java
import java.util.StringTokenizer;  
public class Simple{  
 public static void main(String args[]){  
   StringTokenizer st = new StringTokenizer("my name is khan"," ");  
     while (st.hasMoreTokens()) {  
         System.out.println(st.nextToken());  
     }  
   }  
}  

Output:
my
name
is
khan

The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and nextToken().
Question: Can you provide an Example of nextToken(String delim) method of the StringTokenizer class?
Answer: Test.java
import java.util.*;  
  
public class Test {  
   public static void main(String[] args) {  
       StringTokenizer st = new StringTokenizer("my,name,is,khan");  
        
      // printing next token  
      System.out.println("Next token is : " + st.nextToken(","));  
   }      
}  

Output:
Next token is : my
Question: Can you provide an Example of hasMoreTokens() method of the StringTokenizer class?
Answer: This method returns true if more tokens are available in the tokenizer String otherwise returns false.

StringTokenizer1.java
import java.util.StringTokenizer;    
public class StringTokenizer1  
{    
 /* Driver Code */  
 public static void main(String args[])  
 {    
   /* StringTokenizer object */  
   StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class"," ");    
     /* Checks if the String has any more tokens */  
     while (st.hasMoreTokens())   
     {    
         System.out.println(st.nextToken());    
     }    
 }    
}  

Output:
Demonstrating
methods
from
StringTokenizer
class


The above Java program shows the use of two methods hasMoreTokens() and nextToken() of StringTokenizer class.
Question: Can you provide an Example of hasMoreElements() method of the StringTokenizer class?
Answer: This method returns the same value as hasMoreTokens() method of StringTokenizer class. The only difference is this class can implement the Enumeration interface.

StringTokenizer2.java
import java.util.StringTokenizer;    
public class StringTokenizer2  
{    
 public static void main(String args[])  
 {    
   StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");    
     while (st.hasMoreElements())   
     {    
         System.out.println(st.nextToken());    
     }    
 }    
}
  
Output:
Hello
everyone
I
am
a
Java
developer

The above code demonstrates the use of hasMoreElements() method.
Question: Could you provide an Example of nextElement() method of the StringTokenizer class?
Answer: nextElement() returns the next token object in the tokenizer String. It can implement Enumeration interface.

StringTokenizer3.java
import java.util.StringTokenizer;    
public class StringTokenizer3  
{    
 /* Driver Code */  
 public static void main(String args[])  
 {    
   /* StringTokenizer object */  
   StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");    
     /* Checks if the String has any more tokens */  
     while (st.hasMoreTokens())   
     {    
         /* Prints the elements from the String */  
         System.out.println(st.nextElement());    
     }    
 }    
}  

Output:
Hello
Everyone
Have
a
nice
day

The above code demonstrates the use of nextElement() method.