Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
How to create a string object?
|
There are two ways to create String object:
1.By string literal
2.By new keyword
|
What is String Literal?
|
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.
|
By new keyword
|
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).
|
Can you provide Java String Example?
|
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
|
Java String class methods
|
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
|
What is Immutable String in Java?
|
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.
|
Testimmutablestring.java
|
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
|
Why String objects are immutable in Java?
|
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.
|
Why String class is Final in Java?
|
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.
|
What is Java String compare?
|
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
|
How to use Java string compares By Using equals() Method?
|
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.
|
How to use By Using compareTo() method?
|
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.
|
What is String Concatenation in Java?
|
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
|
Can you provide String Concatenation by + (String concatenation) operator?
|
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
|
How to concatenate string by concat() method?
|
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
|
Can you provide String concatenation example using StringBuilder class?
|
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.
|
Can you provide String concatenation using format() method?
|
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.
|
Can you provide an example of String concatenation using String.join() method (Java Version 8+)?
|
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.
|
Can you provide an example of String concatenation using StringJoiner class (Java Version 8+)?
|
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.
|
Can you provide an example of String concatenation using Collectors.joining() method (Java (Java Version 8+)?
|
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.
|
What is Substring in Java?
|
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).
|
Can you provide Example of Java substring() method?
|
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.
|
Can you provide an example of using String.split() method?
|
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.
|
What are Java String Class Methods?
|
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.
|
Can you provide example of Java String toUpperCase() and toLowerCase() method?
|
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
|
Can you provide example of Java String trim() method?
|
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
|
Can you provide an example of Java String startsWith() and endsWith() method?
|
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
|
Can you provide an example of Java String charAt() Method?
|
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
|
Can you provide an example of Java String length() Method?
|
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
|
Can you provide an example of Java String intern() Method?
|
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
|
Can you provide an example of Java String valueOf() Method?
|
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
|
Can you provide an example of Java String replace() Method?
|
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.
|
What is Java StringBuffer Class?
|
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.
|
What is Important Constructors of StringBuffer Class?
|
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.
|
What are the Important methods of StringBuffer class?
|
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.
|
What is a mutable String?
|
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for creating mutable strings.
|
Can you provide an example of StringBuffer Class append() Method?
|
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
|
Can you provide an example of StringBuffer insert() Method?
|
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
|
Can you provide an example of StringBuffer replace() Method?
|
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
|
Can you provide an example of StringBuffer delete() Method?
|
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
|
Can you provide an example of StringBuffer reverse() Method?
|
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
|
Can you provide an example of StringBuffer capacity() Method?
|
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
|
Can you provide an example of StringBuffer ensureCapacity() method?
|
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
|
What is Java StringBuilder Class?
|
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.
|
What are Important Constructors of StringBuilder class?
|
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.
|
What are the Important methods of StringBuilder class?
|
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.
|
Can you provide an example of Java StringBuilder Examples?
|
Let's see the examples of different methods of StringBuilder class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this String.
StringBuilderExample.java
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.
StringBuilderExample2.java
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
StringBuilderExample3.java
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
StringBuilderExample4.java
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
StringBuilderExample5.java
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder 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.
StringBuilderExample6.java
class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
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
7) StringBuilder ensureCapacity() method
The ensureCapacity() method of StringBuilder 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.
StringBuilderExample7.java
class StringBuilderExample7{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
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
|
What are the Difference of String between StringBuffer?
|
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.
|
Can you provide an example of Performance Test of String and StringBuffer?
|
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
|
Can you providean example of String and StringBuffer HashCode Test?
|
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
|
What are the Difference between StringBuffer and StringBuilder?
|
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
|
Can you provide StringBuffer Example?
|
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
|
Can you provide StringBuilder Example?
|
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
|
Can you provide Performance Test of StringBuffer and StringBuilder?
|
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
|
How to create Immutable class?
|
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
|
Can you provide Example to create Immutable class?
|
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.
|
What is Java toString() Method?
|
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.
|
What is the Advantage of Java toString() method?
|
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.
|
Can you provide an example of Understanding problem without toString() method?
|
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.
|
Can you provide an Example of Java toString() method?
|
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.
|
What is StringTokenizer in Java?
|
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”
|
What are the Constructors of the StringTokenizer Class?
|
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.
|
What are the Methods of the StringTokenizer Class?
|
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.
|
Can you provide an Example of StringTokenizer Class?
|
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().
|
Can you provide an Example of nextToken(String delim) method of the StringTokenizer class?
|
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
|
Can you provide an Example of hasMoreTokens() method of the StringTokenizer class?
|
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.
|
Can you provide an Example of hasMoreElements() method of the StringTokenizer class?
|
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.
|
Could you provide an Example of nextElement() method of the StringTokenizer class?
|
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.
|
Could you provide an Example of countTokens() method of the StringTokenizer class?
|
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.
|
How many objects will be created in the following code?
|
String s1="javatpoint";
String s2="javatpoint";
Answer: Only one.
|
What is the difference between equals() method and == operator?
|
The equals() method matches content of the strings whereas == operator matches object or reference of the strings.
|
What is Java String charAt()?
|
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];
}
|
Can you provide an example of Java String charAt() Method?
|
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)
|
Can you provide an example of Accessing First and Last Character by Using the charAt() Method?
|
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
|
Can you provide an example of Print Characters Presented at Odd Positions by Using the charAt() Method?
|
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.
|
Could you provide an example ofCounting Frequency of a character in a String by Using the charAt() Method?
|
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
|
Could you provide an example of Counting the Number of Vowels in a String by Using the chatAt() Method?
|
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
|
What is Java String compareTo()?
|
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;
}
|
Could you provide Java String compareTo() Method Example?
|
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
|
Can you provide an example of Java String compareTo(): empty string?
|
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
|
Could you provide an example of Java String compareTo(): case sensitive?
|
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.
|
Could you provide an example of Java String compareTo(): ClassCastException?
|
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
|
Could you provide an example of Java String compareTo(): NullPointerException?
|
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)
|
What is Java String concat?
|
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);
}
|
Could you provide an example of Java String concat() method example?
|
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
|
What is Java String contains()?
|
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.
|
can you provide an example of Java String contains() Method Example?
|
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
|
What are the Limitations of the Contains() method?
|
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.
|
What is the Java String endsWith()?
|
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.
|
Could you provide an example of Java String endsWith() Method Example?
|
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
|
What is Java String equals()?
|
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;
}
|
Could you provide an example of Java String equals() Method?
|
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
|
What is Java String equalsIgnoreCase()?
|
The Java String class equalsIgnoreCase() method compares the two given strings on the basis of the content of the string irrespective of the case (lower and upper) of the string. It is just like the equals() method but doesn't check the case sensitivity. If any character is not matched, it returns false, else returns true.
Signature
publicboolean equalsIgnoreCase(String str)
Parameter
str : another string i.e., compared with this string.
Returns
It returns true if characters of both strings are equal, ignoring case otherwise false.
Internal implementation
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
It is obvious from looking at the implementation that the equalsIgnoreCase() method is invoking the regionMatches() method. It makes the equalsIgnoreCase() method case-insensitive. The signature of the regionMatches() method is mentioned below.
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
The regionMatches() method parses five parameters. The first parameter ignoreCase is set to true in the above implementation. Thus, when the method is executed, it checks whether the ignoreCase flag is true or not. If yes, then one character each from both the strings is taken and then compared. If the comparison gives a false value, then both the character is converted to upper case and then checked if the comparison still gives a false value, then both the characters are converted to a lower case and then compared. If the comparison gives the true value, then both the strings have equal contents; otherwise, not. Code Snippet of the discussed comparison is mentioned below.
while (toffset < last)
{
char ch1 = getChar(value, toffset++);
char ch2 = getChar(other, ooffset++);
if (ch1 == ch2)
{
continue;
}
// convert each character to uppercase and
// then make the comparison.
// If the comparison yeilds a true value,
// then next pair of characters should be scanned
char uCh1 = Character.toUpperCase(ch1);
char uCh2 = Character.toUpperCase(ch2);
if (uCh1 == u2)
{
continue;
}
// convert each character to lowercase and
// then make the comparison.
// If the comparison yeilds a true value,
// then next pair of characters should be scanned
// Otherwise, return false.
if (Character.toLowerCase(uCh1) == Character.toLowerCase(uCh2))
{
continue;
}
return false;
}
// reaching here means the content of both the strings
// are the same after ignoring the case sensitiveness
return true;
One may argue that if we made a comparison after converting to uppercase, then why do we need an extra comparison by converting characters to the lowercase. The reason behind this is to provide to the requirement of Georgian alphabets. Conversion in uppercase does not work properly for the Georgian alphabets, as they have some strange rules about the case conversion. Therefore, one extra comparison, by converting characters to the lowercase, is required.
|
Could you provide an example of Java String equalsIgnoreCase() Method?
|
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
|
What is Java String format()?
|
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.
|
Could you provide an example of Java String format() method?
|
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
|
What is Java String Format Specifiers?
|
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.
|
What is Java String getBytes()?
|
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);
}
|
Can you provide an example of String class getBytes() Method?
|
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
|
What is Java String getChars()?
|
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);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.