1) How can I convert a primitive data type or Object into a String?
The String class provides a static method for this:
Alternatively, you can use the toString() method that every class inherits from the Object class. (String.valueOf(Object) actually calls the toString method).
2) How can I convert a String into a primitive data type or Object?
For a byte:
For a short:
For an int:
For a long:
For a float:
For a double:
For a boolean:
For an Object:
3) How can I get the ASCII value of a char?
4) I have two Strings, str1 and str2, both "abc", yet str1 == str2
is false. Why?
This is a common question in Java. == will only compare state of
primitive data types; with objects it checks if they have the same place in memory (ie. they are the exact same object).
The following code:
prints "str1 != str2".
You must use the equals(Object) method to compare Strings.
This prints "str1.equals(str2)".
5) I am comparing two Objects with the equals(Object) method.
In the String class this checks state, but now it's checking memory.
Why?
The equals(Object) method is inherited by the Object class. This
will check memory unless you override it to check state (which is
what the String class does).
eg:
At this point, comparing these two instances of MyClass with
the equals(Object) method would not return true.
After overriding the equals(Object) method, they will:
6) How can I force garbage collection?
You can't. You can suggest to perform garbage collection.
You cannot force it.
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. -- Java API
This message was edited 12 times. Last update was at 06/13/2007 05:06:51
|