Generate a random character in Java
This post will discuss how to generate a random character in Java.
1. Using Random.nextInt() method
If you need to generate a random character between some specific range, you can do so using the nextInt() method from the Random class. The following code generates a random character in the range A-Z. You can easily modify the code to generate a character in the range a-z.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Random; public class Main { private static char randomChar() { Random r = new Random(); return (char)(r.nextInt(26) + 'A'); } public static void main(String[] args) { char c = randomChar(); System.out.println(c); } } |
If you need to generate values in the ranges a-z and A-Z, you can do something like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Random; public class Main { private static char randomChar() { int rand = new Random().nextInt(52); char start = (rand < 26) ? 'A' : 'a'; return (char) (start + rand % 26); } public static void main(String[] args) { char c = randomChar(); System.out.println(c); } } |
If you want to generate an alphanumeric random character or use any other specific character set, you can do as follows.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Random; public class Main { public static void main(String[] args) { String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random r = new Random(); char c = alphabet.charAt(r.nextInt(alphabet.length())); System.out.println(c); } } |
2. Using Apache Commons Lang
You could also use the RandomStringUtils class from the Apache Commons Lang library. It offers several methods like randomAlphabetic(), randomAlphanumeric(), randomNumeric(), randomAscii(), etc., to create a random string of specific length.
|
1 2 3 4 5 6 7 8 |
import org.apache.commons.lang3.RandomStringUtils; public class Main { public static void main(String[] args) { String c = RandomStringUtils.randomAlphabetic(1); System.out.println(c); } } |
To get the lowercase equivalent, call the toLowerCase() method:
|
1 2 3 4 5 6 7 8 |
import org.apache.commons.lang3.RandomStringUtils; public class Main { public static void main(String[] args) { String c = RandomStringUtils.randomAlphabetic(1).toLowerCase(); System.out.println(c); } } |
That’s all about generating a random character in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)