Compare Two String in Java Program

Java Code to Two given Compare Strings


In Java we can compare two strings using compareTo function on String class. Which can be done by using string1.compareTo(string2) if the return value is equal to zero then the given two strings are equal.The compareTo method is case sensitive one i.e "java" and "Java" are two different strings if you use compareTo method.
//source code CompareString.java

import java.util.*;

class CompareStrings{
public static void main(String args[]){
String s1, s2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
s1 = in.nextLine();//Getting string one input
System.out.println("Enter the second string");
s2 = in.nextLine();//Getting String two
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
}
}


Related Topic Java to Calculate Standard Deviation
Java Program to Calculate Mortgage Payments
Java String Comparison with case insensitive
How to Ping in java
Java code for Processing XML file
Java  

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback