hereral/Clara-Training-Data huggingface dataset:
Question: Could you provide an Example of countTokens() method of the StringTokenizer class?
Answer: This method calculates the number of tokens present in the tokenizer String.

StringTokenizer4.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"," ");    
         /* Prints the number of tokens present in the String */  
         System.out.println("Total number of Tokens: "+st.countTokens());    
 }    
}  

Output:
Total number of Tokens: 6


The above Java code demonstrates the countTokens() method of StringTokenizer() class.
Question: How many objects will be created in the following code?
Answer: String s1="javatpoint";
String s2="javatpoint";

Answer: Only one.
Question: What is the difference between equals() method and == operator?
Answer: The equals() method matches content of the strings whereas == operator matches object or reference of the strings.
Question: What is Java String charAt()?
Answer: 
The Java String class charAt() method returns a char value at the given index number.

The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.

Syntax

public char charAt(int index)    

The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length.

Specified by

CharSequence interface, located inside java.lang package.
Internal implementation
public char charAt(int index) {    
       if ((index < 0) || (index >= value.length)) {    
           throw new StringIndexOutOfBoundsException(index);    
       }    
       return value[index];    
   }
Question: Can you provide an example of Java String charAt() Method?
Answer: Let's see Java program related to string in which we will use charAt() method that perform some operation on the give string.
FileName: CharAtExample.java
public class CharAtExample{  
public static void main(String args[]){  
String name="javatpoint";  
char ch=name.charAt(4);//returns the char value at the 4th index  
System.out.println(ch);  
}}  

Output:
t


Let's see the example of the charAt() method where we are passing a greater index value. In such a case, it throws StringIndexOutOfBoundsException at run time.

FileName: CharAtExample.java
public class CharAtExample{  
public static void main(String args[]){  
String name="javatpoint";  
char ch=name.charAt(10);//returns the char value at the 10th index  
System.out.println(ch);  
}}  

Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)
Question: Can you provide an example of Accessing First and Last Character by Using the charAt() Method?
Answer: Let's see a simple example where we are accessing first and last character from the provided string.

FileName: CharAtExample3.java
public class CharAtExample3 {  
    public static void main(String[] args) {  
    String str = "Welcome to Javatpoint portal";      
    int strLength = str.length();      
    // Fetching first character  
    System.out.println("Character at 0 index is: "+ str.charAt(0));      
    // The last Character is present at the string length-1 index  
    System.out.println("Character at last index is: "+ str.charAt(strLength-1));      
    }  
}  

Output:
Character at 0 index is: W
Character at last index is: l
Question: Can you provide an example of Print Characters Presented at Odd Positions by Using the charAt() Method?
Answer: Let's see an example where we are accessing all the elements present at odd index.

FileName: CharAtExample4.java
public class CharAtExample4 {  
    public static void main(String[] args) {  
        String str = "Welcome to Javatpoint portal";          
        for (int i=0; i<=str.length()-1; i++) {  
            if(i%2!=0) {  
                System.out.println("Char at "+i+" place "+str.charAt(i));  
            }  
        }  
    }  
}  

Output:
Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place  
Char at 9 place o
Char at 11 place J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place  
Char at 23 place o
Char at 25 place t
Char at 27 place l


The position such as 7 and 21 denotes the space.
Question: Could you provide an example ofCounting Frequency of a character in a String by Using the charAt() Method?
Answer: Let's see an example in which we are counting frequency of a character in the given string.

FileName: CharAtExample5.java
public class CharAtExample5 {  
    public static void main(String[] args) {  
        String str = "Welcome to Javatpoint portal";  
        int count = 0;  
        for (int i=0; i<=str.length()-1; i++) {  
            if(str.charAt(i) == 't') {  
                count++;  
            }  
        }  
        System.out.println("Frequency of t is: "+count);  
    }  
}  

Output:
Frequency of t is: 4
Question: Could you provide an example of Counting the Number of Vowels in a String by Using the chatAt() Method?
Answer: Let's see an example where we are counting the number of vowels present in a string with the help of the charAt() method.

FileName: CharAtExample6.java
// import statement  
import java.util.*;  
  
public class CharAtExample6  
{    
ArrayList<Character> al;  
  
// constructor for creating and   
// assigning values to the ArrayList al  
CharAtExample6()  
{  
al = new ArrayList<Character>();    
al.add('A'); al.add('E');  
al.add('a'); al.add('e');  
al.add('I'); al.add('O');  
al.add('i'); al.add('o');  
al.add('U'); al.add('u');  
}  
   
// a method that checks whether the character c is a vowel or not     
private boolean isVowel(char c)  
{  
for(int i = 0; i < al.size(); i++)  
{  
if(c == al.get(i))  
{  
return true;  
}  
}  
return false;  
}  
// a method that calculates vowels in the String s  
public int countVowels(String s)  
{  
int countVowel = 0; // store total number of vowels  
int size = s.length(); // size of string  
for(int j = 0; j < size; j++)  
{  
char c = s.charAt(j);  
if(isVowel(c))  
{  
// vowel found!  
// increase the count by 1  
countVowel = countVowel + 1;  
}  
}  
  
return countVowel;  
}  
      
// main method  
public static void main(String argvs[])   
{    
// creating an object of the class CharAtExample6  
CharAtExample6 obj = new CharAtExample6();  
  
String str = "Javatpoint is a great site for learning Java.";    
  
int noOfVowel = obj.countVowels(str);  
  
System.out.println("String: " + str);  
  
System.out.println("Total number of vowels in the string are: "+ noOfVowel + "\n");    
  
str = "One apple in a day keeps doctor away.";  
  
System.out.println("String: " + str);  
  
noOfVowel = obj.countVowels(str);  
  
System.out.println("Total number of vowels in the string are: "+ noOfVowel);   
}    
}    

Output:
String: Javatpoint is a great site for learning Java.
Total number of vowels in the string are: 16

String: One apple in a day keeps doctor away.
Total number of vowels in the string are: 13
Question: What is Java String compareTo()?
Answer: The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0.

It compares strings on the basis of the Unicode value of each character in the strings.

If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value). If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0.

if s1 > s2, it returns positive number  
if s1 < s2, it returns negative number  
if s1 == s2, it returns 0  

Syntax
public int compareTo(String anotherString)  
  
The method accepts a parameter of type String that is to be compared with the current string.

It returns an integer value. It throws the following two exceptions:
ClassCastException: If this object cannot get compared with the specified object.
NullPointerException: If the specified object is null.

Internal implementation
int compareTo(String anotherString) {  
    int length1 = value.length;  
    int length2 = anotherString.value.length;  
    int limit = Math.min(length1, length2);  
    char v1[] = value;  
    char v2[] = anotherString.value;  
   
    int i = 0;  
    while (i < limit) {  
        char ch1 = v1[i];  
        char ch2 = v2[i];  
        if (ch1 != ch2) {  
            return ch1 - ch2;  
        }  
        i++;  
    }  
    return length1 - length2;  
}
Question: Could you provide Java String compareTo() Method Example?
Answer: FileName: CompareToExample.java

public class CompareToExample{  
public static void main(String args[]){  
String s1="hello";  
String s2="hello";  
String s3="meklo";  
String s4="hemlo";  
String s5="flag";  
System.out.println(s1.compareTo(s2));//0 because both are equal  
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"  
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"  
}}  

Output:
0
-5
-1
2
Question: Can you provide an example of Java String compareTo(): empty string?
Answer: When we compare two strings in which either first or second string is empty, the method returns the length of the string. So, there may be two scenarios:

-If first string is an empty string, the method returns a negative
-If second string is an empty string, the method returns a positive number that is the length of the first string.

FileName: CompareToExample2.java
public class CompareToExample2{  
public static void main(String args[]){  
String s1="hello";  
String s2="";  
String s3="me";  
System.out.println(s1.compareTo(s2));  
System.out.println(s2.compareTo(s3));  
}} 
 
Output:
5
-2
Question: Could you provide an example of Java String compareTo(): case sensitive?
Answer: To check whether the compareTo() method considers the case sensitiveness of characters or not, we will make the comparison between two strings that contain the same letters in the same sequence.

Suppose, a string having letters in uppercase, and the second string having the letters in lowercase. On comparing these two string, if the outcome is 0, then the compareTo() method does not consider the case sensitiveness of characters; otherwise, the method considers the case sensitiveness of characters.

FileName: CompareToExample3.java
public class CompareToExample3  
{  
// main method  
public static void main(String argvs[])  
{  
  
// input string in uppercase  
String st1 = new String("INDIA IS MY COUNTRY");  
  
// input string in lowercase  
String st2 = new String("india is my country");  
  
System.out.println(st1.compareTo(st2));  
}  
}  

Output:
-32


Conclusion: It is obvious by looking at the output that the outcome is not equal to zero. Hence, the compareTo() method takes care of the case sensitiveness of characters.
Question: Could you provide an example of Java String compareTo(): ClassCastException?
Answer: The ClassCastException is thrown when objects of incompatible types get compared. In the following example, we are comparing an object of the ArrayList (al) with a string literal ("Sehwag").

FileName: CompareToExample4.java
// import statement  
import java.util.*;  
  
class Players   
{  
       
private String name;  
  
// constructor of the class  
public Players(String str)  
{  
name = str;  
}  
   
}  
  
public class CompareToExample4  
{  
   
// main method  
public static void main(String[] args)   
{  
   
Players ronaldo = new Players("Ronaldo");  
Players sachin = new Players("Sachin");  
Players messi = new Players("Messi");  
ArrayList<Players> al = new ArrayList<>();  
  
al.add(ronaldo);  
al.add(sachin);  
al.add(messi);  
   
// performing binary search on the list al  
Collections.binarySearch(al, "Sehwag", null);  
}  
       
}  

Output:
Exception in thread "main" java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable
Question: Could you provide an example of Java String compareTo(): NullPointerException?
Answer: The NullPointerException is thrown when a null object invokes the compareTo() method. Observe the following example.

FileName: CompareToExample5.java
public class CompareToExample5  
{  
// main method  
public static void main(String[] args)   
{  
   
String str = null;  
  
// null is invoking the compareTo method. Hence, the NullPointerException  
// will be raised  
int no =  str.compareTo("India is my country.");  
  
System.out.println(no);  
}  
}  

Output:
Exception in thread "main" java.lang.NullPointerException
	at CompareToExample5.main(CompareToExample5.java:9)
Question: What is Java String concat?
Answer: The Java String class concat() method combines specified string at the end of this string. It returns a combined string. It is like appending another string.

Signature
The signature of the string concat() method is given below:

public String concat(String anotherString)    
Parameter
anotherString : another string i.e., to be combined at the end of this string.

Returns
combined string

Internal implementation
public String concat(String str) {    
       int otherLen = str.length();    
       if (otherLen == 0) {    
           return this;    
       }    
       int len = value.length;    
       char buf[] = Arrays.copyOf(value, len + otherLen);    
       str.getChars(buf, len);    
       return new String(buf, true);    
   }
Question: Could you provide an example of Java String concat() method example?
Answer: FileName: ConcatExample.java

public class ConcatExample{    
public static void main(String args[]){    
String s1="java string";    
// The string s1 does not get changed, even though it is invoking the method      
// concat(), as it is immutable. Therefore, the explicit assignment is required here.  
s1.concat("is immutable");    
System.out.println(s1);    
s1=s1.concat(" is immutable so assign it explicitly");    
System.out.println(s1);    
}}    
Output:

java string
java string is immutable so assign it explicitly
Question: What is Java String contains()?
Answer: The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found in this string otherwise returns false.
Signature
The signature of string contains() method is given below:
public boolean contains(CharSequence sequence)    
Parameter

sequence : specifies the sequence of characters to be searched.
Returns

true if the sequence of char value exists, otherwise false.
Exception

NullPointerException : if the sequence is null.

Internal implementation

public boolean contains(CharSequence s) {    
      return indexOf(s.toString()) > -1;    
  }    


Here, the conversion of CharSequence takes place into String. After that, the indexOf() method is invoked. The method indexOf() either returns 0 or a number greater than 0 in case the searched string is found.
However, when the searched string is not found, the indexOf() method returns -1. Therefore, after execution, the contains() method returns true when the indexOf() method returns a non-negative value (when the searched string is found); otherwise, the method returns false.
Question: can you provide an example of Java String contains() Method Example?
Answer: FileName: ContainsExample.java

class ContainsExample{  
public static void main(String args[]){  
String name="what do you know about me";  
System.out.println(name.contains("do you know"));  
System.out.println(name.contains("about"));  
System.out.println(name.contains("hello"));  
}}  

Output:
true
true
false
Question: What are the Limitations of the Contains() method?
Answer: Following are some limitations of the contains() method:

-The contains() method should not be used to search for a character in a string. Doing so results in an error.
-The contains() method only checks for the presence or absence of a string in another string. It never reveals at which index the searched index is found. Because of these limitations, it is better to use the indexOf() method instead of the contains() method.
Question: What is the Java String endsWith()?
Answer: The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with the given suffix; else returns false.

Signature
The syntax or signature of endsWith() method is given below.
public boolean endsWith(String suffix)   

Parameter
suffix : Sequence of character

Returns
true or false

Internal implementation
public boolean endsWith(String suffix) {    
      return startsWith(suffix, value.length - suffix.value.length);    
  }    

The internal implementation shows that the endWith() method is dependent on the startsWith() method of the String class.
Question: Could you provide an example of Java String endsWith() Method Example?
Answer: FileName: EndsWithExample.java

public class EndsWithExample{  
public static void main(String args[]){  
String s1="java by javatpoint";  
System.out.println(s1.endsWith("t"));  
System.out.println(s1.endsWith("point"));  
}}  

Output:
true
true
Question: What is Java String equals()?
Answer: The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

The String equals() method overrides the equals() method of the Object class.

Signature
publicboolean equals(Object anotherObject)  
Parameter
anotherObject : another object, i.e., compared with this string.
Returns
true if characters of both strings are equal otherwise false.
Internal implementation
public boolean equals(Object anObject) {    
      if (this == anObject) {    
          return true;    
      }    
      if (anObject instanceof String) {    
          String anotherString = (String) anObject;    
          int n = value.length;    
          if (n == anotherString.value.length) {    
              char v1[] = value;    
              char v2[] = anotherString.value;    
              int i = 0;    
              while (n-- != 0) {    
                  if (v1[i] != v2[i])    
                          return false;    
                  i++;    
              }    
              return true;    
          }    
      }    
      return false;    
  }
Question: Could you provide an example of Java String equals() Method?
Answer: FileName: EqualsExample.java

public class EqualsExample{  
public static void main(String args[]){  
String s1="javatpoint";  
String s2="javatpoint";  
String s3="JAVATPOINT";  
String s4="python";  
System.out.println(s1.equals(s2));//true because content and case is same  
System.out.println(s1.equals(s3));//false because case is not same  
System.out.println(s1.equals(s4));//false because content is not same  
}}  

Output:
true
false
false
Question: Could you provide an example of Java String equalsIgnoreCase() Method?
Answer: FileName: EqualsIgnoreCaseExample.java

public class EqualsIgnoreCaseExample{  
public static void main(String args[]){  
String s1="javatpoint";  
String s2="javatpoint";  
String s3="JAVATPOINT";  
String s4="python";  
System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same  
System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored  
System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same  
}}  

Output:
true
true
false
Question: What is Java String format()?
Answer: The java string format() method returns the formatted string by given locale, format and arguments.

If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.

The format() method of java language is like sprintf() function in c language and printf() method of java language.
Internal implementation
public static String format(String format, Object... args) {  
       return new Formatter().format(format, args).toString();  
   }  

Signature
There are two type of string format() method:
public static String format(String format, Object... args)  
and,  
public static String format(Locale locale, String format, Object... args)  

Parameters
locale : specifies the locale to be applied on the format() method.
format : format of the string.
args : arguments for the format string. It may be zero or more.

Returns
formatted string

Throws
NullPointerException : if format is null.
IllegalFormatException : if format is illegal or incompatible.
Question: Could you provide an example of Java String format() method?
Answer: public class FormatExample{  
public static void main(String args[]){  
String name="sonoo";  
String sf1=String.format("name is %s",name);  
String sf2=String.format("value is %f",32.33434);  
String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part filling with 0  
  
System.out.println(sf1);  
System.out.println(sf2);  
System.out.println(sf3);  
}}  

name is sonoo
value is 32.334340
value is                  32.334340000000
Question: What is Java String Format Specifiers?
Answer: Here, we are providing a table of format specifiers supported by the Java String.

Format Specifier: %a
Data Type: floating point (except BigDecimal)
Output: Returns Hex output of floating point number.

Format Specifier: %b
Data Type: Any type 
Output: "true" if non-null, "false" if null

Format Specifier: %c
Data Type: character
Output:  Unicode character

Format Specifier: %d
Data Type: integer (incl. byte, short, int, long, bigint)
Output: Decimal Integer

Format Specifier: %e
Data Type: floating point
Output:Output: decimal number in scientific notation

Format Specifier: %f
Data Type: floating point
Output: decimal number

Format Specifier:%g
Data Type: floating point
Output: decimal number, possibly in scientific notation depending on the precision and value.

Format Specifier: %h
Data Type: any type
Output: Hex String of value from hashCode() method.

Format Specifier: %n
Data Type: none
Output: Platform-specific line separator.
Format Specifier: %o
Data Type: integer (incl. byte, short, int, long, bigint)
Output: Octal number

Format Specifier:%s
Data Type: any type
Output: String value

Format Specifier:%t
Data Type: Date/Time (incl. long, Calendar, Date and TemporalAccessor)
Output:%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.

Format Specifier: %x
Data Type: integer (incl. byte, short, int, long, bigint)
Output: Hex string.
Question: What is Java String getBytes()?
Answer: The Java String class getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of bytes.
Signature
There are three variants of getBytes() method. The signature or syntax of string getBytes() method is given below:

public byte[] getBytes()  
public byte[] getBytes(Charset charset)  
public byte[] getBytes(String charsetName)throws UnsupportedEncodingException  
Parameters
charset / charsetName - The name of a charset the method supports.
Returns
Sequence of bytes.
Exception Throws
UnsupportedEncodingException: It is thrown when the mentioned charset is not supported by the method.

Internal implementation
public byte[] getBytes() {    
        return StringCoding.encode(value, 0, value.length);    
    }
Question: Can you provide an example of String class getBytes() Method?
Answer: The parameterless getBytes() method encodes the string using the default charset of the platform, which is UTF - 8. The following two examples show the same.

FileName: StringGetBytesExample.java
public class StringGetBytesExample{  
public static void main(String args[]){  
String s1="ABCDEFG";  
byte[] barr=s1.getBytes();  
for(int i=0;i<barr.length;i++){  
System.out.println(barr[i]);  
}  
}}  

Output:
65
66
67
68
69
70
71
Question: What is Java String getChars()?
Answer: The Java String class getChars() method copies the content of this string into a specified char array. There are four arguments passed in the getChars() method. The signature of the getChars() method is given below:

Signature
public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)    

Parameters
int srcBeginIndex: The index from where copying of characters is started.

int srcEndIndex: The index which is next to the last character that is getting copied.

Char[] destination: The char array where characters from the string that invokes the getChars() method is getting copied.

int dstEndIndex: It shows the position in the destination array from where the characters from the string will be pushed.

Returns
It doesn't return any value.
Exception Throws
The method throws StringIndexOutOfBoundsException when any one or more than one of the following conditions holds true.
-If srcBeginIndex is less than zero.
-If srcBeginIndex is greater than srcEndIndex.
-If srcEndIndex is greater than the size of the string that invokes the method
-If dstEndIndex is is less than zero.
If dstEndIndex + (srcEndIndex - srcBeginIndex) is greater than the size of the destination array.

Internal implementation
The signature or syntax of string getChars() method is given below:
void getChars(char dst[], int dstBegin) {    
        // copies value from 0 to dst - 1  
        System.arraycopy(value, 0, dst, dstBegin, value.length);    
    }
Question: Can you provide an example of Java String getChars() Method?
Answer: FileName: StringGetCharsExample.java

public class StringGetCharsExample{  
public static void main(String args[]){  
 String str = new String("hello javatpoint how r u");  
      char[] ch = new char[10];  
      try{  
         str.getChars(6, 16, ch, 0);  
         System.out.println(ch);  
      }catch(Exception ex){System.out.println(ex);}  
}}  

Output:
javatpoint
Question: What is Java String indexOf()?
Answer: The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
Signature
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below:
1) int indexOf(int ch) - It returns the index position for the given char value
2) int indexOf(int ch, int fromIndex) - It returns the index position for the given char value and from index
3) int indexOf(String substring) - It returns the index position for the given substring
4) int indexOf(String substring, int fromIndex) - It returns the index position for the given substring and from index

Parameters
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.
Returns
Index of the searched string or character.
Internal Implementation
public int indexOf(int ch) {  
        return indexOf(ch, 0);  
    }
Question: Can you provide an example of Java String indexOf() Method?
Answer: FileName: IndexOfExample.java

public class IndexOfExample{  
public static void main(String args[]){  
String s1="this is index of example";  
//passing substring  
int index1=s1.indexOf("is");//returns the index of is substring  
int index2=s1.indexOf("index");//returns the index of index substring  
System.out.println(index1+"  "+index2);//2 8  
  
//passing substring with from index  
int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index  
System.out.println(index3);//5 i.e. the index of another is  
  
//passing char value  
int index4=s1.indexOf('s');//returns the index of s char value  
System.out.println(index4);//3  
}}  

Output:
2  8
5
3

We observe that when a searched string or character is found, the method returns a non-negative value. If the string or character is not found, -1 is returned. We can use this property to find the total count of a character present in the given string. Observe the following example.

FileName: IndexOfExample5.java

public class IndexOfExample5  
{    
// main method  
public static void main(String argvs[])   
{     
  
String str = "Welcome to JavaTpoint";      
int count = 0;  
int startFrom = 0;  
for(; ;)  
{  
  
int index = str.indexOf('o', startFrom);  
  
if(index >= 0)  
{  
// match found. Hence, increment the count  
count = count + 1;  
  
// start looking after the searched index  
startFrom = index + 1;  
}  
  
else  
{  
// the value of index is - 1 here. Therefore, terminate the loop  
break;  
}  
  
}  
  
System.out.println("In the String: "+ str);   
System.out.println("The 'o' character has come "+ count + " times");  
}    
}    

Output:
In the String: Welcome to JavaTpoint
The 'o' character has come 3 times
Question: Can you provide an example of Java String indexOf(String substring) Method?
Answer: The method takes substring as an argument and returns the index of the first character of the substring.

FileName: IndexOfExample2.java
public class IndexOfExample2 {  
    public static void main(String[] args) {  
        String s1 = "This is indexOf method";         
        // Passing Substring    
        int index = s1.indexOf("method"); //Returns the index of this substring  
        System.out.println("index of substring "+index);          
    }  
  
}  

Output:
index of substring 16
Question: Can you provide an example of Java String indexOf(String substring, int fromIndex) Method?
Answer: The method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex.

FileName: IndexOfExample3.java
public class IndexOfExample3 {  
    public static void main(String[] args) {      
        String s1 = "This is indexOf method";         
        // Passing substring and index  
        int index = s1.indexOf("method", 10); //Returns the index of this substring  
        System.out.println("index of substring "+index);  
        index = s1.indexOf("method", 20); // It returns -1 if substring does not found  
        System.out.println("index of substring "+index);          
    }  
}  

Output:
index of substring 16
index of substring -1
Question: Can you provide an example of Java String indexOf(int char, int fromIndex) Method?
Answer: The method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex.

FileName: IndexOfExample4.java
public class IndexOfExample4 {  
    public static void main(String[] args) {          
        String s1 = "This is indexOf method";         
        // Passing char and index from  
        int index = s1.indexOf('e', 12); //Returns the index of this char  
        System.out.println("index of char "+index);       
    }  
}  

Output:
index of char 17
Question: What is Java String intern()?
Answer: The Java String class intern() method returns the interned string. It returns the canonical representation of string.
It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.
Signature
The signature of the intern() method is given below:
public String intern()  
Returns
interned string
Question: What is The need and working of the String.intern() Method?
Answer: When a string is created in Java, it occupies memory in the heap. Also, we know that the String class is immutable. Therefore, whenever we create a string using the new keyword, new memory is allocated in the heap for corresponding string, which is irrespective of the content of the array. Consider the following code snippet.

String str = new String("Welcome to JavaTpoint.");   
String str1 = new String("Welcome to JavaTpoint");  
System.out.println(str1 == str); // prints false  

The println statement prints false because separate memory is allocated for each string literal. Thus, two new string objects are created in the memory i.e. str and str1. that holds different references.

We know that creating an object is a costly operation in Java. Therefore, to save time, Java developers came up with the concept of String Constant Pool (SCP). The SCP is an area inside the heap memory. It contains the unique strings. In order to put the strings in the string pool, one needs to call the intern() method. Before creating an object in the string pool, the JVM checks whether the string is already present in the pool or not. If the string is present, its reference is returned.

String str = new String("Welcome to JavaTpoint").intern(); // statement - 1  
String str1 = new String("Welcome to JavaTpoint").intern(); // statement - 2  
System.out.println(str1 == str); // prints true  

In the above code snippet, the intern() method is invoked on the String objects. Therefore, the memory is allocated in the SCP. For the second statement, no new string object is created as the content of str and str1 are the same. Therefore, the reference of the object created in the first statement is returned for str1. Thus, str and str1 both point to the same memory. Hence, the print statement prints true.
Question: Could you provide an example of Java String intern() Method Example?
Answer: FileName: InternExample.java

public class InternExample{  
public static void main(String args[]){  
String s1=new String("hello");  
String s2="hello";  
String s3=s1.intern();//returns string from pool, now it will be same as s2  
System.out.println(s1==s2);//false because reference variables are pointing to different instance  
System.out.println(s2==s3);//true because reference variables are pointing to same instance  
}}  

Output:
false
true
Question: What are the Points to Remember at intern() method?
Answer: Following are some important points to remember regarding the intern() method:
1) A string literal always invokes the intern() method, whether one mention the intern() method along with the string literal or not. For example,

String s = "d".intern();  
String p = "d"; // compiler treats it as String p = "d".intern();  
System.out.println(s == p); // prints true  

2) Whenever we create a String object using the new keyword, two objects are created. For example,

String str = new ("Hello World");  

Here, one object is created in the heap memory outside of the SCP because of the usage of the new keyword. As we have got the string literal too ("Hello World"); therefore, one object is created inside the SCP, provided the literal "Hello World" is already not present in the SCP.
Question: What is Java String isEmpty()?
Answer: The Java String class isEmpty() method checks if the input string is empty or not. Note that here empty means the number of characters contained in a string is zero.
Signature
The signature or syntax of string isEmpty() method is given below:
public boolean isEmpty()    
Returns
true if length is 0 otherwise false.
Since
1.6
Internal implementation
public boolean isEmpty() {    
        return value.length == 0;    
    }
Question: Could you provide an example of Java String isEmpty() method example?
Answer: FileName: StringIsEmptyExample.java

public class IsEmptyExample{  
public static void main(String args[]){  
String s1="";  
String s2="javatpoint";  
  
System.out.println(s1.isEmpty());  
System.out.println(s2.isEmpty());  
}}  

Output:
true
false
Question: Could you provide an examples of Empty Vs. Null Strings?
Answer: Earlier in this tutorial, we have discussed that the empty strings contain zero characters. However, the same is true for a null string too. A null string is a string that has no value.

String str = ""; // empty string  
String str1 = null; // null string. It is also not containing any characters.  

The isEmpty() method is not fit for checking the null strings. The following example shows the same.

FileName: StringIsEmptyExample3.java
public class StringIsEmptyExample3   
{  
// main method  
public static void main(String argvs[])  
{  
String str = null;  
if(str.isEmpty())  
{  
System.out.println("The string is null.");  
}  
else  
{  
System.out.println("The string is not null.");  
}  
}  
}  

Output:
Exception in thread "main" java.lang.NullPointerException
	at StringIsEmptyExample3.main(StringIsEmptyExample3.java:7)

Here, we can use the == operator to check for the null strings.
FileName: StringIsEmptyExample4.java
class StringIsEmptyExample4  
{  
// main method  
public static void main(String argvs[])  
{  
String str = null;  
if(str == null)  
{  
System.out.println("The string is null.");  
}  
else  
{  
System.out.println("The string is not null.");  
}  
}  
}  

Output:
The string is null.
Question: Could you provide an example of Blank Strings?
Answer: Blank strings are those strings that contain only white spaces. The isEmpty() method comes in very handy to check for the blank strings. Consider the following example.

FileName: StringIsEmptyExample5.java
public class StringIsEmptyExample5   
{  
// main method  
public static void main(String argvs[])  
{  
// a blank string  
String str = "     ";  
int size = str.length();  
  
// trim the white spaces and after that  
// if the string results in the empty string   
// then the string is blank; otherwise, not.  
if(size == 0)  
{  
System.out.println("The string is empty. \n");  
}  
else if(size > 0 && str.trim().isEmpty())  
{  
System.out.println("The string is blank. \n");  
}  
else  
{  
System.out.println("The string is not blank. \n");  
}  
  
str = " Welcome to JavaTpoint.  ";  
size = str.length();  
if(size == 0)  
{  
System.out.println("The string is empty. \n");  
}  
if(size > 0 && str.trim().isEmpty())  
{  
System.out.println("The string is blank. \n");  
}  
else  
{  
System.out.println("The string is not blank. \n");  
}  
}  
}  

Output:
The string is blank. 
The string is not blank.
Question: What is Java String join()?
Answer: The Java String class join() method returns a string joined with a given delimiter. In the String join() method, the delimiter is copied for each element. The join() method is included in the Java string since JDK 1.8.
There are two types of join() methods in the Java String class.
Signature
The signature or syntax of the join() method is given below:
public static String join(CharSequence delimiter, CharSequence... elements)    
and    
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)    
Parameters
delimiter : char value to be added with each element
elements : char value to be attached with delimiter
Returns
joined string with delimiter
Exception Throws
NullPointerException if element or delimiter is null.
Since
1.8
Internal Implementation
// type - 1  
public static String join(CharSequence delimiter, CharSequence... elements)   
{  
        Objects.requireNonNull(elements);  
        Objects.requireNonNull(delimiter);        
          
        StringJoiner jnr = new StringJoiner(delimiter);  
        for (CharSequence c: elements)   
        {  
            jnr.add(c);  
        }  
        return jnr.toString();  
}   


// type - 2  
public static String join(CharSequence delimiter, CharSequence... elements)   
{  
        Objects.requireNonNull(elements);  
        Objects.requireNonNull(delimiter);        
          
        StringJoiner jnr = new StringJoiner(delimiter);  
        for (CharSequence c: elements)   
        {  
            jnr.add(c);  
        }  
        return jnr.toString();  
}  
  
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)   
{  
  
  
        Objects.requireNonNull(elements);  
        Objects.requireNonNull(delimiter);  
          
        StringJoiner jnr = new StringJoiner(delimiter);  
        for (CharSequence c: elements)   
        {  
            joiner.add(c);  
        }  
        return jnr.toString();  
    }
Question: Could you provide Java String join() Method Example?
Answer: FileName: StringJoinExample.java

public class StringJoinExample{  
public static void main(String args[]){  
String joinString1=String.join("-","welcome","to","javatpoint");  
System.out.println(joinString1);  
}}  

Output:
welcome-to-javatpoint
Question: Can you provide an example of Java String lastIndexOf() method?
Answer: FileName: LastIndexOfExample.java

public class LastIndexOfExample{  
public static void main(String args[]){  
String s1="this is index of example";//there are 2 's' characters in this sentence  
int index1=s1.lastIndexOf('s');//returns last index of 's' char value  
System.out.println(index1);//6  
}}  

Output:
6
Question: Can provide an example of Java String lastIndexOf(int ch, int fromIndex) Method?
Answer: Here, we are finding the last index from the string by specifying fromIndex.

FileName: LastIndexOfExample2.java
public class LastIndexOfExample2 {  
    public static void main(String[] args) {  
        String str = "This is index of example";  
        int index = str.lastIndexOf('s',5);  
        System.out.println(index);        
    }  
}  

Output:
3
Question: Could you provide an example of Java String lastIndexOf(String substring) Method?
Answer: It returns the last index of the substring.

FileName: LastIndexOfExample3.java
public class LastIndexOfExample3 {  
    public static void main(String[] args) {           
        String str = "This is last index of example";  
        int index = str.lastIndexOf("of");  
        System.out.println(index);        
    }  
}  

Output:
19
Question: Can you provide an example of Java String lastIndexOf(String substring, int fromIndex) Method?
Answer: It returns the last index of the substring from the fromIndex.

FileName: LastIndexOfExample4.java
public class LastIndexOfExample4 {  
    public static void main(String[] args) {           
        String str = "This is last index of example";  
        int index = str.lastIndexOf("of", 25);  
        System.out.println(index);  
        index = str.lastIndexOf("of", 10);  
        System.out.println(index); // -1, if not found        
    }  
}  
Output:
19
-1
Question: What is Java String length()?
Answer: The Java String class length() method finds the length of a string. The length of the Java string is the same as the Unicode code units of the string.

Signature
The signature of the string length() method is given below:
public int length()  
Specified by
CharSequence interface
Returns
Length of characters. In other words, the total number of characters present in the string.
Internal implementation
public int length() {  
      return value.length;  
  }  

The String class internally uses a char[] array to store the characters. The length variable of the array is used to find the total number of elements present in the array. Since the Java String class uses this char[] array internally; therefore, the length variable can not be exposed to the outside world. Hence, the Java developers created the length() method, the exposes the value of the length variable. One can also think of the length() method as the getter() method, that provides a value of the class field to the user. The internal implementation clearly depicts that the length() method returns the value of then the length variable.
Question: Could you provide Java String length() method example?
Answer: FileName: LengthExample.java

public class LengthExample{  
public static void main(String args[]){  
String s1="javatpoint";  
String s2="python";  
System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string  
System.out.println("string length is: "+s2.length());//6 is the length of python string  
}}  

Output:
string length is: 10
string length is: 6
Question: What is Java String replace()?
Answer: The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.

Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values.

Signature
There are two types of replace() methods in Java String class.
public String replace(char oldChar, char newChar)    
public String replace(CharSequence target, CharSequence replacement)    
The second replace() method is added since JDK 1.5.
Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters
Returns
replaced string
Exception Throws
NullPointerException: if the replacement or target is equal to null.
Internal implementation
public String replace(char oldChar, char newChar) {    
       if (oldChar != newChar) {    
           int len = value.length;    
           int i = -1;    
           char[] val = value; /* avoid getfield opcode */    
    
           while (++i < len) {    
               if (val[i] == oldChar) {    
                   break;    
               }    
           }    
           if (i < len) {    
               char buf[] = new char[len];    
               for (int j = 0; j < i; j++) {    
                   buf[j] = val[j];    
               }    
               while (i < len) {    
                   char c = val[i];    
                   buf[i] = (c == oldChar) ? newChar : c;    
                   i++;    
               }    
               return new String(buf, true);    
           }    
       }    
       return this;    
   }    


public String replace(CharSequence target, CharSequence replacement)  
{         
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(  
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));  
}
Question: Can you provide an example of Java String replace(char old, char new) method?
Answer: FileName: ReplaceExample1.java

public class ReplaceExample1{  
public static void main(String args[]){  
String s1="javatpoint is a very good website";  
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'  
System.out.println(replaceString);  
}}  

Output:
jevetpoint is e very good website
Question: Could you provide Java String replace(CharSequence target, CharSequence replacement) method example?
Answer: FileName: ReplaceExample2.java

public class ReplaceExample2{  
public static void main(String args[]){  
String s1="my name is khan my name is java";  
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"  
System.out.println(replaceString);  
}}  

Output:
my name was khan my name was java
Question: What is Java String replaceAll()?
Answer: The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.

Signature
public String replaceAll(String regex, String replacement)  
Parameters
regex : regular expression
replacement : replacement sequence of characters
Returns
replaced string
Exception Throws
PatternSyntaxException: if the syntax of the regular expression is not valid.
Internal implementation

public String replaceAll(String regex, String replacement) {  
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);  
}