Computer Applications
State the difference between == operator and equals() method.
Java String Handling
ICSE 2016
15 Likes
Answer
| equals() | == |
|---|---|
| It is a method | It is a relational operator |
| It is used to check if the contents of two strings are same or not | It is used to check if two variables refer to the same object in memory |
| Example: String s1 = new String("hello"); String s2 = new String("hello"); boolean res = s1.equals(s2); System.out.println(res); The output of this code snippet is true as contents of s1 and s2 are the same. | Example: String s1 = new String("hello"); String s2 = new String("hello"); boolean res = s1 == s2; System.out.println(res); The output of this code snippet is false as s1 and s2 point to different String objects. |
Answered By
7 Likes
Related Questions
The output of the statement "talent".compareTo("genius") is:
- 11
- ā11
- 0
- 13
Write a program in Java to enter any sentence. Also ask the user to enter a word. Print the number of times the word entered is present in the sentence. If the word is not present in the sentence, then print an appropriate message.
Which of the following returns a String?
- length()
- charAt(int)
- replace(char, char)
- indexOf(String)
The following code to compare two strings is compiled, the following syntax error was displayed ā incompatible types ā int cannot be converted to boolean.
Identify the statement which has the error and write the correct statement. Give the output of the program segment.
void calculate() { String a = "KING", b = "KINGDOM"; boolean x = a.compareTo(b); System.out.println(x); }