user2101421
user2101421

Reputation: 17

Intro Java - How does the use of char work? letter assigned by random number?

I am completely perplexed by this char scenario. I understand that in java if you using a single character you use char. I understand math.random but I have no idea how the random number is assigned a uppercase letter?

The way I read this is: print -> type case char primitive type -> the letter "A" -> concatenate a random number up to 27...

but this code works How?

public class question {
  public static void main(String[] args) {
    System.out.println((char)('A' + Math.random() * 27));
  }
}

Upvotes: 1

Views: 3524

Answers (4)

MinGW
MinGW

Reputation: 87

public class question {
  public static void main(String[] args) {
    System.out.println('A' + 1); //The result is 66.
    System.out.println('B' + 1); //The result is 67.
    System.out.println('C' + 1); //The result is 68.
    System.out.println('A' + 100); //The result is 165.
  }
}

Upvotes: 0

Robin Krahl
Robin Krahl

Reputation: 5308

If you convert an int to a char, the integer value is used as the index of the character in the ASCII table. So this code uses the ASCII code of an uppercase A (65) and adds 0 to 25 to it to get an character from A to Z.

As @ruakh said in the comments, you should add values in the range [0, 25] to A to get the characters from A to Z. Therefore use Math.random() * 26 instead of Math.random() * 27.

Upvotes: 1

Christian Ternus
Christian Ternus

Reputation: 8492

A char can be treated as an integer for a number of purposes -- e.g. A is 65 (in ASCII and Unicode). When you add that to a random number between 0 and 25 and casting it back to char, you're generating a random letter between A and Z. Simple!

Upvotes: 1

kviiri
kviiri

Reputation: 3302

In Java, a char is essentially a 16-bit unsigned integer as well as a single symbol. When using + between a char and integer, instead of concatenation, you use normal addition. Each character's value is their usual unicode value: capital A is 65.

So what's happening here? Math.random() produces a random floating point number in the range [0..1). That is multiplied with 27 (order of operations) and the result is added to 65. Finally, the resulting number is cast to char and printed, resulting in a random letter of the alphabet.

Upvotes: 2

Related Questions