General

How to convert string to String array in Java?

Java may be a high-level, class-based, object-oriented programing language that’s designed to possess as few implementation dependencies as possible. it’s a general-purpose programing language intended to let application developers write once, run anywhere, meaning that compiled Java code can run on all platforms that support Java without the necessity for recompilation. Java is mostly based on Object-oriented programming.

You can know more about Java here

What is a Java string?

for example:

In Java, the string is basically an object that represents a sequence of char values. An array of characters works the same as a string.

char[] ch={'a','n','s','w','e','r','p','u','p'};  
String s=new String(ch); 

is same as:

String s="answerpup";  

This will reduce work load and also save some memory.

What is a String Array?

A String Array is an Array of a fixed number of String values. A String is a sequence of characters as explained above. The basic difference between string and string array is string array has limited to a certain number.

A String Array can be initialized by following ways:-

1. String[] strAr1=new String[] {"Khalid", "Ritik", "Satinder}; //inline initialization  
2. String[] strAr2 = {"Khalid", "Satinder", " Ritik"};  
3. String[] strAr3= new String[3]; //Initialization after declaration with specific size  
   strAr3[0]= "Khalid";  
   strAr3[1]= "Satinder";  
   strAr3[2]= "Ritik";  // Please follow us at @answerpup 

How to convert string to String array?

In java 8, there is a method with which you can do this: toCharArray(): This is the simplest method one can use to convert a string into a string array .

String k = "abcdef";
char[] x = k.toCharArray();

By using the above code, output would be

[a,b,c,d,e,f]

Hence by this method one can convert a String into a string array. below is one more example one can use

 
public class JavaStringToStringArray {
 
 public static void main(String args[]){
 
 //String 
 String str = "Got your back";
 

 
 String strArray[] = str.split(" ");
 
 System.out.println("String converted to String array");
 
 //print elements of String array
 for(int i=0; i < strArray.length; i++){
 System.out.println(strArray[i]);
 }
 }
 
}
 
/*
Output of Java String to String Array Example would be
String converted to String array
We
Got
Your 
Back
*/

Read Also: How to Buy Dogecoin | Will dogecoin reach $1

What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Ritik Banger

Founder and Editor of Answer Pup. An Engineer who loves to write in History, Politics, Tech, Opinion, and Facts.

Related Articles

Leave a Reply

Back to top button