I am trying to print the letters of the alphabet in caps. So I wrote this in a for loop:
System.out.print(Character.toChars(i));
//where i starts at 65 and ends at 90
This works fine and prints the letters but In my code I wanted to put a space between the letters to make it look nicer. So i did this:
System.out.print(Character.toChars(i) + " ")
Why does it print the memory address of the characters instead of the letter?
The solution I came up with was to explicitly convert the char to a new String object:
String character = new String(Character.toChars(i));
System.out.print (character + " ");
but I'm not quite sure why I can't just write "Character.toChars(i)"
In the first one Does the method(Character.toChars()) point to the address of the character and System.out.print is smart enough to print the value at that address? i.e the corresponding letter?
System.out.print(Character.toChars(i)) calls PrintStream.print(char[]), an overload that handles char[] specially.
Character.toChars(i) + " " is really equivalent to Character.toChars(i).toString() + " "; calling toString() on an array type results in a string representation of its address (this behaviour is directly inherited from Object).
A simpler solution for your particular case may be this:
System.out.println((char)i + " ");
The Character.toChars method returns char[], which will be represented as [C#<hex hashcode> in String form.
You don't need to use the toChars method (or do any casting at all):
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
You use string concatenation, with one side being an array of chars and the other a string and according to the Java language specification, then as the char array is not a primitive type, but a reference value (aka an object), its toString method is called. And as there is no specific method implemented for arrays, they inherit the method implementation from java.lang.Object, which prints the address.
On the other hand, System.out.print(Character.toChars(i)) calls a specific implementation of print for character arrays, see the documentation of PrintStream.
//take the input from user
text = br.readLine();
//convert to char array
char ary[] = text.toCharArray();
System.out.println("initial string is:" + text.toCharArray());
System.out.println(text.toCharArray());
Output:
initial string is:[C#5603f377
abcd
println() is overloaded to print an array of characters as a string, which is why the 2nd print statement works correctly:
public void println(char[] x)
Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().
Parameters:
x - an array of chars to print.
The 1st println() statement, on the other hand, concatenates the array's toString() with another string. Since arrays don't override toString(), they default to Object's implementation, which is what you see.
I am printing a 1d array of chars by using System.out.println(arr) and I get the characters in the array (not space seperated). When I do the same by adding a "/t", the output changes and it now prints the address of the char array.
I tried to print a 1d array of ints using System.out.println(arr), but the results were different and it printed the location of the array in memory.
Please tell what is going on and how is it all implemented.
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
class Main3{
public static void main(String[] args)throws java.lang.Exception{
int[] intArr = {1,2,3,4};
char[] charArr = {'a' , 'b' };
System. out.println(intArr); // prints the address of the intArr
System. out.println(charArr); // prints the charArr contents
System.out.println("\t" + charArr); // prints the address of the charArr after a tab
}
}
PrintStream has a method that accepts a char[].
However when you do "\t" + charArray java tries to do String concatenation. To do this it first has to convert charArray to a String using the Object#toString method(JLS 5.1.11). Then it passes the String into println.
The following print statement:
System.out.println(charArr);
invokes the PrintStream#println(char[]) method. From the documentation:
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.
Whereas the next print statement:
System.out.println("\t" + charArr);
converts the charArray to String, by invoking the toString() method of Object class, as arrays don't override it. And then the method PrintStream#println(String) is invoked.
So, the above print statement is equivalent to:
System.out.println("\t" + charArr.toString());
Look into the Object#toString() method to see how it forms the string for the array.
The way to access the elements of the array is with bracket notation. So for example if you want the get the int at index 0 of the intArr you could write
System.out.println(intArr[0]);
where the number in brackets is the index of the element you want or you could iterate over all of them with
for(int i = 0; i < intArr.length; i++){
System.out.println(intArr[i]);
}
This will work as long as whats in the array is not an object - in which case it will print the address.
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();
}
}
I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);