Two methods for converting char to int in Java __java

Source: Internet
Author: User

Today, there was a problem with the machine test: How to turn char ' 9 ' to int 9, you should know that you can't convert directly, so you get the ASCII of ' 9 '. As below:

public class Intandcharconvertor {public
	static void Main (string[] args) {
		char NumChar = ' 9 ';
		int  intnum = (int) NumChar;
 		System.out.println (NumChar + ":" + Intnum);
	}


Run Result:

9:57
So how do you convert char ' 9 ' to int 9?

Method One: First convert char to char[1] array, then convert to string, and finally, using the Parserint method in integer, this method consumes a lot of memory to create multiple objects.

Method Two: Using the encapsulation class character of Char, it can be realized directly through the static method.

    public static int Getnumericvalue (CHAR-ch) {return
        getnumericvalue (int) ch);
    }

Example:
Package Com.albertshao.interview;

public class Intandcharconvertor {public
	static void Main (string[] args) {
		char NumChar = ' 9 ';
		int  intnum = (int) NumChar;
		System.out.println (NumChar + ":" + intnum);
		
		Method 1:
		char[] Chararray = {NumChar};
		Intnum = Integer.parseint (new String (Chararray));
		System.out.println ("Method 1:" + NumChar + ":" + intnum);
		
		Method 2:
		System.out.println ("Method 2:" + NumChar + ":" + character.getnumericvalue (NumChar));

		}
	
Run results

9:57 method
1:9:9 method
2:9:9



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.