Here's the problem. This code:
String a = "0000";
System.out.println(a);
char[] b = a.toCharArray();
System.out.println(b);
returns
0000
0000
But this code:
String a = "0000";
System.out.println("String a: " + a);
char[] b = a.toCharArray();
System.out.println("char[] b: " + b);
returns
String a: 0000
char[] b: [C#56e5b723
What in the world is going on? Seems there should be a simple enough solution, but I can't seem to figure it out.
When you say
System.out.println(b);
It results in a call to print(char[] s) then println()
The JavaDoc for print(char[] s) says:
Print an array of characters. The characters are converted into bytes
according to the platform's default character encoding, and these
bytes are written in exactly the manner of the write(int) method.
So it performs a byte-by-byte print out.
When you say
System.out.println("char[] b: " + b);
It results in a call to print(String), and so what you're actually doing is appending to a String an Object which invokes toString() on the Object -- this, as with all Object by default, and in the case of an Array, prints the value of the reference (the memory address).
You could do:
System.out.println("char[] b: " + new String(b));
Note that this is "wrong" in the sense that you're not paying any mind to encoding and are using the system default. Learn about encoding sooner rather than later.
Use
System.out.println("char[] b: " + Arrays.toString(b));
The gibrish you get is the Class name followed by the memory address of the object. Problem occurs when you try to append b with a string char[] b: in this case the char array b.toString() method is called thus [C#56e5b723 is printed.
[ indicates that it is an array
C indicates the class in this case char
#56e5b723 indicates the memory location
System.out.println("char[] b: " + b);
This is just like
System.out.println(("char[] b: " + b.toString());
You can look up "Object.toString()"
An array's toString() method (which is what's called when you do "..." + b) is only meant to give debugging output. There isn't a special case where a char[]'s toString() will give you the original string - arrays of all types have the same toString() implementation.
If you want to get the original string from the char array, use:
String a2 = new String(b);
Use
3:e row!
Scanner input = new Scanner(System.in);
char[] txt = input.next().toCharArray();
System.out.println((char[])txt);
private void print(char[] arr) {
try {
PrintStream stream
= new PrintStream(System.out);
stream.println(arr);
stream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3... and create a String word like this.
I could do
System.out.print(char1);
System.out.print(char2);
System.out.print(char3);
But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.
Thanks
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:
String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";
The first is evaluated at compile-time. The second is evaluated at run-time.
So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.
If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';
If however they aren't, consider this:
String concat(char... chars) {
if (chars.length == 0) {
return "";
}
StringBuilder s = new StringBuilder(chars.length);
for (char c : chars) {
s.append(c);
}
return s.toString();
}
as an appropriate solution.
However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.
Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.
For low-level optimisation the compiler is better at optimising code than you are.
Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
You can use the String constructor.
System.out.println(new String(new char[]{a,b,c}));
You need to tell the compiler you want to do String concatenation by starting the sequence with a string, even an empty one. Like so:
System.out.println("" + char1 + char2 + char3...);
System.out.println(char1+""+char2+char3)
or
String s = char1+""+char2+char3;
You need a String object of some description to hold your array of concatenated chars, since the char type will hold only a single character. e.g.,
StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);
public class initials {
public static void main (String [] args) {
char initialA = 'M';
char initialB = 'P';
char initialC = 'T';
System.out.println("" + initialA + initialB + initialC );
}
}
I don't really consider myself a Java programmer, but just thought I'd add it here "for completeness"; using the (C-inspired) String.format static method:
String s = String.format("%s%s", 'a', 'b'); // s is "ab"
this is very simple approach to concatenate or append the character
StringBuilder desc = new StringBuilder();
String Description="this is my land";
desc=desc.append(Description.charAt(i));
simple example to selecting character from string and appending to string variable
private static String findaccountnum(String holdername, String mobile) {
char n1=holdername.charAt(0);
char n2=holdername.charAt(1);
char n3=holdername.charAt(2);
char n4=mobile.charAt(0);
char n5=mobile.charAt(1);
char n6=mobile.charAt(2);
String number=new StringBuilder().append(n1).append(n2).append(n3).append(n4).append(n5).append(n6).toString();
return number;
}
System.out.print(a + "" + b + "" + c);
I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
toUpperCase in Java does not work [duplicate]
(5 answers)
Closed 6 years ago.
I want to change a string literal into all-uppercase one. Here is my code:
// a and b are the same literal
String a = "Test";
String b = "Test";
// now I want to change all b's letter
// into uppercases, but fail.
b.toUpperCase();
System.out.println("a = " + a + ", " + "b = " + b);
// print: a = Test, b = Test
String c = "Test1";
System.out.println("c = " + c + " , c.toUpperCase() = "
+ c.toUpperCase());
// print: c = Test1 , c.toUpperCase() = TEST1
// change letters of "Test" literal
// into uppercase and success
System.out.println("Test".toUpperCase());
// print: TEST
My question is:
1. b can't be changed into uppercase one, but c and "Test" can. Why?
What I know is:
1. a and b reference to the same object in string pool.
2. String is immutable, but it seems not relevant to this question.
Strings are immutable. So for change b:
b = b.toUpperCase();
Every time then you do something that changes a String, a new String object is created. So you need change the reference on object.
String is immutable, but it seems not relevant to this question
Actually, it's very relevant to the question
b can't be changed into uppercase one
Because toUpperCase() returns a new string by acting on the invoking string , use
b = b.toUpperCase();
c and "Test" can. Why?
c has not been changed it's result has been added to the string in System.out.println()
Let's take your code line by line and please read my comments :
// a and b are the same literal
/* FIRST POINT :
Here you assigned two times the same value "Test",
BUT IT'S 2 DIFFERENT OBJECTS IN MEMORY */
String a = "Test";
String b = "Test";
// now I want to change all b's letter
// into uppercases, but fail.
/* SECOND POINT :
Here you just apply a function (toUpperCase()) on "b" object.
This function returns a string object but
YOU ARE NOT DOING ANYTHING WITH IT
i.e. displaying it or reassigning it to another variable!
*/
b.toUpperCase();
System.out.println("a = " + a + ", " + "b = " + b);
// THAT'S WHY IT STILLS PRINT
// print: a = Test, b = Test
String c = "Test1";
System.out.println("c = " + c + " , c.toUpperCase() = "
+ c.toUpperCase());
/* THIRD POINT :
Here you apply a function (toUpperCase()) on "c" object but this time
YOU ARE REUSING THE RETURN STRING :)
i.e. you are displaying it!
*/
// print: c = Test1 , c.toUpperCase() = TEST1
// change letters of "Test" literal
// into uppercase and success
/* LAST POINT :
Here you do the same as you did before on "c" object
YOU ARE REUSING THE RETURN STRING AGAIN :)
i.e. you are displaying it!
*/
System.out.println("Test".toUpperCase());
// print: TEST
Last but not least calling toUpperCase()/toLowerCase() functions on string objects will never reassign the object's value. These functions only RETURN a string.
The way to reassign the string value is the usual way :
String a = "Test";
a = a.toUpperCase();
Please note, as many said, that this will create another object in memory "TEST" and assign it to "a" and your old string "Test" will then become a candidate to the garbage collector.
I hope it makes more sense now.
Cheers,
What happens when a string literal is changed?
Nothing. That is the string literal object cannot change, because as you point out you already know, it is immutable. References to it (variables like a,b,c) can be made to reference other strings, but that string instance will not change from "Test".
But to explain your code:
This is the difference between b and c:
b.toUpperCase(); //there's a result from this function you are not using
System.out.println("b = " + b);
System.out.println("c = " + c.toUpperCase()); //you're using the result here.
String is immutable, but it seems not relevant to this question
It is relevant, if you know that it is immutable, it is obvious that b cannot change to upper case and that a new string must be created as a result of toUpperCase and you must therefore use that. However b can be made to reference the new string, and this wont affect a or anything else which still references the old string:
b = b.toUpperCase(); //b now is set to the new upper case string
System.out.println("b = " + b);
My question is: 1. b can't be changed into uppercase one, but c and "Test" can. Why?
My answer is when you print c.toUpperCase(), variable c is not changed at all.
You merely returned the another String which was built to uppercase based on the content of c.
The same applies to String "test" as well.
Even if you do this, you are only pointing c to a new String:
String c = "Test1";
c = c.toUpperCase();
This is what happened:
//String c = "Test1";
+-------+
|"Test1"| <--- c
+-------+
//c = c.toUpperCase();
+-------+
|"TEST1"| <--- c
+-------+
+-------+
|"Test1"| <--- waiting to be collected by Garbage collector
+-------+
You need to change like this,because strings are immutable
public static void main(String[] args) {
// a and b are the same literal
String a = "Test";
String b = "Test";
// now I want to change all b's letter
// into uppercases, but fail.
b= b.toUpperCase();
System.out.println("a = " + a + ", " + "b = " + b);
// print: a = Test, b = Test
String c = "Test1";
// c=c.toUpperCase();
System.out.println("c = " + c + " , c.toUpperCase() = "
+ (c=c.toUpperCase()));
// print: c = Test1 , c.toUpperCase() = TEST1
// change letters of "Test" literal
// into uppercase and success
System.out.println("Test".toUpperCase());
// print: TEST
I suggest you to look into the Java API. By using toUpperCase you will get a new Object of String. If you want to print out the variable with new text, you should assign the new object to the variable. In case of c, you're printing out the returned "new" content of the object. The variable c will be lower case anymore.
I read from the blogs that internally java use StringBuilder to concat the String when we use + operator. I was just checking it and found some strange outputs.
public class StringDemo {
public static void main(String[] args) {
String a = "Hello World";
String b = "Hello World";
String c = "Hello";
String d = c + " World".intern();
String e = new StringBuilder().append(String.valueOf(c)).append(" World").toString().intern() ;
String f = new StringBuilder(String.valueOf(c)).append(" World").toString().intern();
System.out.println(a == b); // Line 1 Expected output true
System.out.println(a == d); // Line 2 Output is false
System.out.println(a == e); // Line 3 Output is true
System.out.println(a == f); // Line 4 Output is true
}
}
So i am using + operator to concat two strings c & " World" and then use intern() method to move String in the pool for String d.
As per my understanding java use StringBuilder, so now I use StringBuilder to concat the String and use intern() method for Strings e and f.
So if both the equivalent then address of both the String must be same but the output of Line 2 not matching with Line 4 & 5.
Thanks in advance for your valuable feedback.
How + internally works in JAVA
Here is my post on the same, give a read Compiler version : How String concatenation works in java.
And coming to your code inside
System.out.println(a == d);
That should be false only.
As per your understanding you are expecting true. No. Your understanding is wrong. There is a clear difference between
String d = c + " World".intern();
And
String d = (c + " World").intern();
In first line only "World" got interned and the second line "Hello World" got interned
When you do (c + " World").intern(), you'll see the output true.
I am new to Java.
I executed the below program successfully but I don't understand the output.
This is the program.
public class StringBufferCharAt {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
System.out.println("Length of sb : " + sb.length());
int start = 0;
int end = 10;
char arr[] = new char[end - start];
sb.getChars(start, end, arr, 0);
System.out.println("After altering : "+ arr.toString());
}
}
After executing this program: I got the following output:
Length of sb : 26
After altering : [C#21a722ef
My Questions:
Instead of printing 10 characters in the output, why 11 characters.
Instead of printing the original characters "abcdefghij" which are
inside sb, why did I get some other characters.
The arr.toString() in your last sentence is giving you a String value of your Object (doc here), here's an array. What you were probably trying to achieve was something like Arrays.toString(arr) which will print the content of your array (doc).
Why is the output 11 characters, and what do those characters mean?
It just so happens that the string representation of the char[], as specified by Object#toString(), is 11 characters: the [C indicates that it's a char[], the # indicates the following 8 hex digits are an address in memory. As the JavaDoc states,
This method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Class#getName() returns "C[" for a char array, and the default hashCode() implementation (generally) returns the object's address in memory:
This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.
How should this be solved?
If you want to print the contents of an array, use Arrays.toString():
// Instead of this:
System.out.println("After altering : "+ arr.toString());
// Use this:
System.out.println("After altering : "+ Arrays.toString(arr));
You need to have final print statement like this:
System.out.println("After altering : "+ new String(arr));
OR
System.out.println("After altering : "+ java.util.Arrays.toString(arr));
OUTPUT
For 1st case: abcdefghij
For 2nd case: [a, b, c, d, e, f, g, h, i, j]
Note: arr.toString() doesn't print the content of array that's why you need to construct a new `String object from char array like in my answer above or callArrays.toString(arr)`.
Arrays in java do not have any built in 'human readable' toString() implementations. What you see is just standard output derived from the memory location of the array.
The easiest way to turn a char[] into something printable is to just build a string out of it.
System.out.println("After altering : " + String.valueOf(arr));
The expression arr.toString() does not convert a char[] to a String using the contents of the char[]; it uses the default Object.toString() method, which is to print a representation of the object (in this case an array object). What you want is either to convert the characters to a String using new String(arr) or else an array representation of the characters using Arrays.toString(arr).
The one part of this question I can answer is #1. You are getting back 11 characters because the start and end variables are indexes. 0 is a valid index so, from 0 - 10 there are 11 different numbers.