Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
91 views

2 Ways To Convert String To Character Array in Java

There are two ways to convert a string to a character array in Java: 1) Using the String.toCharArray() method which converts the string directly to a character array. 2) Writing your own logic by extracting each character from the string using String.charAt() and inserting it into a character array. Both approaches are demonstrated with code examples that output the character array.

Uploaded by

Muataz Medini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

2 Ways To Convert String To Character Array in Java

There are two ways to convert a string to a character array in Java: 1) Using the String.toCharArray() method which converts the string directly to a character array. 2) Writing your own logic by extracting each character from the string using String.charAt() and inserting it into a character array. Both approaches are demonstrated with code examples that output the character array.

Uploaded by

Muataz Medini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

2 Ways to Convert String to

Character Array in Java


Here you will learn about different ways to convert string to character array in java.
1. Using String.toCharArray() Method
We can easily convert string to character array using String.toCharArray() method. It can
be done in following way.

package com;

public class StringToArray {


public static void main(String...s){
String str = "I Love Java";
char charArray[];

//converting string to character array


charArray = str.toCharArray();

for(char c : charArray){
System.out.print(c + " ");
}
}
}

Output
I Love Java
2. Writing Own Logic
We can also writing our own logic. Each character of string is extracted
using String.charAt() method and inserted into the character array.

package com;

public class StringToArray {


public static void main(String...s){
String str = "I love Java";
char charArray[] = new char[str.length()];

//converting string to character array


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

for(char c : charArray){
System.out.print(c + " ");
}
}
}

You might also like