Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 308
  • Last Modified:

char and int conversions...

I need to do the following:

I have an integer with a value, and for this example we'll use 65.

Now, I want to convert that value to the character 65 or "A".

In C, I can use:
   int temp1=65;
   char temp2;

   temp2=temp1;

and boom, I have temp2 == 'A'

However, in Java I can't do that.  I can do:
  int temp1;
  char temp2='A';
 
  temp1=temp2;

and instantly temp1=65, but I can't go the other way.  Is there a way to do this?

Thank you.
0
zathael
Asked:
zathael
1 Solution
 
webster030697Commented:
Unlike C, Java is strongly typed (thankfully). To do what you want, you must expliciltly cast the data type:

import java.io.*;

public class TestChar
{
      
      public static void main(String Args[])
      {      int theInt = 65;
            char theChar;
            theChar = (char) theInt;
            System.out.println("theInt = " + theInt + "\n");
            System.out.println("theChar = " + theChar);
      }
      
}

produces the output:

theInt = 65

theChar = A

Why you would want to do this is another question. Strong typing is one of the great features of Java - you can't just go juxtaposing data types willy-nilly, causing all sorts of confusion in the process.
0
 
zathaelAuthor Commented:
The reason I needed to do this is there are certain c routines that I'm taking to Java, certain functions that I find useful in my projects that work great in C, and now I need in Java.  One such function required this.  For the most part I can work around them, but rather than add 10 lines of code to do the same thing, I thought there might be a better way to take it to one line of code. Thank you for your answer.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now