String Manipulation

compareTo and equals methods

You can use the CompareTo(String) method to compare the invoking string with the string specified by the string argument. This function returns 0 if both strings are equal. It returns 1 if the invoking string is greater than the string specified by the string argument, otherwise it returns -1. Another method to compare strings in Java is equals(String) method. This method return true if both strings are equals, otherwise it return false.

Example:



import java.io.*;

public class JavaExercises
{
public static void main(String[] args)
{
selectChoice();
}

static void selectChoice(){

String choice;
String con="y";
try{
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   System.out.println("What is the command keyword to exit a loop in Java?");
   System.out.println("a.quit");
   System.out.println("b.continue");
   System.out.println("c.break");
   System.out.println("d.exit");


while (con.compareTo("y")==0)
{

  System.out.print("Enter your choice:");
  choice =br.readLine();

if (choice.compareTo("c")==0)
{
  System.out.println("Congratulation!");
}
else if (choice.compareTo("q")==0 || choice.compareTo("e")==0) {      System.out.println("Exiting...!"); break; }
else System.out.println("Incorrect!");

System.out.print("Again? press y to continue:");
con =br.readLine();
}

}catch(IOException e){}


  }

}

The example code above can be rewritten as shown below:


import java.io.*;

public class JavaExercises
{
public static void main(String[] args)
{
selectChoice();
}

static void selectChoice(){

  String choice;
  String con="y";
try{
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  System.out.println("What is the command keyword to exit a loop in Java?");
  System.out.println("a.quit");
  System.out.println("b.continue");
  System.out.println("c.break");
  System.out.println("d.exit");


while (con.equals("y"))
{

  System.out.print("Enter your choice:");
  choice =br.readLine();

if (choice.equals("c"))
{
  System.out.println("Congratulation!");
}
else if (choice.equals("q") || choice.equals("e")) { System.out.println("Exiting...!"); break; }
else System.out.println("Incorrect!");

System.out.print("Again? press y to continue:");
con =br.readLine();
}

}catch(IOException e){}


}

}



HTML Comment Box is loading comments...



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.