Java set int to char

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is called an explicit conversion. There are two methods to convert int to char:

Using typecast operator

Casting is when we explicitly convert from one primitive data type, or a class, to another.

In this example, we have initialized 65 to the variable a. 65 is the ASCII value of A. We cast the number from an integer to char, converting it to the letter A.

public class inTocharExample < public static void main(String args[]) < int a=65; char ch=(char)a; System.out.println("The character value of an integer is: "+ch); >>
The character value of an integer is: A

Remember: If you are assigning 1 to a variable and want to convert it into character, then nothing will be print on the console. Because it will store ASCII value of 1 that is SOH (start of heading) which is a non-printable character.

In the following example, we have done the same as above mentioned. We have initialized 1 to the variable i of type int. In the next statement, we performed casting. In the println statement, we are trying to print the converted value of 1, but it will not print the character ch.

public class inTocharExample1 < public static void main(String args[]) < int i=1; char ch=(char)i; System.out.println("Nothing will be print "+ch); >>

To remove the above problem, we will add ‘0’ (as a character not as a digit) to the integer i during casting. It returns the actual value in the character form. The ASCII value of ‘0’ is 48. When we add 48 to 1, it becomes 49, which is the ASCII value of 1.

public class inTocharExample2 < public static void main(String args[]) < int i=1; char ch=(char)(i+'0'); System.out.println("Character value is: " +ch); >>

When we initialize ‘1’ as a character to the variable i of type int, it will store actual character in ch variable and print the same.

public class inTocharExample3 < public static void main(String args[]) < int i='1'; char ch=(char)i; System.out.println("Character value is: " +ch); >>

Using forDigit() method

forDigit() is a built-in static method of Character class which belongs to java.lang package. It parses two arguments digit and radix and returns the character representation of digit in specified radix format. It returns null if the digit or radix are invalid numbers. The signature of the method is given below.

public static char forDigit(int digit, int radix)

Invalid conversions

The following conversions returns null.

char ch2=Character.forDigit(3,2); //Binary radix

char ch2=Character.forDigit(9,8); //Octal radix

char ch2=Character.forDigit(10,10); //decimal radix

char ch2=Character.forDigit(16,16); //Hexa radix

Valid Conversions

char ch2=Character.forDigit(15,16); //returns f because decimal value of f is 15

We can conclude from the above conversions that digit must be less than the radix.

public class inTocharExample4 < public static void main(String args[]) < char ch1=Character.forDigit(9,10); //Octal radix format char ch2=Character.forDigit(11,16); //Hexa radix format System.out.println("9 representations in radix 10 format: "+ch1); System.out.println("11 representations in radix 16 format: "+ch2); >>
9 representations in radix 10 format: 9 11 representations in radix 16 format: b

Источник

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is called an explicit conversion. There are two methods to convert int to char:

Using typecast operator

Casting is when we explicitly convert from one primitive data type, or a class, to another.

In this example, we have initialized 65 to the variable a. 65 is the ASCII value of A. We cast the number from an integer to char, converting it to the letter A.

public class inTocharExample < public static void main(String args[]) < int a=65; char ch=(char)a; System.out.println("The character value of an integer is: "+ch); >>
The character value of an integer is: A

Remember: If you are assigning 1 to a variable and want to convert it into character, then nothing will be print on the console. Because it will store ASCII value of 1 that is SOH (start of heading) which is a non-printable character.

In the following example, we have done the same as above mentioned. We have initialized 1 to the variable i of type int. In the next statement, we performed casting. In the println statement, we are trying to print the converted value of 1, but it will not print the character ch.

public class inTocharExample1 < public static void main(String args[]) < int i=1; char ch=(char)i; System.out.println("Nothing will be print "+ch); >>

To remove the above problem, we will add ‘0’ (as a character not as a digit) to the integer i during casting. It returns the actual value in the character form. The ASCII value of ‘0’ is 48. When we add 48 to 1, it becomes 49, which is the ASCII value of 1.

public class inTocharExample2 < public static void main(String args[]) < int i=1; char ch=(char)(i+'0'); System.out.println("Character value is: " +ch); >>

When we initialize ‘1’ as a character to the variable i of type int, it will store actual character in ch variable and print the same.

public class inTocharExample3 < public static void main(String args[]) < int i='1'; char ch=(char)i; System.out.println("Character value is: " +ch); >>

Using forDigit() method

forDigit() is a built-in static method of Character class which belongs to java.lang package. It parses two arguments digit and radix and returns the character representation of digit in specified radix format. It returns null if the digit or radix are invalid numbers. The signature of the method is given below.

public static char forDigit(int digit, int radix)

Invalid conversions

The following conversions returns null.

char ch2=Character.forDigit(3,2); //Binary radix

char ch2=Character.forDigit(9,8); //Octal radix

char ch2=Character.forDigit(10,10); //decimal radix

char ch2=Character.forDigit(16,16); //Hexa radix

Valid Conversions

char ch2=Character.forDigit(15,16); //returns f because decimal value of f is 15

We can conclude from the above conversions that digit must be less than the radix.

public class inTocharExample4 < public static void main(String args[]) < char ch1=Character.forDigit(9,10); //Octal radix format char ch2=Character.forDigit(11,16); //Hexa radix format System.out.println("9 representations in radix 10 format: "+ch1); System.out.println("11 representations in radix 16 format: "+ch2); >>
9 representations in radix 10 format: 9 11 representations in radix 16 format: b

Источник

Convert Between int and char in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll see how to convert from int to char and back in Java.

2. char in Java

We’ll briefly discuss how characters are represented in order to better understand the code we’ll see later in the article.

Internally, Java stores each char as a 16-bit Unicode encoded value:

Character 2 Bytes Decimal (base 10) Hex (base 16)
A 00000000 01000001 65 41
a 00000000 01100001 61 97
1 00000000 00110001 49 31
Z 00000000 01011010 90 5A

We can easily check this by casting the char value to int:

ASCII code is a subset of the Unicode encoding, representing mostly the English alphabet.

3. Converting int to char

Let’s say we have an int variable with value 7 and we want to convert it to its char counterpart ‘7‘. We have a few options to do this.

Simply casting it to char won’t work because this converts it to the character that’s represented in binary as 0111, which in UTF-16 is U+0007 or the character ‘BELL’.

3.1. Offsetting by ‘0′

The characters in UTF-16 are represented in sequential order. So we can just offset the ‘0‘ character by 7 to get the ‘7‘ character:

@Test public void givenAnInt_whenAdding0_thenExpectedCharType()

3.2. Using the Character.forDigit() Method

Adding ‘0‘ works, but it seems a bit hackish. Luckily, we have a much cleaner way to do it using the Character.forDigit() method:

@Test public void givenAnInt_whenUsingForDigit_thenExpectedCharType()

We can notice that the forDigit() method accepts a second argument, radix, which represents the base representation of the number we want to convert. In our case, it’s 10.

3.3. Using the Integer.toString() Method

We can use the wrapper class Integer, which has the toString() method that converts the given int to its String representation. Of course, this can be used to convert a number with multiple digits to String. But, we can also use it to convert a single digit to char by chaining the charAt() method and picking the first char:

@Test public void givenAnInt_whenUsingToString_thenExpectedCharType()

4. Converting char to int

Previously, we saw how to convert an int to char. Let’s see how we can get the int value of a char. As we probably expect, casting the char to int won’t work, as this gives us the decimal representation of the UTF-16 encoding of the character:

@Test public void givenAChar_whenCastingFromCharToInt_thenExpectedUnicodeRepresentation()

4.1. Subtracting ‘0′

If when we add ‘0′ we get the char, then conversely by subtracting the ‘0′ decimal value, we should get the int:

@Test public void givenAChar_whenSubtracting0_thenExpectedNumericType()

This indeed works, but there are better and simpler ways to do it.

4.2. Using the Character.getNumericValue() Method

The Character class again provides another helper method, getNumericValue(), which basically does what it says:

@Test public void givenAChar_whenUsingGetNumericValue_thenExpectedNumericType()

4.3. Using Integer.parseInt()

We can use Integer.parseInt() to convert a String to a numeric representation. Just as before, while we can use this to convert an entire number with multiple digits to the int representation, we can also use it for a single digit:

@Test public void givenAChar_whenUsingParseInt_thenExpectedNumericType()

Indeed, the syntax is a bit cumbersome, mostly because it involves multiple conversions, but it works as expected.

5. Conclusion

In this article, we learned how characters are internally represented in Java and how we can convert an int to char and back.

As always, the complete code samples for this article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Читайте также:  Java нет всплывающих окон
Оцените статью