Results 1 to 3 of 3
  1. #1
    kurtulas is offline Member
    Join Date
    Feb 2008
    Posts
    2
    Rep Power
    0

    Default Casting an int value into a char

    Hi all;
    This is my first post here. Been working with java for over a year now so im pretty new but ill help others where i can. Here is my first question.
    I have a method that creates a random number (so the number is never known until the method runs), i have been trying for days to cast this number into a char. I have written various ways but after succesful compiling i still get a number rather than a char. Any help please???

  2. #2
    Leprechaun is offline Member
    Join Date
    Dec 2007
    Posts
    30
    Rep Power
    0

    Default

    I don't know if you can directly cast an int to a char but, if the range of your numbers is small, you could just use a switch statement and another method to get the char you want... like this:
    switch (x) { //x is the int
    case 1: return ('a');
    case 2: return ('b');
    }
    Last edited by Leprechaun; 02-16-2008 at 06:32 PM. Reason: Add {} to the code for the switch statement

  3. #3
    jimm1 is offline Member
    Join Date
    Jan 2008
    Location
    South Africa
    Posts
    18
    Rep Power
    0

    Default

    Its very easy:
    char c = 112; (Or whatever number you want)

    OR

    char c = (char)112;

    System.out.println(c);

    The output will be 'p';

Similar Threads

  1. Type Casting Help
    By rhm54 in forum New To Java
    Replies: 2
    Last Post: 02-07-2008, 01:06 PM
  2. 'Casting' couch !!!!
    By ajaygargnsit in forum Advanced Java
    Replies: 4
    Last Post: 01-04-2008, 05:54 PM
  3. 'Casting' couch !!
    By ajaygargnsit in forum New To Java
    Replies: 1
    Last Post: 12-22-2007, 02:05 PM
  4. Casting
    By leebee in forum New To Java
    Replies: 5
    Last Post: 08-10-2007, 01:24 PM
  5. Help with, String, Char
    By lenny in forum New To Java
    Replies: 1
    Last Post: 07-25-2007, 03:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •