Java 8 Cheat Sheet – Most Used Conversions – Char To String

Most often used java conversions all together: char to string, string to char, char to int, int to char, get the length of a string and more.

Card image cap

In this article I put together all of the conversions that are searched most often. Since java is a strong typed language, you will find yourself converting variables from one type to another quite often. The conversions below are some of the most searched conversions, like char to String, String to char and more. Having them all together in a piece of paper, close to your laptop, will save you time when you are programming.

All conversions will use only native java, no third-party libraries.

Let’s dive into each one of them!

Char to string java

There are three different ways to convert a char to string. Below you can find the three ways, using only native java.

Approach #1

The Character class has a static method toString()that is designed for this use case. See below how it works:

public class Sample {
	public static final void main(String[] args){
		String string1 = Character.toString('c');
    }
}

Approach #2

Here is another way, which is equivalent to the one above. You can create an instance of the class Character using its constructor. This is called boxing. Boxing means wrapping a primitive type with its equivalent object type.

Once you wrap the character, you can call the toString() method to get the String. See below how this works:

String string2 = new Character('c').toString();

Approach #3

The String class also offer a way to convert char to string. You can use the static method valueOf() passing as a parameter(or argument), the character you want to convert. As a result, you will get exactly the same character saved in a string variable. See below how this will work:

public class Sample {
	public static final void main(String[] args){
		 String string3 = String.valueOf('c');
    }
}

String to char

You might encounter situation where you have a string, that you need to convert to a char. The String class offers a method dedicated to this purpose, the charAt() method. Given a string, and the index of the letter or digit you want to convert, this method will return the corresponding character. See how this works below:

public class Sample{
	public static final void main(String[] args) {
       char variable = "c".charAt(0);
       System.out.println(variable);
    }
}

Output:

c

Java char to int 

When converting char to int, or the other way around, keep in mind each character has its corresponding ascii number that represents the character. As you can see in this ascii table, each character has a corresponding decimal number that uniquely represented.

Approach #1

This approach will convert a char to its corresponding decimal ascii number. All you need to do is casting the char variable to an int, and you will get the decimal character. Or you can do the opposite conversion. Given an ascii decimal number, get the corresponding character. See this in action in the example below:

 public class Sample {
	public static final void main(String[] args) {
       char variable1 = 'c'; // ascii number = 99
       System.out.println((int)variable1);
       System.out.println((char)99);
    }
}

Output:

99
c

Approach #2

This approach will convert the string to its numeric value. In this case, to convert from char to int, first you need to convert the char to string, using String.valueOf(). Then using the static method Integer.parseInt(), convert the string to its int numeric value. See how this works below:

public class Sample{
	public static final void main(String[] args){
    	int int1= Integer.parseInt(String.valueOf('1'));
        System.out.println(int1);
    }
}

Output:

1

Approach #3

And the last approach to convert a char to int in java. The Character class provides a static method called getNumericValue() that is aiming this use case. As argument, you need to pass the character, and it will return an integer containing the character numerical value. See how to action this below:

public class Sample {
	public static final void main(String[] args){
    	int int2= Character.getNumericValue('2');
        System.out.println(int2);
    }
}

Output:

2

Int to char java

Sometimes you will have a number and you might want to convert to a char to append it to a string, for instance. The Character class has the static method forDigit(), that is designed for this scenario. As parameter, you will need to pass, first the number to convert, and second the numeric base, 10 for decimal numbers. As a result, this method will return the number as a char. See how this works in the example below:

public class Sample {
	public static final void main(String[] args){
       char char1 = Character.forDigit(3,10);
       System.out.println(char1);
    }
}

Output:

3

Length of a string

There are many situation while programming where you will need to get the string length. For instance, verifying if a string is empty. Fortunately, the String class has a method aiming exactly this scenario. The length() method. This method will return a number containing the string size. See how this works below:

public class Sample{
	public static final void main(String[] args){
        String text = "hey there";
        int length = text.length();
        System.out.println(length);
    }
}

Ouput:

5

Or you can call the length()method directly on the literal string, and avoid using an intermediate variable. See the example below:

int length = "hello".length();

String to char array java

Another very often used data conversion is converting a string to a char array. This enables you to loop through each character. The String class provides a method for exactly this purpose. The toCharArray() method, will return a char array containing all string letter, without changing its order. See example below illustrates how the toCharArray() method works:

public class Sample{
	public static final void main(String[] args) {
        String text = "Hey there";
        // Convert string to char array
        char[] array = text.toCharArray(); 
        for(char c: array){
            System.out.println(c);
        }
    }
}

Output:

H
e
y
 
t
h
e
r
e

Reverse a string in java 

There are various string checks and operations that you might require you to reverse a string in java. You can use a loop to iterate the string from end to start, however java offers a simpler way. The StringBuilder class has a method called reverse() that will reverse the string order. First, create an StringBuilder instance using its constructor. Next call the reverse() method. And last convert the StringBuilder to String with the toString() method. See how this works below:

public class Sample {
	public static final void main(String[] args) {
       String variable = "Hey there";
       String reversed = new StringBuilder(variable).reverse().toString();
       System.out.println(reversed);
    }
}

Output:

ereht yeH

Java list to array

Converting a list to an array in java is a common operation. For this purpose, the List class has a method called toArray() which will return an array. As a parameter, you need to pass the elements type. See how this works below:

import java.util.Arrays;
import java.util.List;

public class Sample {

    public static void main(String[] args) {
       List<Integer> list = Arrays.asList(54, 234, 64, 23);
        Integer[] array = list.toArray(new Integer[0]);
        for(Integer i:array) {
            System.out.println(i);
        }
    }
}

Output:

54
234
64
23

How to print an array in java

Java 8 has introduced the stream feature. This feature removed the need to use loops to iterate through a collection. This allows to perform an action for each collection item, easily with one code line. 

In this case we want to print each collection item. First we will need to convert the array to a Stream instance using the Stream.of(). Next we can use the forEach() method, passing as parameter the operation to perform. See how this works below:

import java.util.stream.Stream;

public class Sample {
	public static void main(String[] args) {
        String[] array = {"something","fresh","hi"};
        Stream.of(array).forEach(System.out::println);
    }
}

Output:

something
fresh
hi

Char array to string java

And last conversion. Converting a char array to a string is quite common and easy to forget operation. There are two ways to do this conversion.

Approach #1

You can convert a char array to a string simply using the String constructor, which accepts a char array as a parameter. See an example below:

public class Sample {
	public static void main(String[] args) {
        char[] array = {'c','o','d','i','n','g'};
        String text = new String(array);
        System.out.println(text);
    }
}

Output:

coding

Approach #2

And there is another alternative way to convert a char array to a string. The String class has a static method valueOf(), which also accepts a char array as a parameter. This method will append all chars and return a string. See how this works below:

public class Sample {
	public static void main(String[] args) {
        char[] array = {'p','r','o','g','r','a','m','m','i','n','g'};
        String text = String.valueOf(array);
        System.out.println(text);
    }
}

Output:

programming

Conclusion

To summarise, we have seen some of the most used conversion in java, including: char to string, string to char, char to int, int to char, get the length of a string, convert string to char array, reverse a string in java, convert list to array and converting a char array to a string.

These conversions are quite easy to forget. You can write them all down in a post so you can refer them easily when you are programming.

I hope this tutorial was helpful and thanks for reading and supporting this blog! Happy Coding! 🙂

Recommended articles

Python Errors: Nameerror name is not defined and more

Django: order by and filter with examples

How long does it take to learn Python?

Python assignment for Practice – Plan a delivery route

What is the purpose of OpenCV?

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java