Newsletter

How to Convert String to char Array in Java

Core Java » on Oct 14, 2016 { 1 Comment } By Sivateja

In java we have built-in function String.toCharArray() to convert String to char array. But for sure in the interviews they will ask you to write a program to convert string to char array without using the built-in functions 🙂 I will show you how..

String to char Array Using Java Built-in Function

public class StringtoChar{
  public static void main(String[] args)
  {
     String str = "Java4s";
     char[] chArray = str.toCharArray();
     for(char ch : chArray)
     {
         System.out.println(ch);
     }
  }
}

String to char Array Without Using Built-in Function

public class StringtoChar{
  public static void main(String[] args)
  {
     String str = "Java4s";
     char[] chArray = new char[str.length()];

     for(int i=0; i<str.length(); i++){
        chArray[i] = str.charAt(i);
     }

     for(char ch : chArray){
        System.out.println(ch);
     }
  }
}

 

Output :

J
a
v
a
4
s

Choose whichever you need 😉

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

One Response to “How to Convert String to char Array in Java”
  1. Saurabh Gupta says:

    you have still used built in method.

    for(int i=0; i<str.length(); i++){
    chArray[i] = str.charAt(i);
    }

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.