aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on toString  and Static Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Question on toString  and Static" Watch "Question on toString  and Static" New topic
Author

Question on toString and Static

Raja Nandam
Greenhorn

Joined: Sep 14, 2001
Posts: 1
See the following Code..
Can you tell my why it should return False when
(b1.toString() == b1.toString()) is compared.
Another Question..
If you declare int i = 10 in the static block instead of i = 10, ie.,
if you type static { int i = 10} instead of static {i = 10} the result is differing.. Can you explain the reason.
Here is the complete code..

public class Q8
{
static int i = 20;
static
{ i = 10;
}
public static void main(String[] args)
{
//int i = 10;
Q8 a = new Q8();
System.out.println(a.i);
System.out.println(i);
Byte b1 = new Byte("127");
System.out.println(b1.toString());
if(b1.toString() == b1.toString())
System.out.println("True");
else
System.out.println("False");
}
}
Gurpreet Sachdeva
Ranch Hand

Joined: Feb 20, 2001
Posts: 90
Hello Raja,
b1.toString()==b1.toString() will return false as both the statements will return new string objects and when you compare two different string objects using == it will return false.
Now coming to the case of declaring "int i=10" or "i=10" in the static block:
When you give the print statements:
System.out.println(b.i); OR
System.out.println(i);
Both the statements is trying to print the same class variable i. The variable i is first intialized by 20 and then modifies in the static block by 10(when you use simply "i=10"). So it will print the last value assigned to i i.e. 10.
Now, when you use "int i=10", in that case there are two variable named i one is class variable and one is local to the static block and in the print statements you are printing the class variable i and its value is 20,so it will print 20.
I hope it will help.
Regards
Gurpreet Sachdeva
For Mock Exams, FAQ and some useful information about Bitshift operator, inner classes, garbage collection,etc please visit: http://www.go4java.20m.com

Regards<BR>Gurpreet Sachdeva<P>For Mock Exams, FAQ, Exam tips and some useful information about Bitshift operator, inner classes, garbage collection,etc please visit: <A HREF="http://www.go4java.lookscool.com" TARGET=_blank rel="nofollow">http://www.go4java.lookscool.com</A>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on toString and Static
 
Similar Threads
String Question
Byte and String
Byte class(Wrapper class)
toString() behaviour?
toString