String A; A = "abH"; // Assign string to string variable |
How a String is stored in memory:
As you can see, they are identical !!!
A string and an array of characters is different in Java because the language definition forces the user to use different syntax to gain access to the information stored inside a string and inside an array of characters.
|
In Java, the class definition in Java library java.lang.String class defines methods that forces the users to manipulate String typed veriables as specified by the given methods inside the java.lang.String class.
|
(No conversion mechanism is necessary in C/C++ to make strings into arrays of char and vice versa).
String s; s = "...."; s.toCharArray( ) returns an array of char containing all characters in string s |
Example:
String s; s = "abc"; char[] A; A = s.toCharArray( ); // Result: A[0] = 'a', A[1] = 'b', A[2] = 'c' |
Example:
char[] A = new char[ 3 ]; A[0] = '?'; A[1] = '>'; A[2] = "a"; String s s = new String( A ); // Make a String using the characters in array A |
public class ArrayChar1 { public static void main( String[] args ) { String s = "abc"; char[] A; /* ========================================= Convert String s into an array of char ========================================= */ A = s.toCharArray(); System.out.println( s ); for ( int i = 0; i < A.length; i++ ) System.out.println( "A[" + i + "] = " + A[i] ); System.out.println( "\n" ); /* ========================================= Convert an array of char A into string ========================================= */ A = new char[4]; A[0] = '>'; A[1] = '<'; A[2] = '?'; A[3] = 'a'; s = new String( A ); for ( int i = 0; i < A.length; i++ ) System.out.println( "A[" + i + "] = " + A[i] ); System.out.println( s ); } } |
How to run the program:
|
|
In other words:
|