File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mismatch in printing the value of a variable

 
Rajat Bhatnagar
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a simple class Gertude in which i have a private variable number of type int.

I access this variable by getter and setter methods.

initially i set the value of this number to 100 by saying gerry.setNumber(100);and print it back by System.out.println(gerry.getNumber()) where gerry is a Gerude object.

Everything runs fine till here

But When I try printing the value of this gertude variable
by saying (new Gertude()).getNumber() it always comes to 0

I cant understand as to why this mismatch is happening

My code is

 
saurav sarkar
Ranch Hand
Posts: 180
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is your question?.
Both the objects are different.Your second SOP will print '0' always
as the instance variable of type int is initialized default to 0.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rajat Bhatnagar:
... But When I try printing the value of this gertude variable
by saying (new Gertude()).getNumber() it always comes to 0...

You're creating a new instance of Gertude, and then calling getNumber() before setting the number to anything, so number has its default of 0.
 
Rajat Bhatnagar
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It still doesn't work..

Even when i set the value by saying (new Gertude()).setNumber(200);
before the SOP it still prints the value as 0

 
saurav sarkar
Ranch Hand
Posts: 180
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
again you are creating two instances of your class.
calling new Gertrude() everytime creates a new instance for you.
 
Rajat Bhatnagar
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it ..

thnks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gertrude g = new Gertude();
g.setNumber(200);
System.out.println("Value of g.getNumber() is "+ g.getNumber());
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic