In Java, Why is it not possible to convert a String to an Char array and vice versa?
Why aren't they comparable?
char matrixC[][] = {{'s', 't','a', 'c','k'},
{'o','v','e','r'},
{'f','l','o','w'}};
String [] matrixS = {"stack", "over","flow"};
// matrixS=matrixC //Not allowed...
if (matrixS.equals(matrixC) || matrixC.equals(matrixS) )
{
System.out.print("true");
}
else
System.out.print("false"); //Output
Edited:
After some research and digging, I found Answer of my first question (Why is it not possible to convert a String to an Char array and vice versa?) in below link, as explained by roger_that. Thanks for the hint James. Immutable
String is immutable. What exactly is the meaning?
So, we have separate String pool in java heap, which stores and creates new String literals each time and refer them to String objects accordingly.
Still, I have some doubts about their comparison (I am talking about simple String and Char sequence here, not 2d arrays)
Why is not there any standard and simple method to compare String and Char seq? One way could be, char data[] = {'a', 'b', 'c'}; String str="abc";
if (str.length()==data.length && str.length()>0 )
{
for (int i=0;i<str.length();i++)
{
if (str.charAt(i)!=data[i])
System.out.println("not equal");
}
}
else
System.out.println("not equal");
Is there any other simple/direct way to do this, except,
char data[] = {'a', 'b', 'c'};
String str="abc";
String str1= new String(data);
if (str1.equals(str))
System.out.println("equal");
Conclusion:
Strings are not sequence of characters in java.
They should remove this line from here https://docs.oracle.com/javase/tutorial/java/data/strings.html
Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.
This is the line from where my confusion started. :|
Please correct my understanding.
In C++ (which I'm guessing is what your coming from) Strings are stored as character arrays. This is not the case in Java. In java Strings are immutable objects rather then Char[].