What is Java String?
- Categories Strings in Java, String, Java
To understand what is Java String watch our playlist – click here
1. What is String class?
Ans.
- A String is a collection of characters in a sequence; for example a word can be a String and a sentence can also be a String.
- A String is treated as object which is constant i.e. a String can not be changed once it created in a program.
- String objects are immutable that is ones String object is created it cannot be modified or changed.
Q. 2 How do you create a String Object?
Ans. New String can be created by any of these methods
- Using String Default Constructor: String h0 = new String();
- Using String parameterized Constructor: String h1 = new String(“Hello”);
- Using character array in String parameterized Constructor:
char[] h3 = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ };
String h4 = new String(h3); - Assigning a String literal directly: String h2 = “Hello “;
Q. 3 Explain what do you mean when you say String in immutable in Java?
Ans. When you create a new string object for e.g. ch in the diagram, Java has something called as String constant pool in heap which stores the value and ch refers to it.
If you create a second variable referring to the same string, it creates only a new reference variable and it points to the same string.
String ch = “Hello”;
String ch1=ch;
String ch2="Hello";
Suppose if we try to use a function toUpperCase on ch. It does not change ch. VM creates a new string with upper case and returns a reference to that.
ch2 = ch.toUpperCase();
So once a String object is created, if you change it, it creates a new String object. This shows than the String is immutable. So it is critical that you have the return value assigned to a new String variable otherwise your string is lost.
Q. 4 What do you mean by a package? Give three examples.
Ans. A package in java is a group of logically related classes together in the form of java class libraries in which all related functions and information are pre-stored which helps in executing a program.
Example. Java.io, java.util, java.lang
Q. 5 What is String Buffer? How we create a String Buffer?
Ans.
- Any string or sequence of character created using StringBuffer class is considered as mutable i.e the characters that the string contain can be modified or changed.
- It represents flexible length of mutable sequence of characters in which various characters and substrings can be inserted.
- String Buffer is created as follows:
StringBuffer p=new StringBuffer(“SimplyCoding”);
Q. 6 In which package is String class included?
Ans. String Class is included in java.lang.
Q. 7 Why we do not need to import any library for using String class?
Ans. String Class is included in java.lang. Since Java imports java.lang by default, we do not need to explicitly include it in our program.
Q. 8 Which Scanner class function is used to input String?
Ans. We can use next() or nextLine() to input a String from a user. next() function is used to read only one word or till first newline. While nextLine() can read complete line till EOL.
Q. 9 How do you convert a String to primitive type like int, double etc.?
Ans. To convert String to primitive type, we can use Wrapper class functions. There are two methods.
- Every Wrapper class except character class contains a method parseXxx() method to find primitive for the given String object.
- E.g. int i = Integer.parseInt(“10”);
- double d – Double.parseDouble(“12.45”);
- Every Wrapper class contains a method valueOf() to create a Wrapper object for the given String.
- E. g. int I = Integer.valueOf(“10”);
- float f =valeOf(“3.14”);
Q. 10 How do you convert a primitive type to String?
Ans. To convert primitive type to String, we can use Wrapper class functions.
We can use toString() method to convert Wrapper object or primitive to String.
E.g. String s = Double.toString(10.5);
Q. 11 List of different String Functions
Ans.
Method | Return | parameter |
---|---|---|
char charAt(int index) | char | int |
int length() | int | – |
int compareTo(String) CompareToIgnoreCase() | int | String |
int lastIndexOf()/ indexOf(int ch/ String str) | int | int, String |
boolean equals() equalsIgnoreCase () | boolean | String |
boolean StartsWith() endsWith() | boolean | String |
Boolean contains(str) | boolean | String |
String concat(String str) | String | String |
String replace(char old, char new) | String | Char, string |
String substring(int beginI, int endI): | String | int |
String toLowerCase() toUpperCase() | String | – |
String trim() | String | – |
Q. 12 What is the Difference between equals() and compareTo() method.
Ans.
equals() | compareTo() |
---|---|
This function is used to check only the equality of two strings and return a boolean result in the form of true or false. | This is a sting function and used to compare two strings “lexicographically” and returns integer result in the form of positive (>0), negative(<0) or zero (=0) |
boolean res= “Simply”.equals(“Simply”) //return ‘true’ boolean res= “Simply”.equals(“SIMPLY”) //return ‘false’ | boolean res= “SIMPLY”.equals(“SIMPLY”) //it gives result zero |
Q. 13 Write a short note on contains() method.
Ans. The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
Syntax: public boolean contains(CharSequence chars)
Q. 14 State the data type and value of res after the following is executed:
char ch=‘n’;
res=Character.toUpperCase(ch);
Ans. res is of char type is value is ‘N’.
Q. 15 Give the use of trim() and length(). Explain with example.
Ans.
trim(): String trim() method is used to avoid the white space before of any String. Trim method does not have any parameters.
Example:
String s1= “simply”;
String s2= new String(s1, trim());
System.out.println(s1.trim());
length(): This method returns the length of sequence of characters as an int value.
Example:
String s1=”simply”;
System.out.println(s1.length());
Q. 16 What is the difference between indexOf() and charAt() function?
Ans.
indexOf() | charAt() |
---|---|
It returns the character at the specific index | Returns of the index within the this string (current string object) of the first occurrence of the specified character. |
Example: String s= new String(“SimplyCoding”); System.out.println(s.indexOf(‘m’)); Output: 2 | Example: String s= new String(“SimplyCoding”); System.out.println(s.charAt(6)); Output: C |
Q. 17 Describe equalsignorecase() method.
Ans. It compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and it represents an equivalent String ignoring case, else false.
Syntax: str2.equalsIgnoreCase(str1);
Q. 18 Write the output of the following:
(i) System.out.println (Character.isUpperCase(‘D’));
(ii) System.out.println(Character.toUpperCase(‘l’));
Ans.
(i) true
(ii) L
Q. 19 What is the use of substring()?
Ans. it 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.