Why does toString() not print this array of ints? [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
In working on an Euler problem as a new Java programmer, I have encountered something peculiar related to printing an array.
I do not understand why this is happening - the individual values appear to be correct, when printed individually, but the toString() is clearly creating a string which is not what I expect.
I would have expected either a compile error, or the array to be put into a concatenated list. Neither of these happened.
Note: I am not interested in "how to print an array?" but rather understanding why the toString() does NOT print the array. There are plenty of resources online available to find how to do so.
public class example {
public static void main(String[] args) {
/* Setup a string/int array converion*/
int i=0;
String nums = "123456";
char[] splitNums = nums.toCharArray();
int[] ints = new int[nums.length()];
for (char c : splitNums) {
ints[i++] = Character.digit(c,10);
}
//Print using the string/char[]
System.out.println(nums);
System.out.println(splitNums);
//Values are clearly there
for (int j : ints){
System.out.println(j);
}
//What is toString() doing?
System.out.println(ints.toString());
}
}
Output:
123456
123456
1
2
3
4
5
6
[I#4b71bbc9

The output [I#4b71bbc9 that you see is the output of the method Object.toString(). Arrays are objects in Java, but they don't have their own implementation of a toString() method - so java.lang.Object's version is called, which prints this kind of output (see the docs).
To print an array, do this instead:
System.out.println(Arrays.toString(ints));

toString() are implicitly called when you are printing an object. Since ints is an array (treated as object) and not a primitive.
When your ints are placed within a println statement, the toString() method inherited from Class Object are invoked printing what you saw on your screen.
So why does it inherit from Class Object?
This is because every class in Java implicitly extends from Class Object.
To print an array with a println statement, you can do this:
System.out.println(Arrays.toString(arrayName));
It will print out the formatted array nicely for you:
Example:
[0, 1, 2, 3, 4]
About toString()
The toString() method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read.
-From the API of toString-
So in general a toString() method makes a printed object meaningful and textually understandable of what the object represents. However there are a few exception when printing object such as String objects and char array. The reason which is self-explanatory (String already in String)

Related

how can i get word from arraylist?

I made an arraylist data and when I do
int last=data.size();
int random = r.nextInt(last) + 0;
string a = ""+data.get(random).toString();
a gets the address of the data.
Actually , data.get(random) returns you the object from the list. Since, you are calling data.get(random).toString(), you are getting the string representation which by default returns the hexadecimal characters.
Try the following:
a. Perform your code with a list of String. -> it should return the string at that index position(random).
b.
Try overriding the toString() method inside you java object, you will get the output from your toString() method of the java object,.

Printing String Array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
Here is my code:
String[] magic = {"stick", "hat", "witch"};
String magic1 = magic.toString();
String magic2 = Arrays.toString(magic);
System.out.println(magic1); // this is printing a memory location
System.out.println(magic2); // this one prints: [stick, hat, witch]
What is the difference between magic1 and magic2?
Arrays are objects, but they don't change (override) its toString() method, which means they use default one, inherited from Object. If you read documentation of this method you will find:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
In your case
getClass().getName() returns [Ljava.lang.String which means
one dimensional array (because there is only one [)
of type which full name is java.lang.String
and Integer.toHexString(hashCode()) returns something like 1db9742 which is hexadecimal form of integer returned by hashCode() method.
Now if you take a look at code of Arrays.toString(Object[] array) (String[] is considered as Object[])
4531 public static String toString(Object[] a) {4532 if (a == null)4533 return "null";4535 int iMax = a.length - 1;4536 if (iMax == -1)4537 return "[]";4539 StringBuilder b = new StringBuilder();4540 b.append('[');4541 for (int i = 0; ; i++) {4542 b.append(String.valueOf(a[i]));4543 if (i == iMax)4544 return b.append(']').toString();4545 b.append(", ");4546 }4547 }
you will see that its purpose is to create string build from content of this array. It does this by iterating over all elements and adding their string representation to StringBuilder which is then used to create String which will be returned.
It is basically a tailored toString which makes the output pretty.
What you see in the first toString is the memory address . Reason being that the variable-name is just that - a memory address( aka reference ).
Every class inherits toString, and can implement its own.
See Arrays class API
String[] names = {"Bob", "Dad", "Mom"};
String names1 = names.toString();
String names2 = Arrays.toString(names);
System.out.println(names1 );
System.out.println(names2 );
prints out:
[Ljava.lang.String;#1034bb5
[Bob, Dad, Mom]
Read the doumentation. I have copied the necessary information here.
public static String toString(Object[] a)
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
The value returned by this method is equal to the value that would be returned by Arrays.asList(a).toString(), unless a is null, in which case "null" is returned.
public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())

Multiple string method chained in single code

I am working on this bit of code
public class SimpleStringTest {
public static void main(String args[])
{
String ints="123456789";
System.out.println(ints.concat("0").substring(ints.indexOf("2"),ints.indexOf("0")));
}
As per as my knowledge on java "When the multiple methods are chained on a single code statement, the methods execute from left to right" Then, Why is this bit of code throwing StringIndexOutOfBondsException?
Thanks in advance,
GPAR
Because Strings are immutable.
By invoking concat, you are not modifying ints, you are creating a new String.
Therefore by the time you invoke ints.indexOf("0"), ints is still equal to its former value and the indexOf invocation returns -1, which in turn will be the outer bound of your substring.
Try a counter-example with a mutable CharSequence such as StringBuilder:
StringBuilder ints = new StringBuilder("123456789");
System.out.println(ints.append("0").substring(ints.indexOf("2"),ints.indexOf("0")));
Output
23456789
Because ints.indexOf("0") is applied on the original String ints (not the one you concatenate).
Since there is no "0" indexOf("0") returns -1 and which throws the exception.
Your code is equivalent to this:
String ints="123456789";
int indexOne = ints.indexOf("2");
int indexTwo = ints.indexOf("0");
System.out.println(ints.concat("0").substring(indexOne, indexTwo));

Print only certain elements in an Array [duplicate]

This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 8 years ago.
I've been given the following array
tests[] b = new tests[50];
So, there are some null elements in this array and I don't want to print those in my array.
for(int i = 0; i < b.length; i++){
if(b[i] != null){
System.out.println(b[i]);
}
}
So, this prints out '#251970e2' but I need to be able to print out each valid elements contents which should be like 'batman', 'joker', 'batgirl'
Sorry if this has been answered previously, I had a look but haven't had much luck :(
You need to override toString method in your class because it is going to give you clear information about the object in readable format that you can understand.
The merit about overriding toString:
Help the programmer for logging and debugging of Java program
Since toString is defined in java.lang.Object and does not give valuable information, so it is
good practice to override it for subclasses.
#override
public String toString(){
// I assume name is the only field in class test
return name ;
}
Override toString method in your Tests class ..
class Tests{
..... your code
#Override
public String toString(){
... return the value
}
}
You need to override the toString() method in your tests class.
For further discussion, see How to use the toString method in Java?

What does the mere name of objects in java imply (Array, ArrayList ) [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 8 years ago.
I am switching over from C to java programming gradually. While doing so I am confused while understanding the following scenario:
I have following Java Code:
ArrayList<Integer> myList = new ArrayList<Integer>();
for(int j = 0 ; j < 10 ;j++){
myList.add(j);
}
System.out.println(myList);
the o/p is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
According to my understanding what I have here is an object(myList) of type ArrayList.
Now I tried to do the same with an Array object: The same code but replacing Arraylist with an Array:
int [] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
System.out.println(Arr);
I get Garbage values. Why is this so? What is the difference between Array and ArrayList?
As in C , the name of the array is sort of a pointer. (IT has the address of the first element) , So in Java , what does the mere names of the object imply ?
Address or Reference ?
What is the difference?
Why do I get varied results in case of Array and ArrayList?
Although all parts of the question have been answered in different posts, I'd like to address your specific wording.
First, it is recommended that you declare your list type as an interface and initialize it as an implementation:
List<Object> list = new ArrayList<Object>();
List<Object> list = new ArrayList<>(); // JDK 7 or later allows you to omit the generic type.
You can implement a List interface with several implementations (ArrayList, LinkedList...). See the collection tutorial.
What is the difference between Array and ArrayList?
ArrayList is a class, see the API. it serves as an implementation for the List interface, see the API. These are part of the Java Collections Framework.
An array is not a class as the ArrayList is, but both an array and an instance of a class are objects. Be careful with uppercasing Array, as it is a different class.
I get garbage values. Why is this so?
Why do I get varied results in case of Array and ArrayList?
This has to do with the println method. It automatically calls the toString method of the argument passed into it. The toString method is defined for the Object class which superclasses all other classes, thus they all inherit it. Unless the subclass overrides the inherited method, it retains the implementation of its superclass. Let's look at what it does for Object:
public String toString()
Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the
class of which the object is an instance, the at-sign character `#',
and the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Emphasis mine. As you can see, that's the "garbage" you get when printing the array variable. Since arrays are not classes, they cannot override this method (arrays can invoke all the methods of Object, although they don't subclass it in the usual way). However, the subclass AbstractCollection of Object overrides this:
public String toString()
Returns a string representation of this
collection. The string representation consists of a list of the
collection's elements in the order they are returned by its iterator,
enclosed in square brackets ("[]"). Adjacent elements are separated by
the characters ", " (comma and space). Elements are converted to
strings as by String.valueOf(Object).
Since ArrayList is a subclass of AbstractList, which is a subclass of AbstractCollection (and they do not override toString), you get the "concise but informative representation that is easy for a person to read".
There are some fine points as to how the JVM handles arrays, but for the sake of understanding the output from the developer's point of view, this is enough.
In java, a name of a variable is a reference to the variable (if we compare to c++). When you call println on myList you in-fact call the toString() method of ArrayList which is inherited from Object but overridden to give meaningful print. This method is inherited from Object because ArrayList is a class and all classes extend Object and thus have the method toString.
You don't have this trait with native arrays which are primitives so what you get is the default object representation (virtual memory address).
You can try something like this:
public class TestPrint {
private String name;
private int age;
public TestPrint(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name;}
public int getAge() { return age; }
}
Then try println(new TestPrint("Test", 20)); - This will print something similar to what you got with the array.
Now, add a toString() method:
#Override
public String toString() {
return "TestPrint Name=" + name + " Age=" + age;
}
And call println(new TestPrint("Test", 20)); again and you'll get TestPrint Name=Test Age=20 as the output.
Just to further explain why this happens - the method println has an overload that accepts something of type Object. The implementation of this method calls toString to print the object (this is very schematic explanation of course).
In Java everything is a pointer, but depending on what a variable is pointing, the behavior can change.
int[] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] is an array of a primitive type (not of a class type), and it does not contains any information about its 'string representation', so when you want to print the variable as you have done (System.out.println(Arr);), what is printed out it is simply a string representation suitable for any kind of object, like its hashcode (it is not garbage).
While with:
ArrayList<Integer> myList = new ArrayList<Integer>();
you are creating an object of the (generic) class ArrayList<>: this overrides the method (function in C) toString() that specify how print gracefully the content of the ArrayList itself (the method is really basic: it simply iterate over all the items contained, create a string and print it).
When you call System.out.println(myList); the method toString() (which return a String) is implicitly called, and therefore the string created by the method will be printed, as you have shown.

Categories