Как перевести string в char java
Как перевести string в char java
Иногда возникают ситуации, когда имея величину какого-либо определенного типа, необходимо присвоить ее переменной другого типа. С переменными и их типами мы познакомились в прошлом уроке, в этом уроке мы рассмотрим наиболее популярные преобразования типов в Java:
Java преобразование строки в число (STRING to NUMBER)
В следующих примерах будет использована конструкция try-catch. Это необходимо для обработки ошибки, в случае, если строка содержит иные символы кроме чисел или число, выходящее за рамки диапазона допустимых значений определенного типа.
Например, строка «somenumber» не может быть переведена в тип int или в любой другой числовой тип. В это случае, при компеляции возникнет ошибка. Чтобы этого избежать, следует обезопаситься с помощью конструкции try-catch.
String to byte
C использованием конструктора
С использованием метода valueOf класса Byte
С использованием метода parseByte класса Byte
Перевод строки в массив байтов и обратно из массива байтов в строку
String to short
C использованием конструктора
C использованием метода valueOf класса Short
C использованием метода parseShort класса Short
String to int
C использованием конструктора
C использованием метода valueOf класса Integer
C использованием метода parseInt класса Integer
String to long
C использованием конструктора
C использованием метода valueOf класса Long
C использованием метода parseLong класса Long
String to float
С использованием конструктора
C использованием метода valueOf класса Float
C использованием метода parseFloat класса Float
String to double
С использованием конструктора
C использованием метода valueOf класса Double
C использованием метода parseDouble класса Double
String to boolean
Преобразование строки в логический тип 2мя способами. Обратите внимание, что строка не соответствующая true, будет преобразована в логическое значение false.
How to convert String to char in Java? Example
If your String contains just one character then, the only element in character array is what you are looking after. Though that’s not the only way to convert a String to char in Java.
You can also use charAt(index) method to get a char from String at a given index. Since String index starts from 0, «s».charAt(0) will return ‘s’, which is even easier than earlier approach.
Let’s see examples of both of these approaches to convert String to char in Java.
String to char using toCharArray()
The toCharArray() method returns the character array which makes the String. So, if you have just a single character as String like «a» then the toCharArray() will return a character array with just one element e.g. array with length 1, and the first character would be the equivalent character for the String. For example, here is the code to convert «a» to character ‘a’ in Java:
You can print both given String and character to see if they are same or not. Here is the output when I printed them into the console on my Eclipse IDE:
Btw, if you don’t know System.out.println() method is overloaded and one version takes String while another takes a character, here because we are concatenating String, the same method is called twice. See Complete Java Masterclass from Udemy to learn more about overloading and overriding in Java.
String to char using charAt(index)
Whatever we have done in the previous example, can also be done by using the charAt(int index) method.
If you look closely, in the last example, we first get the character array and then retrieve the char from the first index because we knew that our String just got one character.
Instead of doing all this you could have just called the charAt(int index) method.
This method does same, i.e. return the character from the character array which backs the String. For example, if you have a String with just one character e.g. «b» then the following code will convert this into a character ‘b’:
String given = «b»;
char b = given.charAt(0);
This code will return the character from the first index, which is ‘b’, hence we have successfully converted string «b» to character ‘b’ in Java. You can further see these free Java Online Courses for Beginners to learn more about String and character literals in Java.
Here is the screenshot of complete Java program and its output for your reference:
That’s all about how to convert String to char in Java. This is one of the fundamental things which every Java developers should be aware of. You can solve many coding problems if you know these basic techniques because most of the String based coding problems are nothing but an array-based problems, once you know how to convert a String to a character array.

