please help me regarding this please
1) class ArrayCopyDemo
2) {
3) public static void main(String[] args)
4) {
5) char[] copyFrom={'s','i','v','a','k','i','r','a','n'};
6) char[] copyTo;
7) copyTo=new char[5];
8) System.arraycopy(copyFrom,4,copyTo,0,5);
9) System.out.println(new String(copyTo));
}
}
In line number of 9, even if we write the code as "System.out.println(copyTo)" the output is obtaining. what is the use of using "new String(copyTo)"
please answer this
regards
siva kiran.B
There is no use. It's almost always wrong to use new String(). You'll know when you need to use it, with experience. Until then, don't bother with it
> There is no use. It's almost always wrong to use new
> String(). You'll know when you need to use it, with
> experience. Until then, don't bother with it
new String(String x) is pretty useless, but in this case the code is calling new String(char[] x). That's a useful constructor, to convert an array of chars into a String. This particular code doesn't need to do it though, because he's only using it in System.out.println -- which works with various parameters, String or char[] among others.
So in this particular project, it can be viewed as useless to do that, but in general there are good reasons to use the String(char[] x) constructor.
> > There is no use. It's almost always wrong to use
> new
> > String(). You'll know when you need to use it,
> with
> > experience. Until then, don't bother with it
>
> new String(String x) is pretty useless, but in this
> case the code is calling new String(char[] x). That's
> a useful constructor, to convert an array of chars
> into a String. This particular code doesn't need to
> do it though, because he's only using it in
> System.out.println -- which works with various
> parameters, String or char[] among others.
>
> So in this particular project, it can be viewed as
> useless to do that, but in general there are good
> reasons to use the String(char[] x) constructor.
Apologies, I didn't spot it was using that constructor! Which is odd, since I've just used that constructor myself not half an hour ago! Thanks
> "System.out.println(copyTo)" the output is obtaining.
Apparently that is true for a char[]; however, in general, arrays do not print out the contents but a reference to the array instead. My guess is that the "new String" was used to ensure that the string representation was printed.
public class Test118{
public static void main(String[] args) {
char[] copyFrom={'s','i','v','a','k','i','r','a','n'};
char[] copyTo;
copyTo=new char[5];
System.arraycopy(copyFrom,4,copyTo,0,5);
System.out.println(new String(copyTo));
System.out.println(copyTo);
String[] xyz = {"a","b","c"};
System.out.println(xyz);
}
}
javac Test118.java
java Test118
kiran
kiran
[Ljava.lang.String;@3e25a5
jbisha at 2007-7-12 22:03:37 >
