Character – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 05:45:35 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Character – Java2Blog https://java2blog.com 32 32 Get Unicode Value of Character in Java https://java2blog.com/get-unicode-value-of-character-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-unicode-value-of-character-java https://java2blog.com/get-unicode-value-of-character-java/#respond Mon, 07 Feb 2022 13:03:52 +0000 https://java2blog.com/?p=19227 In this post, we will see how to get unicode value of character in java.

Get Unicode Value of Character in Java

You can simply use below code to get unicode value of character in java.

private static String getUnicodeCharacterOfChar(char ch) {
    return String.format("\\u%04x", (int) ch);
}

Here is complete example to print unicode value of character in java:

package org.arpit.java2blog;

public class GetUnicodeCharacterOfCharMain {

    public static void main(String[] args) {

        String str="java2blog";
        String char1 = getUnicodeCharacterOfChar(str.charAt(3));
        System.out.println("Unicode value of character d: "+char1);

        String char2 = getUnicodeCharacterOfChar('क');
        System.out.println("Unicode value of character क: "+char2);
    }

    private static String getUnicodeCharacterOfChar(char ch) {
        return String.format("\\u%04x", (int) ch);
    }
}

Output

Unicode value of character d: \u0061
Unicode value of character क: \u0915

If source is not character but string, you must chatAt(index) to get unicode value of the character.

package org.arpit.java2blog;

public class GetUnicodeValueOfCharMain {

    public static void main(String[] args) {

        String str="java2blog";
        String char1 = getUnicodeCharacterOfChar(str.charAt(3));
        System.out.println("Unicode value of character d: "+char1);

    }

    private static String getUnicodeCharacterOfChar(char ch) {
        return String.format("\\u%04x", (int) ch);
    }
}

Output:

Unicode value of character d: \u0061

Get Unicode Character Code in Java

In java, char is a "16 bit integer", you can simply cast char to int and get code of unicode character.

char char1 = 'ज';
int code = (int) char1;

Here is definition of char from Oracle:

The char data type is a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).

Here is complete example:

package org.arpit.java2blog;

public class GetUnicodeCodeOfCharMain {

    public static void main(String[] args) {

        char char1 = '®';
        System.out.println(String.format("Unicode character code: %d", (int) char1));
        System.out.println(String.format("Unicode character code in hexa format: %x", (int) char1));
    }
}
Unicode character code: 174
Unicode character code in hexa format: ae

That’s all about how to get unicode value of character in java.

]]>
https://java2blog.com/get-unicode-value-of-character-java/feed/ 0
Convert Character to ASCII Numeric Value in Java https://java2blog.com/convert-character-to-ascii-numeric-value-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-character-to-ascii-numeric-value-java https://java2blog.com/convert-character-to-ascii-numeric-value-java/#respond Tue, 04 May 2021 14:39:53 +0000 https://java2blog.com/?p=14072 In this post, we will see How to convert Character to ASCII Numeric Value in Java.
There are multiple ways to convert Character to ASCII Numeric Value in Java

By casting char to int

You can simply get char from String using charAt() and cast it to int.
Here is an example:

package org.arpit.java2blog;

public class CharToASCIICast {
    public static void main(String[] args) {
        String s="Hello";

        char c=s.charAt(1);
        int asciiOfE=(int)c;
        System.out.println("Ascii value of e is: "+asciiOfE);
    }
}

Output:

Ascii value of e is: 101

You can even directly assign char to int, but it is good idea to explicitly cast it for readabiliy.
You can change highlighted code to below line and program will still work:

int asciiOfE = c;

Using toCharArray()

You can simply use index with toCharArray() to get ASCII value of character in the String.
Here is an example:

package org.arpit.java2blog;

public class CharToASCIICast {
    public static void main(String[] args) {
        String s="Hello";

        char c=s.toCharArray()[1];
        int asciiOfE=(int)c;
        System.out.println("Ascii value of e is: "+asciiOfE);
    }
}

Output:

Ascii value of e is: 101

Using String’s getBytes()

You can convert String to byte array using getBytes(StandardCharsets.US_ASCII) and this byte array will contain character’s ASCII values. You can access individual value by accessing byte array by index.
Here is an example:

package org.arpit.java2blog;

import java.nio.charset.StandardCharsets;

public class CharToASCIIGetBytes {
    public static void main(String[] args) {
        String str = "Hello";

        byte[] bytes = str.getBytes(StandardCharsets.US_ASCII);
        System.out.println("Ascii value of e is: "+bytes[1]);

        System.out.println("ASCII values for all characters are:");
        for(byte b:bytes)
        {
            System.out.print(b+" ");
        }
    }
}

Output:

Ascii value of e is: 101ASCII values for all characters are:72 101 108 108 111

Using String’s char() [Java 9+]

You can convert String to IntStream using String’s chars() method, use boxed() to convert it to Stream of wrapper type Integer and collect to the list. Result list will contain all the ascii value of the characters and you can use index to access individual ASCII value of character.
Here is an example:

package org.arpit.java2blog;

import java.util.List;
import java.util.stream.Collectors;

public class CharToASCIIUsingIntStream {
    public static void main(String[] args) {
        String str="Hello";

        List asciiIntegers = str.chars()
                .boxed()
                .collect(Collectors.toList());

        System.out.println("ASCII values for all characters are:");
        for(int i:asciiIntegers) {
            System.out.print(i+" ");
        }
    }
}

Output:

ASCII values for all characters are:72 101 108 108 111

Convert a String of letters to an int of corresponding ascii

If you want to convert entire String into concatenated ASCII value of int type, you can create StringBuilder from String’s ASCII values and convert it to BigInteger.
Here is an example:

package org.arpit.java2blog;

import java.math.BigInteger;

public class CharToASCIIInt {

    public static void main(String[] args) {
        String str="Hello";

        StringBuilder sb = new StringBuilder();
        for (char ch : str.toCharArray())
        {
            sb.append((int)ch);
        }

        BigInteger biAscii = new BigInteger(sb.toString());
        System.out.println(biAscii);
    }
}

Output:

72101108108111

That’s all about Convert Character to ASCII in Java

]]>
https://java2blog.com/convert-character-to-ascii-numeric-value-java/feed/ 0
How to compare characters in Java https://java2blog.com/compare-characters-java/?utm_source=rss&utm_medium=rss&utm_campaign=compare-characters-java https://java2blog.com/compare-characters-java/#respond Tue, 29 Sep 2020 18:53:21 +0000 https://java2blog.com/?p=10661 In this article, we are going to compare characters in Java.
Java provides some built-in methods such compare() and equals() to compare the character objects. Although, we can use less than or greater than operators but they work well with primitive values only.
Let’s take some examples to compare characters in Java.

Compare primitive chars

You can compare primitive chars either using Character.compare() method or <, > or = relational operators.

Using compare()

The compare() method of Characters class returns a numeric value positive, negative or zero.
See the example below.

class Main {

    public static void main(String[] args){

        char a = 'a';
        char b = 'b';
        if(Character.compare(a, b) > 0) {
            System.out.println("a is greater");
        }else if(Character.compare(a, b) < 0) {
            System.out.println("a is less than b");
        }else 
            System.out.println("Both are equal");
    }
}

Output

a is less than b

Using relation operators

We can use relational operators like less than or greater than to compare two characters in Java. It is simplest approach and does not involve any class or method.

class Main {

    public static void main(String[] args){

        char a = 'a';
        char b = 'b';
        if(a > b) {
            System.out.println("a is greater");
        }else if(a < b) {
            System.out.println("a is less than b");
        }else 
            System.out.println("Both are equal");
    }
}

Output

a is less than b

Compare Character objects

You can compare primitive chars either using Character.compare() method or equals() method.

Using compare()

You can use compare() method with Character objects as well. The compare() method of Characters class returns a numeric value positive, negative or zero.
See the example below.

class Main {

    public static void main(String[] args){

        Character ch1 = 'x';
        Character ch2 = 'y';
        if(Character.compare(ch1, ch2) > 0) {
            System.out.println("x is greater");
        }else if(Character.compare(ch1, ch2) < 0) {
            System.out.println("x is less than y");
        }else 
            System.out.println("Both are equal");
    }
}

Output

x is less than y

Using Equals()

The equals() method is used to check whether two char objects are equal or not. It returns true if both are equal else returns false.

class Main {

    public static void main(String[] args){

        Character a = 'a';
        Character b = 'b';

        if(a.equals(b)) {
            System.out.println("a is equals b");
        }else 
            System.out.println("a is not equal to b");
    }
}

Output

a is not equal to b

That’s all about How to compare characters in Java.

]]>
https://java2blog.com/compare-characters-java/feed/ 0
New line character in java https://java2blog.com/new-line-character-java/?utm_source=rss&utm_medium=rss&utm_campaign=new-line-character-java https://java2blog.com/new-line-character-java/#respond Mon, 16 Mar 2020 18:45:23 +0000 https://java2blog.com/?p=8826 In this post, we will see about new line character in java and how to add new line character to a String in different operating systems.
Operating systems have different characters to denote the end of the line.

Linux and new mac:
In Linux, the end line is denoted by \n, also known as line feed.

Window:
In windows, end line is denoted by \r\n, also known as Carriage return and line feed (CRLF)

Old mac:
In older version of mac, end line is denoted by \r, also known as Carriage return.

Using \n or \r\n

You can simply add \n in linux and \r\n in window to denote end of the line.

package org.arpit.java2blog.Java2blogPrograms;

public class EndLineCharacterMain {

    public static void main(String[] args)
    {
        // Should be used in Linux OS
        String str1 = "Hello"+ "\n" +"world";
        System.out.println(str1);

        // Should be used in Windows
        String str2 = "Hello"+ "\r\n" +"world";
        System.out.println(str2);
    }
}

Output:

Hello
world
Hello
world

You can use \n or \r\n but this method is not platform independent, so should not be used.

Using Platform independent line breaks (Recommended)

We can use System.lineSeparator() to separate line in java. It will work in all operating systems.

You can also use System.getProperty("line.separator") to put new line character in String.

Here is the quick snippet to demonstrate it.

package org.arpit.java2blog.Java2blogPrograms;

public class EndLineCharacterMain {

    public static void main(String[] args)
    {
        String str1 = "Hello"+ System.lineSeparator() +"world";
        System.out.println(str1);

        String str2 = "Hello"+ System.getProperty("line.separator") +"world";
        System.out.println(str2);
    }
}

Output:

Hello
world
Hello
world

As this method will work in all environment, we should use this method to add new line character in String in java.

That’s all about new line character in java.

]]>
https://java2blog.com/new-line-character-java/feed/ 0
Find Vowels in a String https://java2blog.com/java-program-print-vowels-string/?utm_source=rss&utm_medium=rss&utm_campaign=java-program-print-vowels-string https://java2blog.com/java-program-print-vowels-string/#respond Wed, 09 Oct 2019 18:03:13 +0000 https://java2blog.com/?p=5264 In this post, we will see how to find and count vowels in a string.

Find Vowels in a String

If any character in String satisfy below condition then it is vowel and we will add it to Hashset.

character==’a’ || character==’A’ || character==’e’ || character==’E’ ||
character==’i’ || character==’I’ || character==’o’ || character==’O’ ||
character==’u’ || character==’U’
package org.arpit.java2blog;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class VowelFinder
{
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an String : ");
        String str = scanner.next();

        Set<Character> set=new HashSet<Character>();
        for (int i = 0; i < str.length(); i++) {
            char c=str.charAt(i);
            if(isVowel(c))
            {
                set.add(c);
            }
        }

        System.out.println("Vowels are:");
        for (Character c:set) {
            System.out.print(" "+c);
        }

        scanner.close();
    }

    public static boolean isVowel(char character)
    {

        if(character=='a' || character=='A' || character=='e' || character=='E' ||
                character=='i' || character=='I' || character=='o' || character=='O' ||
                character=='u' || character=='U'){
            return true;
        }else{
            return false;
        }
    }

}

Output:

Enter an String : Java2blog
Vowels are:
a o

Explanation

  1. Iterate over String str and check each Character is vowel or not based on below condition
    if(character=='a' || character=='A' || character=='e' || character=='E' ||
                        character=='i' || character=='I' || character=='o' || character=='O' ||
                        character=='u' || character=='U')
  2. If it is vowel, then print the vowel

Count number of Vowels in the String

Here is the program to count number of Vowels in the String.

package org.arpit.java2blog;

import java.util.Scanner;

public class VowelCounter
{
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an String : ");
        String str = scanner.next();

        int countVowels = countVowels(str);
        System.out.println("Number of vowels: "+countVowels);
        scanner.close();
    }

    public static int countVowels(String str)
    {
        int count = 0;

        for (int i = 0; i < str.length(); i++) {
            char character =str.charAt(i);
            if(character=='a' || character=='A' || character=='e' || character=='E' ||
                    character=='i' || character=='I' || character=='o' || character=='O' ||
                    character=='u' || character=='U'){
                count++;
            }
        }
        return count;
    }
}

Output:

Enter an String : Java2blog
Number of vowels: 3

Explanation

  1. Declare count variable and initialize it with 0.
  2. Iterate over String str and check each Character is vowel or not based on below condition
    if(character=='a' || character=='A' || character=='e' || character=='E' ||
                        character=='i' || character=='I' || character=='o' || character=='O' ||
                        character=='u' || character=='U')
  3. If it is vowel, then increment the count
  4. Once loop is complete, then return the count.

That’s all about how to find vowels in a string in java.

]]>
https://java2blog.com/java-program-print-vowels-string/feed/ 0
Java remove last character from string https://java2blog.com/java-remove-last-character-from-string/?utm_source=rss&utm_medium=rss&utm_campaign=java-remove-last-character-from-string https://java2blog.com/java-remove-last-character-from-string/#respond Sun, 06 Oct 2019 16:44:39 +0000 https://java2blog.com/?p=7924 In this post, we will see how to remove last character from String in java.

There are many ways to do it. Let’s see each one by one.
]]> https://java2blog.com/java-remove-last-character-from-string/feed/ 0 Convert char to lowercase java https://java2blog.com/convert-char-to-lowercase-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-char-to-lowercase-java https://java2blog.com/convert-char-to-lowercase-java/#respond Sun, 06 Oct 2019 10:28:14 +0000 https://java2blog.com/?p=7871 You can use Character class’s toLowerCase method to convert char to lowercase in java.


Method signature

public static char toLowerCase(char ch)

Parameters

ch is primitive character type.


Return type

return type is char. If char is already lowercase then it will return same.

package org.arpit.java2blog;

public class JavaToLowercaseMain {

public static void main(String[] args) {

      System.out.println(Character.toLowerCase('a'));
      System.out.println(Character.toLowerCase('Y'));
      System.out.println(Character.toLowerCase('B'));
      System.out.println(Character.toLowerCase('Z'));

   }

}

When you run above program, you will get below output:

a
y
b
z

That’s all about how to convert char to lowercase in java.

]]>
https://java2blog.com/convert-char-to-lowercase-java/feed/ 0
Convert char to uppercase java https://java2blog.com/convert-char-to-uppercase-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-char-to-uppercase-java https://java2blog.com/convert-char-to-uppercase-java/#respond Sun, 06 Oct 2019 10:27:45 +0000 https://java2blog.com/?p=7874 You can use Charater class’s touppercase method to convert char to uppercase in java.


Method signature

public static char touppercase(char ch)

Parameters

ch is primitive character type.


Return type

return type is char. If char is already uppercase then it will return same.

package org.arpit.java2blog;

public class JavaToUpperCaseMain {

public static void main(String[] args) {

      System.out.println(Character.toUpperCase('a'));
      System.out.println(Character.toUpperCase('Y'));
      System.out.println(Character.toUpperCase('f'));
      System.out.println(Character.toUpperCase('u'));

   }

}

When you run above program, you will get below output:

A
Y
F
U

That’s all about how to convert char to uppercase in java.

]]>
https://java2blog.com/convert-char-to-uppercase-java/feed/ 0
Java isLetter method https://java2blog.com/java-isletter-method/?utm_source=rss&utm_medium=rss&utm_campaign=java-isletter-method https://java2blog.com/java-isletter-method/#respond Sun, 06 Oct 2019 10:18:15 +0000 https://java2blog.com/?p=7864 Character class’s isletter method can be used to check if character is letter or not.


Method signature

public static boolean isLetter(char ch):

Parameters

ch is primitive character type.


Return type

boolean is primitive character type.

package org.arpit.java2blog;

public class JavaIsLetterMain {

public static void main(String[] args) {

      System.out.println(Character.isLetter('a'));
      System.out.println(Character.isLetter('Y'));
      System.out.println(Character.isLetter('5'));
      System.out.println(Character.isLetter('&'));

   }

}

When you run above program, you will get below output:

true
true
false
false

That’s all about java Character’s isletter method.

]]>
https://java2blog.com/java-isletter-method/feed/ 0