• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on toString and Static

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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");
}
}
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
reply
    Bookmark Topic Watch Topic
  • New Topic