• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Selenium
  • Manual Testing
  • SQL Tutorial For Beginners
  • Difference
  • Tools
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » Convert String to Char and Char Array in Java

Convert String to Char and Char Array in Java

Last Updated on: July 10, 2023 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • What is a Character in Java?
  • What is a String in Java?
  • What is an Array in Java?
  • Java Strings and Chars
  • Let’s Convert a String to a Character
  • String to Char Using charAt() method
  • Program: Write a Java Program to Print the First Character Of a String.
  • String to Char Using toCharArray() method
  • Program: Write a Java Program to Convert a String to Character Array.
  • String to Char Using codePointAt() method
  • Program: Write a Java Program to Retrieve a Character Using the codePointAt() method
  • String to Char Using getChars() method

In this article, we will explore how to convert a string into a single character and an array of characters in Java. I will also take the time to explain what strings, characters, and arrays are for those who may not be familiar.

Post On:String to Char and Char Array in Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

What is a Character in Java?

Characters are the most primitive data type. A character is a single entity enclosed inside single quotation marks. It can be anything from a letter to a digit to a punctuation mark or even just a space!

For Example:

char var1 = 'a';
char var2 = '2';
char var3 = '!';
char var4 = ' ';

What is a String in Java?

Strings are one of the objects (reference type) in programming – they’re used to represent text. A string is simply a series of characters, and you can create them by enclosing their content in double quotation marks.

For example:

String vowels = "Software Testingo";

What is an Array in Java?

ArrayArrays are a fundamental data structure that can store a fixed number of elements of the same data type in Java. They’re simple to use and extremely versatile, making them one of Java’s most popular data structures.

char[] chararray= {'S', 'o', 'f', 't', 'w','a', 'r', 'e'};

Java Strings and Chars

If you’re working with text-based data in Java, you can use two data types that can be used to store text-based data. The first is called a string, which stores a sequence of one or more characters. The second is called char, and it stores an individual character.

For example, If you want to store a student’s name in a fifth-grade math class, you would store it as a string because it contains multiple characters. But if you only wanted to store the first letter of the student’s name, you would use a char data type.

The char data type is more efficient when working with individual characters than the String class. This is because the String class contains a lot of additional string-based methods, which are unnecessary when only dealing with one character.

Great! Now that we understand the strings, characters, and arrays, let’s move on to the next topic.

Let’s Convert a String to a Character

To convert String to Char, there are different ways available in Java. Here are some ways you can convert a string to a character array:

  • Using String.charAt() method
  • Using String.toCharArray() method
  • Using String.codePointAt() method
  • Using String.getChars() method

We will share the different ways with the examples So that it will be easy for you to understand the topic well.

String to Char Using charAt() method

We can convert a string to a char in Java using the charAt() method of the String class. The charAt() method returns one character at a specified index. The signature of the charAt() method is given below:

public char charAt(int index);
Program: Write a Java Program to Print the First Character Of a String.
package com.softwaretestingo.string;
public class StringToCharExample1 
{
	public static void main(String[] args) 
	{
		String s="Softwaretestingo";  
		char c=s.charAt(0);  
		
		System.out.println("Original String is : "+s);
		System.out.println("1st character is: "+c);  
	}
}

Output:

Original String is : Softwaretestingo
1st character is: S

String to Char Using toCharArray() method

A helpful way to get the character at a specific index in a string is to convert the string into a character array using String.toCharArray().

Program: Write a Java Program to Convert a String to Character Array.
package com.softwaretestingo.string;
import java.util.Arrays;
public class StringToCharExample2 
{
	public static void main(String[] args) 
	{
		String str="Softwaretestingo";  
		
		// create an array of characters 
		char[] strArray = str.toCharArray();

		// print Array
		System.out.println(Arrays.toString(strArray));
	}
}

Output:

[S, o, f, t, w, a, r, e, t, e, s, t, i, n, g, o]

From the above array, if you want to retrieve a specific character, then we can retrieve like below also:

package com.softwaretestingo.string;
public class StringToCharExample5 
{
	public static void main(String[] args) 
	{
		String str="Softwaretestingo";  
		
		char strChar = str.toCharArray()[0];
		System.out.println("1st character is: "+strChar);  
	}
}

Output:

1st character is: S

String to Char Using codePointAt() method

You can also use the String.codePointAt() method to find the code point value of the character present at a specified index.

Program: Write a Java Program to Retrieve a Character Using the codePointAt() method
package com.softwaretestingo.string;
public class StringToCharExample4 
{
	public static void main(String[] args) 
	{
		String s="Softwaretestingo";  
		
		//The codePointAt return the unicode of the character thats 
		//why we have done the type casting
		char c=(char) s.codePointAt(0);  
		System.out.println("1st character is: "+c);  
	}
}

Output:

1st character is: S

This method is useful for iterating over the code points in a string. It can be used like this:

The String class has a codePointBefore() method that returns the codepoint value before the given index. This is similar to the codePointAt() method, which returns the codepoint value at that index.

package com.SoftwareTestingO.Strings;
public class StringToCharExample7 
{
	public static void main(String[] args) 
	{
		String str="Softwaretestingo";  

		char strChar = (char) str.codePointBefore(1);
		System.out.println("1st character is: "+strChar);
	}
}

String to Char Using getChars() method

The getChars() method is useful when copying characters from a string to a character array. This method copies the characters from the specified start index (inclusive) to the specified end index (exclusive) into the destination character array. The method syntax is:

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

Let’s understand the significance of each of the method arguments.

  1. srcBegin: index from where the characters will be copied.
  2. srcEnd: index at which copying will stop. The last index to be copied will be srcEnd-1.
  3. dst: The destination character array. It should be initialized before calling this method.
  4. dstBegin: The start index in the destination array.
package com.softwaretestingo.string;
import java.util.Arrays;
public class StringToCharExample6 
{
	public static void main(String[] args) 
	{
		String str="Welcome to Softwaretestingo Blog";  

		//Destination Array Size is 16
		char[] substringChars = new char[16];

		//We are copied from 11-27 and store in Destination array from index 0 
		str.getChars(11, 27, substringChars, 0);
		System.out.println(Arrays.toString(substringChars)); 
	}
}

Output:

[S, o, f, t, w, a, r, e, t, e, s, t, i, n, g, o]

Note: If the destination array size is smaller than the required size, we will get the StringIndexOutOfBoundsException exception.

Conclusion:

Now we believe you know how to convert strings to char arrays in Java; try it yourself! If you still have any doubts or questions, comment in the comment section, and we will try to help you ASAP.

    Strings In Java
    Strings In Java
    Polymorphism In Java
    Polymorphism In Java
    Java Instanceof in Java
    Instanceof in Java
    Variable in Java
    Variable in Java
    Online Core Java Tutorial for Beginners
    Online Core Java Tutorial for Beginners
    Java Installation On Windown 10 Machine
    Java Installation On Windows 10 Machine
    HashSet Class In Java
    HashSet Class In Java
    Deque In Java
    Deque In Java
    Declare and Initialize Array in Java
    How to Declare and Initialize Array in Java
    Java Switch Case Statement
    Java Switch Case Statement

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Footer

    Java Tutorial for Beginners | Selenium Tutorial | Manual Testing Tutorial | SQL Tutorial For Beginners | GitHub Tutorial For Beginners | Maven Tutorial

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers