×

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

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.