| 1. |
What will be the output of following [2] String s1= “COMPUTER”; String s2= “competition”; System.out.println(s1.compareTo(s2)); System.out.println(s1.charAt(s2.length( ) –9) – s2.charAt(s2.indexOf(‘m’))); System.out.println(s1.substring(0,4).equalsIgnoreCase(s2.substring(0,4))); System.out.println(s1.compareToIgnoreCase(s2)); |
|
Answer» <U>Given : STRING s1= "COMPUTER"; String s2= "competition"; System.out.println(s1.compareTo(s2)); System.out.println(s1.charAt(s2.length() - (9)) - s2.charAt(s2.indexOf('m'))); System.out.println(s1.substring(0,4).equalsIgnoreCase(s2.substring(0,4))); System.out.println(s1.compareToIgnoreCase(s2)); Output : -32 -32 true 16 Explanation : s1 = C O M P U T E R 0 1 2 3 4 5 6 7 Length of s1 = 8 s2 = c o m p e t i t i o n 0 1 2 3 4 5 6 7 8 9 10 Length of s2 = 11 System.out.println(s1.compareTo(s2)); s1.compareTo(s2) : This will compare character by character. And also this function is case sensitive. So, when it will compare first alphabet : C and c ASCII value of C = 67 ASCII value of c = 99 67 - 99 = -32 So, output is -32. System.out.println(s1.charAt(s2.length() - (9))-s2.charAt(s2.indexOf('m'))); s2.length() : This will give the length of s2, i.e., 11 11 - 9 = 2 s1.charAt(2) = M So, from s1.charAt(s2.length() - (9)) ww will GET M. s2.indexOf('m') = 2 s2.charAt(2) = m M - m = 77 - 109 = -32 So, output is -32. System.out.println(s1.substring(0,4).equalsIgnoreCase(s2.substring(0,4)); s1.substring(0,4) = COMP s2.substring(0,4) = comp equalsIgnoreCase() : This is not case sensitive So, COMP = comp = true So, output is true. System.out.println(s1.compareToIgnoreCase(s2)); In case of C , c ⇒ 0 O , o ⇒ 0 M , m ⇒ 0 P , p ⇒ 0 U , e ⇒ 16 (compareToIgnoreCase() ignores the difference of upper and lower case. So, output is 16. |
|