Create User-defined Example
Create a new Java class named UserDefined
inside the JavaCharEquals
folder.
The program will use a Scanner
object to allow the user to input two characters. The equals()
method will then be used to compare the two characters and output whether they are the same or different. Use the following code:
import java.util.Scanner;
public class UserDefined {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first character: ");
Character ch1 = sc.next().charAt(0);
System.out.print("Enter second character: ");
Character ch2 = sc.next().charAt(0);
boolean isEqual = ch1.equals(ch2);
if (isEqual) {
System.out.println("Same characters entered");
} else {
System.out.println("Different characters entered");
}
} catch (Exception e) {
System.out.println("Invalid input! Please check.");
}
}
}
Save the changes and compile the code using the following command:
javac UserDefined.java
Run the program using the following command:
java UserDefined
You should see the following output:
Enter first character: m
Enter second character: m
Same characters entered
You can test the program with different values for ch1 and ch2.