Thursday 26 March 2020

Convert a char to integer

Approach 1: Using Character.getNumericValue method.
int number1 = Character.getNumericValue(ch);

Approach 2: Subtract the character '0' from given character.
int number2 = (ch - '0');

Approach 3: Subtract 48 (It is the unicode value for 0) from given character.
int number3 = (ch - 48);

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  char ch = '3';

  int number1 = Character.getNumericValue(ch);

  int number2 = (ch - '0');
  
  int number3 = (ch - 48);
  
  System.out.println("number1 : " + number1);
  System.out.println("number2 : " + number2);
  System.out.println("number3 : " + number3);

 }

}

Output
number1 : 3
number2 : 3
number3 : 3



You may like

No comments:

Post a Comment