String methods – charAt() and compareTo()

I this post, we will discuss about string methods charAt() and compareTo().

Let’s discuss them one by one with examples.

charAt():

The method charAt(int index) returns the character at the specified index. Index should be between 0 and string length-1.

Note: Method throws IndexOutOfBoundsException if the index is less than zero or greater than equal to the length of the string.
public class ExampSubstring {
	public static void main(String[] args) {

		String val1 = "Hello World";
		System.out.println("Returns the character - "+val1.charAt(6)); // returns W
	}
}
Output: Returns the substring – W

 

 

compareTo():

The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison.

If both the strings are equal then this method returns number 0 else it will return positive or negative value.The result is positive if the first string is lexicographically greater than the second string else the result would be negative.

public class ExampCompareTo {
	public static void main(String[] args) {

		String val1 = "Hello World";
		String val2 = "Hello World";
		String val3 = "How are you?";
		String val4 = "How are you doing?";
				
		System.out.println("Compare val1 and val2  : "+val1.compareTo(val2)); 
		System.out.println("Compare val2 and val3  : "+val2.compareTo(val3)); 
		System.out.println("Compare val3 and val4  : "+val3.compareTo(val4)); 
	}
}
Output:
Compare val1 and val2 : 0
Compare val2 and val3 : -10
Compare val3 and val4 : 31

String compareToIgnoreCase():

It is similar to the method compareTo(). The only difference is it ignores the case like uppercase and lower case while comparing i.e. it is not case sensitive.

public class ExampCompareTo {
	public static void main(String[] args) {

		String val1 = "Hello World";  //String in lowercase
		String val2 = "HELLO WORLD";  //String in uppercase
		String val3 = "How are you?";
		String val4 = "How are you doing?";
				
		System.out.println("Compare val1 and val2  : "+val1.compareToIgnoreCase(val2)); 
		System.out.println("Compare val2 and val3  : "+val2.compareToIgnoreCase(val3)); 
		System.out.println("Compare val3 and val4  : "+val3.compareToIgnoreCase(val4)); 
	}
}
Output: Compare val1 and val2 : 0
Compare val2 and val3 : -10
Compare val3 and val4 : 31
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 7, 2015

    […] char charAt(int index) […]