Java char to number one

4 ways to convert char to int in Java [Practical Examples]

In Java, the char and an int are a primitive data types. In real life applications, many times we will need to convert the value of one type to the other type. So, Java provides the mechanism for this conversion. As we know, the char type in java can hold a single character whereas an int type holds the numbers without decimal. Here, we will see several ways to convert a char to its equivalent int.

  • Using ASCII Values
  • Using Integer.parseInt() method
  • Using Character.getNumericValue() method
  • Subtracting ‘0’

Using ASCII Values

This is the simplest approach to convert char to int in Java. Here, there are two ways to accomplish this task. The first way is through an implicit type conversion, where we assign the value of char variable to int variable. So, it stores the equivalent ASCII value in int type. The other way is explicit type conversion, where we do not use int variable but we write a int in the bracket for type conversion.

Example : In this example, we are showing both implicit and explicit type conversions.

// Program to convert char to int public class Main < public static void main(String[] args) < // Initializing the variables char a = '1'; char b = '2'; // Implicit type conversion int a1 = a; int b1 = b; System.out.println("The ASCII value of " + a + " is " + a1); System.out.println("The ASCII value of " + b + " is " + b1); // Explicit type conversion a = '5'; b = '6'; System.out.println("The ASCII value of " + a + " is " + (int) a); System.out.println("The ASCII value of " + b + " is " + (int) b); >>
The ASCII value of 1 is 49 The ASCII value of 2 is 50 The ASCII value of 5 is 53 The ASCII value of 6 is 54

Using Integer.parseInt() method

In this approach, we are using the static method parseInt of Integer wrapper class. It takes one parameter of string type and converts it to integer. So, we would need to convert char to string in order to use parseInt function.

Example : In this example, char variables are converted to int using parseInt method and valueOf method.

// Program to convert char to int in Java public class Main < public static void main(String[] args) < // Initializing the variables char c = '9'; char d = '5'; // Converting char to int and printing int i = Integer.parseInt(String.valueOf(c)); System.out.println("Converting char to int : " + i); i = Integer.parseInt(String.valueOf(d)); System.out.println("Converting char to int : " + i); >>
Converting char to int : 9 Converting char to int : 5

Using Character.getNumericValue() method

In this approach, we will use getNumericValue() method which is a static method of Character wrapper class. This method returns an equivalent int value that the specified Unicode character represents.

Читайте также:  Python any lambda example

Example : In this example, char variables are converted to int using getNumericValue method of Character class.

Converting character to int : 9 Converting character to int : 5

Subtracting ‘0’

In this approach, we are simply subtracting the character ‘0’ from the other character. That means, if we subtract ‘0’ (ASCII equivalent 48) from any character let’s say ‘2’ (ASCII equivalent 50), we will get 2 as a result. Which means, ‘2’-‘0’=2.

Example : In this example, char variables are converted to int by subtracting character ‘0’ from the other character.

Converting character to int : 9 Converting character to int : 5

Examples Showing conversion of char to int

Example 1 : Evaluating expression stored in String

In this example, we are evaluating the expression stored in the string after converting the numbers to equivalent int value.

public class Main < public static void main(String[] args) < // Initializing the variables String e = "2+3"; char c; int first = 0, second = 0, result; // Iterating over the string for (int i = 0; i < e.length(); i++) < c = e.charAt(i); if (c >= '0' && c else < result = first + second; System.out.println("Result of Expression " + e + " is " + result); break; >> > >
Result of Expression 2+3 is 5

Example 2 : Find the summation of numbers stored in the String

In this example, we are finding the summation of the numbers after converting the numbers to equivalent int value.

Summation of the numbers 3455 is 17

Example 3 : Find the product of numbers stored in the String

In this example, we are finding the product of the numbers after converting the numbers to equivalent int value.

Product of the numbers 1248 is 64

Example 4 : Convert the multi digit numbers stored in String to int

In this example, we are converting the multi digit number stored in the string to its equivalent int value.

public class Main < public static void main(String[] args) < // Initializing the variables String s = "4588"; char c; int i, num = 0, multiplier = 1; for (i = s.length() - 1; i >= 0; i--) < // Getting a character from the string c = s.charAt(i); // Converting character to int and multiplying with multiplier num = num + (Integer.parseInt(String.valueOf(c)) * multiplier); // Printing the intermediate values System.out.println("character is " + c); System.out.println("\n Now the number is " + num); // reset the multiplier multiplier = multiplier * 10; >// Printing the result System.out.println("Equivalent number is " + num); > >
character is 8 Now the number is 8 character is 8 Now the number is 88 character is 5 Now the number is 588 character is 4 Now the number is 4588 Equivalent number is 4588

Summary

The knowledge of converting char value to a int in Java is very useful while working on real time applications. In this tutorial, we covered four different approaches to convert char to int in Java. As per the requirement of an application, we can choose an appropriate approach for conversion. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on conversion of char value to a int value in Java.

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Читайте также:  Java spring beans scope

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Java Tutorial

  • Set Up Java Environment
    • Set Up Java on Linux
    • Set up Java with BlueJ IDE
    • Set up Java with VSC IDE
    • Set up Java with Eclipse IDE
    • Java Multiline Comments
    • Java Variables
    • Java Global Variables
    • Java Date & Time Format
    • Different Java Data Types
    • Java Booleans
    • Java Strings
    • Java Array
    • Java Byte
    • Java convert list to map
    • Java convert double to string
    • Java convert String to Date
    • Java convert Set to List
    • Java convert char to int
    • Java convert long to string
    • Java Operators Introduction
    • Java Boolean Operators
    • Java Relational Operators
    • Java Arithmetic Operators
    • Java Bitwise Operators
    • Java Unary Operators
    • Java Logical Operators
    • Java XOR (^) Operator
    • Java Switch Statement
    • Java If Else Statement
    • Java While Loop
    • Java For / For Each Loop
    • Java Break Continue
    • Java Nested Loops
    • Java throw exception
    • Java Try Catch
    • Java Accessor and Mutator Methods
    • Java main() Method
    • IndexOf() Java Method
    • Java ListIterator() Method
    • Java create & write to file
    • Java read file
    • Java Parameter
    • Java Argument
    • Java Optional Parameters
    • Java Arguments vs Parameters
    • Java Arrays.asList
    • Java HashSet
    • Java Math
    • Java HashMap vs Hashtable vs HashSet
    • Java LinkedList
    • Linked List Cycle
    • Java List vs LinkedList
    • Java ArrayList vs LinkedList

    Источник

    Java char to number one

    2) Java char to int Example: Character.getNumericValue()

    Let’s see the simple code to convert char to int in java using Character.getNumericValue(char) method which returns an integer value.

    3) Java char to int Example: String.valueOf()

    Let’s see another example which returns integer value of specified char value using String.valueOf(char) method.

    Youtube

    For Videos Join Our Youtube Channel: Join Now

    Feedback

    Help Others, Please Share

    facebook twitter pinterest

    Learn Latest Tutorials

    Splunk tutorial

    SPSS tutorial

    Swagger tutorial

    T-SQL tutorial

    Tumblr tutorial

    React tutorial

    Regex tutorial

    Reinforcement learning tutorial

    R Programming tutorial

    RxJS tutorial

    React Native tutorial

    Python Design Patterns

    Python Pillow tutorial

    Python Turtle tutorial

    Keras tutorial

    Preparation

    Aptitude

    Logical Reasoning

    Verbal Ability

    Company Interview Questions

    Artificial Intelligence

    AWS Tutorial

    Selenium tutorial

    Cloud Computing

    Hadoop tutorial

    ReactJS Tutorial

    Data Science Tutorial

    Angular 7 Tutorial

    Blockchain Tutorial

    Git Tutorial

    Machine Learning Tutorial

    DevOps Tutorial

    B.Tech / MCA

    DBMS tutorial

    Data Structures tutorial

    DAA tutorial

    Operating System

    Computer Network tutorial

    Compiler Design tutorial

    Computer Organization and Architecture

    Discrete Mathematics Tutorial

    Ethical Hacking

    Computer Graphics Tutorial

    Software Engineering

    html tutorial

    Cyber Security tutorial

    Automata Tutorial

    C Language tutorial

    C++ tutorial

    Java tutorial

    .Net Framework tutorial

    Python tutorial

    List of Programs

    Control Systems tutorial

    Data Mining Tutorial

    Data Warehouse Tutorial

    Javatpoint Services

    JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

    • Website Designing
    • Website Development
    • Java Development
    • PHP Development
    • WordPress
    • Graphic Designing
    • Logo
    • Digital Marketing
    • On Page and Off Page SEO
    • PPC
    • Content Development
    • Corporate Training
    • Classroom and Online Training
    • Data Entry

    Training For College Campus

    JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
    Duration: 1 week to 2 week

    Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

    Источник

    Char to Int in Java

    Java Course - Mastering the Fundamentals

    There are different ways to convert a character to its corresponding integer representation.

    • Assigning a character to an integer-type variable gives the ASCII value of the character.
    • Use Character.getNumericValue() method
    • Convert the character to a String using String.valueOf() method and use Integer.parseInt() method.
    • Subtract ‘0’ from the character.

    How to convert char to int in Java?

    Sometimes we need to perform operations on integer values, here in this case it may be possible that the int value is stored in a char data type. In this situation, we first need to convert the char value to its corresponding integer value and then do the required operation.

    The primitive data type can be converted from char to int data type in java using several ways:-

    1. Using ASCII values: We can automatically convert a character to its ASCII value by using implicit typecasting.
    2. Character.getNumericValue(): We can convert char to int using getNumericValue() method of the Character class.
    3. Using parseInt() method with String.valueOf(): We can convert char to int in java by converting char to string using String.valueOf() and then converting string to int using Integer.parseInt() method.
    4. Subtracting with ‘0’: we can convert char to int by subtracting with 0 , this works on the concept of ASCII values.

    Method 1: Using ASCII values

    American Standard Code for Information Interchange is an encoding format used to store characters on a computer, it is a 7 — bit character set containing 128 characters.

    In Java programming language we have implicit typecasting, i.e if we store the value of a smaller datatype to a variable of the larger datatype, then the value is automatically converted. This means that the variable is implicitly typecasted into a larger datatype variable.

    Explanation:

    • So in this example variable first is implicitly typecasted to int datatype and then stored in second variable.
    • So now if we print the second variable it will print 53 . This is because we have assigned the char variable first to the int variable second and we get the ASCII value of 5 i.e. 53.

    Example: 53-48 = 5

    Below is the java program to convert char to int in java using the ASCII value:-

    Method 2: Using Character.getNumericValue()

    In Java, we have a method getNumericValue() inside the Character class. This method returns an int value which is the encoding of a Unicode character.

    This method takes an argument of char datatype and returns the corresponding int value.

    Method 3: parseInt() method with String.valueOf()

    In java we can also convert from char to int java using the parseInt() and String.valueOf() methods.

    • The String.valueOf(): method converts a char datatype variable into a string datatype variable and,
    • Integer.parseInt(): method is used to convert string into an int datatype.

    The method valueOf() belongs to String class and parseInt() method belongs to Integer class.

    Explanation:

    • Here in this example, ch1 is first converted to string using String.valueOf() and then it is converted to int using Integer.parseInt() .
    • Similar operations are performed with ch2 character as well.

    Method 4: Subtraction with ‘0’:

    In Java we can also convert the numeric value stored in a char to int datatype by subtracting it with the character 0 (zero). This is based on the concept of ASCII values.

    If we want to convert char to int, we will subtract ‘0’ from the character.

    • In the code above, ch1 which is equal to ‘5’ has an ASCII value of 53 .
    • And ASCII value of 0 is 48 so if we subtract 48 from 53 we get 5 which is the int value of num1.
    • So in background implicit type casting is being done and the we subtract it from ASCII value of 0 and hence getting the conversion from char to int.
    • Similar operations are performed in case of ch2 as well.

    Conclusion:

    1. In this article, we discussed different methods to convert char to int in java.
    2. These methods are:
      • Using ASCII values
      • Character.getNumericValue()
      • char to int using parseInt() method with String.valueOf()
      • char to int by subtracting with 0
    3. When a character is subtracted from another character, internal typecasting is performed to convert the characters to their corresponding ASCII numbers. The result is the subtraction between their ASCII values.

    Источник

Оцените статью