clone()
The easiest method to copy an array, if what we want is to exactly copy the entire array, is to use the clone() method of the source array Object. Here is the signature of the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.*; public class Main { public static void main(String[] args) { String[] str={"welcome","to","webencyclop"}; String[] arr=str.clone(); for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } } |
Output:
1 2 3 |
welcome to webencyclop |
split()
split method takes string as input and return string array.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.*; public class Main { public static void main(String[] args) { String str="welcome to webencyclop"; String[] arr=str.split(" "); for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } } |
Output:
1 2 3 |
welcome to webencyclop |
toString
he simplest way to convert an Array to String is by using the java.util.Arrays class. It has already a built in method toString().
1 2 3 4 5 6 7 8 9 10 |
import java.util.*; public class Main { public static void main(String[] args) { String[] str={"welcome","to","webencyclop"}; String arr=Arrays.toString(str); System.out.println(arr); } } |
Output:
1 |
[welcome, to, webencyclop] |
length and length()
- length variable is used to calculate size of array.
- length() method is use to calculate size of string. Returns number of chars present in String.
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.*; public class Main { public static void main(String[] args) { String[] str1={"welcome","to","webencyclop"}; String str2="webencyclop"; System.out.println("Length of array is: " + str1.length); System.out.println("Length of string is: " + str2.length()); } } |
Output:
1 2 |
Length of array is: 3 Length of string is: 11 |
charAt()
charAt() method is used to find a character at index in string. charAt() method takes index as input. If the entered index is more than size of string then it throws “StringIndexOutOfBound” exception.
1 2 3 4 5 6 7 8 9 |
import java.util.*; public class Main { public static void main(String[] args) { String str="webencyclop"; System.out.println("char at index 3 is: "+ str.charAt(3)); } } |
Output
1 |
char at index 3 is: e |
If index is more than size of string
1 2 3 4 5 6 7 8 9 |
import java.util.*; public class Main { public static void main(String[] args) { String str="webencyclop"; System.out.println("char at index 15 is: "+ str.charAt(15)); } } |
Output
1 2 3 4 |
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at Main.main(Main.java:7) |