Character Comparison Example

In this section, you will learn how to compare characters in Java. The java.lang package provides a method for comparing two case sensitive strings.

Character Comparison Example

In this section, you will learn how to compare characters in Java. The java.lang package provides a method for comparing two case sensitive strings.

Character Comparison Example

Character Comparison Example

     

In this section, you will learn how to compare characters in Java. The java.lang package provides a method for comparing two case sensitive  strings. The compareTo() method compares two strings on the basis of Unicode of each character of the given strings. This method returns integer type value. If it will return '0' it means the given string is equal otherwise not equal.

Description of program:

This program helps you to compare characters with cases and sequence. For comparing the string you will need those string that have to be compared. Here the CharComp() method is applied for comparing the string. At the time of defining, you will use the compareTo() method that compares both strings and shows an appropriate given message.

Description of code:

compareTo(String str):
Above method is used to compare two strings with its cases. If it returns '0', an argument of the given string is equal otherwise not. It takes string type parameter as following:

str: This is the string that have to be compared. 

Here is the code of program:

import java.lang.*;

public class CharComparation{
  public static void main(String[] args) {
  System.out.println("Character comparation example!");
  String str1 = "Vinod";
  String str2 = "Vinod";
  String str3 = "vinod";
  CharComp(str1, str2, str3);
  }
  public static void CharComp(String str1, String str2, String str3){
  System.out.println("String1 = " + str1);
  System.out.println("String2 = " + str2);
  System.out.println("String2 = " + str3);
  if(str1.compareTo(str2== 0){
  System.out.println("String1 and String2 are equal!");
  }
  else{
  System.out.println("String1 and String2 are not equal!");
  }
  if(str1.compareTo(str3== 0){
  System.out.println("String1 and String3 are equal!");
  }
  else{
  System.out.println("String1 and String3 are not equal!");
  }
  if(str2.compareTo(str3== 0){
  System.out.println("String2 and String3 are equal!");
  }
  else{
  System.out.println("String2 and String3 are not equal!");
  }
  }
}

Download this example.

Output of program:

C:\vinod\Math_package>javac CharComparation.java

C:\vinod\Math_package>java CharComparation
Character comparation example!
String1 = Vinod
String2 = Vinod
String2 = vinod
String1 and String2 are equal!
String1 and String3 are not equal!
String2 and String3 are not equal!