×

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java

Char

The character is a data type with a name char. This data type only stores a single character inside it. The size of char data type is two bytes.

char data type ranges from value:

Zero to Sixty-five thousand five hundred and thirty-five (0 to 65535).

Char is also a primitive data type in Java.

Char can be used as how an int, float data types are used.

Input Statements for Char

We already know that we need to create an object for Scanner class to take inputs dynamically or during run time.

The input statement used for char is:

Syntax:

char variable_name = object_name.next().charAt(0);

Examples:

Scanner sc = new Scanner(System.in); // created for taking dynamic input
char c = sc.next().charAt(0);
char character = sc.next().charAt(0);

Note:

We can also create character arrays using char data type.
char c [ ] = new char[5];
Using the above input method we insert values into the character array.

Example:

File Name: Ch.java

Rules:

  1. All the class names must start with capital letter.
  2. The class name with main method should be the name of the program.
// A Java program learning about characters.
import java.util.*;
import java.io. *;
import java.lang. *;
class Ch
{
public static void main(String[] args)
 {
Scanner sc = new Scanner(System.in);
System.out.print("Give character input: ");
char c = sc.next().charAt(0);
System.out.println("The character is:"+c);


// A program for character array.


char ch[] = {'a','b','c','d'};
for(int i=0;i<4;i++)
{
System.out.println("The character at "+i+" is: "+ch[i]);
}



}
}

Output:

C:\new\java>java Ch
Give character input: h
The character is: h
The character at 0 is: a
The character at 1 is: b
The character at 2 is: c
The character at 3 is: d


C:\new\java>

This is how characters’ work in Java. Now let us see how characters are compared in java.

Using Relational Operators

Let us start from the basics on how to compare characters. While we started coding we always used relational operators for comparing any values. Even now as we are in beginning state, we are also going to use relational operators.

The relational operators are:

  • (==) equals to
  • (>) greater than
  • (<) less than
  • (> =) greater than or equals to
  • (< =) lesser than or equals to
  • (! =) not equals to

Let us explain this method using a program

Example:

File Name: Ch.java

// Character comparison.


import java.util.*;
import java.io. *;
import java.lang. *;


class Ch
{


public static void main(String[] args)
{


Scanner sc = new Scanner(System.in);
//Two character inputs are taken into consideration.
System.out.print("Give character 1 input:");


char c1 = sc.next().charAt(0);


System.out.print("Give character 2 input:");


char c2 = sc.next().charAt(0);


System.out.println("The character 1 is:"+c1);


System.out.println("The character 2 is:"+c2);


if(c2==c1)
{
System.out.println("EQUAL");
}
else if(c2>c1)
{
System.out.println("c2 is greater");
}


else if(c2<c1)
{
System.out.println("c1 is greater");
}



}
}

Output:

Output 1:

C:\new\java>java Ch
Give character1 input: k
Give character2 input: k
The character1 is: k
The character2 is: k
EQUAL


C:\new\java>

Output 2:

C:\new\java>javac Ch.java


C:\new\java>java Ch
Give character1 input: l
Give character2 input: m
The character1 is: l
The character2 is: m
c2 is greater


C:\new\java>

Output 3

C:\new\java>javac Ch.java


C:\new\java>java Ch
Give character1 input: z
Give character2 input: a
The character1 is: z
The character2 is: a
c1 is greater


C:\new\java> 

Compare Method

In Java there is an in-built method in character class known as compare method. This is used to compare the characters present in the program.

Syntax:

int variable_name = Character. compare (character 1, character 2);

Examples:

int comp = Character. compare (c1, c2);

Example:

// Character comaprison.


import java.util.*;
import java.io. *;
import java.lang. *;


class Ch
{


public static void main(String[] args)
{


Scanner sc = new Scanner(System.in);
//Two character inputs are taken into consideration.
System.out.print("Give character1 input:");


char c1 = sc.next().charAt(0);


System.out.print("Give character2 input:");


char c2 = sc.next().charAt(0);


System.out.println("The character1 is:"+c1);


System.out.println("The character2 is:"+c2);


int comp = Character.compare(c1,c2);
if(comp==0)
{
System.out.println("EQUAL");
}
else if(comp>0)
{
System.out.println("c1 is greater");
}


else if(comp<0)
{
System.out.println("c1 is greater");
}



}
}

Output:

Output 1:

C:\new\java>java Ch
Give character1 input: k
Give character2 input: k
The character1 is: s
The character2 is: s
EQUAL


C:\new\java>

Output 2:

C:\new\java>javac Ch.java


C:\new\java>java Ch
Give character1 input: l
Give character2 input: m
The character1 is: z
The character2 is: k
c2 is greater


C:\new\java>

Output 3

C:\new\java>javac Ch.java


C:\new\java>java Ch
Give character1 input: x
Give character2 input: b
The character1 is: z
The character2 is: a
c1 is greater

Explanation:

Comp =0 then characters are equal

Comp>0 then c1 is greater than c2

Comp<0 then c1 is less than c2

This is how characters are compared in Java.


Related Topics

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.