Should i initialize the instance variables or not?

hi guys ,i am trying to learn java therefore if i miss something sorry.
for example i have like this a class
is it good thing to always initialize those variables or initialize like in this exam and initialize with constructor too ?
public class SomeClass
     private double principal=1.0;
     private double rate=0.1;
     private int    years=1;
     private int    times=1;
     public static void main(String[] args)
}

878144 wrote:
i guess i explicitly initialize them or i dont however java does it for me even i dont explicitly say int variable=0; however java will do it i guess also it doesnt make sense to me i do or compiler does.No idea what you're saying here. Try writing proper sentences with proper capitalization, grammar, spelling, and punctuation.
why some people say yes some of them say no.if u dont do it then java does it also same thing.Reason to do it: Makes it clear what you want the initial value to be, and that you didn't forget to initialize it.
Reasons not to do it: Redundant and cluttersome. Also, can lead to unexpected behavior in some cases involving subclasses.
Ultimately, the decision is more about personal preference than anything.

Similar Messages

  • Initialize the shared variable

    "From the issue description it seems that the Shared variable needs to be reinitialize.
    Create a formula to initialize the shared variable value and place it in appropriate section of the Main Report based on the section in which you are displaying shared variable value of the Subreport."  (post from Poonam Thorat 7/7/08)
    This is a solution to my problem.  However, I'm not sure how to initialize the shared variable value nor do I know where to place it in the appropriate section of the main report.  Therefore, what should the formula look like and where should it go in the main report?
    Can anyone help me with this?
    Thanks much!

    Hello
    Lets say you have a report like this
    Report Header
    Page Header
    Details
    Report Footer
    Page Footer
    If you want to create and initialise a shared variable, create a formula like this
    For this example call this forumula Rate
    whileprintingrecords;
    shared numbervar Rate := 1.5; // this can also be a field
    If you needed to use this shared variable in the Details section, then you would place the Rate formula in the Report Header, or Page Header (above Details so that it is created before the Details section is created)
    In details lets say you have some other calculation - Commission
    The Commission formula would look like this
    whileprintingrecords;
    shared numbervar Rate; // a shared variable must be referenced in each formula that it will be used.  It is NOT being initialised or set to any value here, just referenced
    {table.fieldname} * Rate
    Place the Commission formula in the Details section and Rate will be for each record in the report
    The same process applies for passing values from main report to sub report and vice versa
    There is also plenty of info in the Help and online about using shared variables
    Best regards
    Patrick

  • Jdev11 complains about public instance variables, but not Jdev10

    Hi all, if I fire up Jdeveloper10 I can declare a public instance variable. (OK, stylistically maybe not a good thing, but nothing in the java 'rules' that says I shouldn't be able to do this.) However in Jdeveloper11 it complains, it underlines it in red and grumbles "should not have greater than protected access."
    Anyone know where to turn off this compiler hint?
    thanks.
    public class Thing() {
    public String bob; // complains in jdev11, ok in jdev10.

    Hi Kevin, thanks for the tip. It's taken me years just to remember where to turn on the line numbers in 'preferences' , so I would never have found that one about the instance variable checks ! Frank, thanks for the update, I agree it's useful as a stylistic hint, but I think that the Jdev floating code assist, rather than just hinting "declare this field protected" (as this will obviously fix it) would be more user-friendly if it also said "or disable under preferences - code assists." But Jdev11 is growing on me, tons of cool stuff :-)
    thanks all.

  • The shared variable does not exist????

    This seems really strange!!
    I already use several shared variables within my whole project without any problem. At this point, I created a new one (a boolean network published) and everything seemed just fine (no errors were detected in my VI and it runs normally). However, when the VI on my host computer tries to use the shared variable, it generates an error message saying "LabVIEW:  (Hex 0x8BBB0005) The shared variable does not exist." (see attached screenshot).
    What is going on? I can't find any help online about that... Can anybody help me with this please?
    Thanks!

    Hello,
    This error can occur if you have an incorrect Path specified under your Bind to Source section for the shared variable - this could be as simple as a typographical error in the defined path.  Double-check that portion of your shared variable definition, and hopefully it'll be as simple as finding a typo in your path.  You should be able to browse for your variable/path by clicking Browse and then selecting Network Items if your shared variable is on the network.  Can you find it by browsing?
    I hope this helps!
    Best Regards,
    JLS
    Message Edited by JLS on 10-05-2006 03:54 PM
    Best,
    JLS
    Sixclear

  • JDODataStoreException: The instance null does not exist in the data store

    I'm unable to figure out how this exception occurs.
    I have a class IDCounter which has a number of fields such as
    'm_Name' (String)
    'm_AccountName' (String)
    'm_UserName' (String)
    'm_Description' (String)
    'm_CreationDate' (Date)
    'm_LastModifiedDate' (Date)
    'm_DeletedDate' (Date)
    'm_Count' (long)
    The filter I'm using is "m_AccountName == \"test\" && m_UserName
    ==\"test\" && m_DeletedDate == null"
    The generated SQL statement is "SELECT t0.M_IDX, t0.JDOCLASSX,
    t0.JDOLOCKX, t0.M_ACCOUNTNAMEX, t0.M_CREATIONDATEX, t0.M_DELETEDDATEX,
    t0.M_DESCRIPTIONX, t0.M_LASTMODIFIEDDATEX, t0.M_NAMEX, t0.M_USERNAMEX,
    t0.M_COUNTX FROM ABSTRACTENTITYX t0 WHERE ((t0.M_DELETEDDATEX IS NULL) AND
    t0.JDOCLASSX = 'com.ewarna.pdm.entities.IDCounter')"
    Exception Trace:
    javax.jdo.JDODataStoreException: The instance null does not exist in the
    data store.
         at
    com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.instantiateRow(LazyResultList.java:165)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.get(LazyResultList.java:96)
         at java.util.AbstractList$Itr.next(AbstractList.java:416)
         at
    com.solarmetric.kodo.runtime.ResultListIterator.next(ResultListIterator.java:49)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.ResultListFactory.createResultList(ResultListFactory.java:85)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.executeQuery(JDBCStoreManager.java:646)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCQuery.executeQuery(JDBCQuery.java:150)
         at com.solarmetric.kodo.query.QueryImpl.executeWithMap(QueryImpl.java:580)
         at com.solarmetric.kodo.query.QueryImpl.execute(QueryImpl.java:428)
         at
    com.solarmetric.kodo.query.QueryImpl$SynchronizedQuery.execute(QueryImpl.java:1331)
         at
    com.ewarna.pdm.sessions.persistence.BasicQuery.getByAdvancedFormula(BasicQuery.java:78)
         at
    com.ewarna.pdm.sessions.persistence.BasicQuery.getByFormula(BasicQuery.java:119)
         at
    com.ewarna.pdm.sessions.persistence.BasicQuery.getByFormula(BasicQuery.java:95)
         at
    com.ewarna.pdm.sessions.persistence.BasicQuery.getAll(BasicQuery.java:131)
         at
    com.ewarna.pdm.sessions.persistence.GenericEntityManager$7.execute(GenericEntityManager.java:305)
         at
    com.ewarna.pdm.sessions.persistence.GenericEntityManager.execute(GenericEntityManager.java:251)
         ... 18 more

    Youcan no longer display a workbook. You receive an error message when opening: <Internal error>: 1201 document storage
    Cause and prerequisites
    In very rare cases, when you store a workbook, you might not be able to open it again.
    Solution
    Function module BDS_PHIOS_GET_RIGHT has to be changed so that the last available version of the Workbooks can be displayed.

  • The RPAS_HOME variable is not set

    I want to install RPAS Configuration Tools on Windows 7.
    But I received the following error
    "The RPAS_HOME variable is not set..."
    It seems, that all correct
    Maybe someone knows what to do with using cygwin?

    Hi,
    Try creating RPAS_HOME as system variable in Wiindows 7 and reboot it. This may help.
    Another solution is to invoke you program with a wrapper windows batch file which sets RPAS_HOME env variable before invoking target program.
    Let me know if you need further details.
    Regards,
    PPS

  • How can I use evaluate to get the instance variable in customized tag

    1.
    At first , I create a class called bean,and declared several params in it and do not define any getter function for the param.
    class bean{
    String param = "test";
    SomeClass scObj = new SomeClass();
    2.
    The second ,I use
    request.setAttribute("beanObj",new bean());
    3.
    And then I wanna use the customized tag to show a text box , then initialize it's value.
    <salt:text name="param" value="beanObj.param">
    <salt:text name="obj" value="beanObj.scObj.func()">
    4.
    I tried the evaluator provided by JexlContext ,Struts, JSTL and it seems that if I do not define the getter for the variable ,I can not get the bean's instance variable's value.
    Expression e = ExpressionFactory.createExpression( value );
    JexlContext jc = JexlHelper.createContext();
    jc.getVars().put(strInitBeanName, request.getAttribute("beanObj"));
    Object obj = e.evaluate(jc);
    the result of the obj is null....
    Can anybody recommand some other evaluator can get the value of a instance variable from an object?

    do you have any other suggestion ? Nops, somebody else may have though. AFAIK, all lookups of the type
    beanName.propertyNameuse reflection on the getXXX() methods to access the property.
    Having said that, I guess you could write one though in a custom tag, using the same - reflection (you will ahve to rely on the java.lang.reflect.Field class quite heavily) - but that would be reinventing the wheel for most other functionality that you would have to include (like looking up the bean in scope etc)
    cheers,
    ram.

  • How to wash out an AM instance variable at the end of user session (logout)

    We have a need to create AM instance variables to hold some session level data, which is too complex to be held in a transient VO.
    What we observed is that the instance variable is not washed out at the end of the user session (i.e logout).
    I think since the AM instance is not really destroyed but only release back to the pool the instance variable content persists and is carried over to the next session that access the AM instance.
    What method in AM can be overridden to wash out this instance variable.
    At the moment we are resetting it in prepareSession(), but this means that the information is still held till the next session access the AM.
    It would be better to reset it when the AM is released back to the pool.
    Any pointers would be helpful.

    At the moment we are resetting it in prepareSession(), but this means that the information is still held till the next session access the AM.
    Note that prepareSession() is also invoked after AM activation so this can(and probaly will) reset your variable inside existing session.
    If you don't need to keep variable value between AM activations/passivations, you can use userData, for example:
    this.getSession().getUserData().put("someKey", value);
    UserData values are lost after AM passivation (by default).
    If you need to keep UserData variable value for lifetime of user session, then you can override passivateState() and activateState() as in this sample:
    Application State Management
    Dario

  • Problem in recognising instance variables declared in the class

    Hi all,
    I am trying to deploy an Servlet desiged in WebObjects5.1 application server on application on Iplanet Application server 6.5
    Back ground: All of you might be aware that WebObjects5.1 is an J2ee compliant application server. When an application is designed in WebObjects, it creates a WAR file which can be deployed on any J2ee complaint application server.
    I tried to create such application in WebObjects and tried to deploy on IplanetApplication server6.5(running on Windows using IIS web server).
    I am able to successfully deploy the application. But inorder to do this i had to manually add ias-Web.xml file to the war file generated( gave some arbitrary global id). The aplication just consists some string displaying hello world.
    Now when i try to deploy an application which has some instance variables, the instance variables are not getting recognised. This application works fine on WebObjects5.1. But variables are not getting recognised when deployed iplanet application server
    Has any one faced such kind of problem earlier? If yes please help me out
    Thanks
    Venkatesh

    Hi,
    Please send me your servlet code and war file.
    Thanks

  • Inheritance & instance variables

    Okay, this just went against everything I thought I knew about inheritance and Java...
    So I wrote something like the code below, and when I declared
    ClassB cb = new ClassB();
    cb.variable2 was set to "". I traced it line-by-line in JBuilder's debugger, and I watched it set it to "bar" with my very own eyes, and then the tracer went to the "String variable2 = "";" line AFTER it ran the constructor. Is that supposed to happen?
    class ClassA{
         String variable1 = "";
         ClassA()
             parse();
         protected void parse()
              variable1 = "foo";
    class ClassB extends ClassA
        String variable2 = "";
        ClassB()
            super();
        protected void parse()
            super.parse();
            variable2 = "bar";

    And also: for those of you who said "never use an
    overridable method in the constructor," does this mean
    that every time you create a subclass, you must write
    a constructor that initializes all of the instance
    variables? Not exactly sure what you mean by "initializes all of the instance variables." You certainly don't need to explicitly initialize each of your object's fields in the constructor; in some cases, you won't know their values at that time.
    Doesn't this cause you to have to change all the subclasses
    individual subclasses if you ever needed to remove or change
    a superclass' instance variable (for example)?No, and this comes back to my point that a class is only responsible for the fields that it declares. If you don't try to change your superclass' fields directly, then you're not dependent on how it's implemented. Instead, you should call the appropriate superclass constructor. For example:
    public class XXX
        protected Map     _data;
        public XXX()
            _data = new HashMap();
        public XXX( Map data )
            _data = data;
    }Let's say that you now want to create class YYY, which extends XXX but uses a TreeMap instead of a HashMap. You could simply access "_data" directly; after all, it's "protected" and not "private". However, this introduces a dependency: class XXX now cannot change field "_data" without breaking class YYY. Instead, you should call the second constructor, which initializes the field from passed data:
        public YYY()
            super(new TreeMap());
        //...There are still ways that this example could break ... for example, the implementor of XXX could decide that the second constructor should copy the passed Map. There are ways to avoid this, but we won't go into those here :-)

  • BufferedReader bf;       is this also treated as instance variable?

    hi i m just now finished my assignment and doing documentation
    and i got a single line here
    BufferedReader bf; //instance variable
    constructor{
    bf = new BufferedReader(new InputStreamReader(System.in));
    }and now i m doing documentation suddenly i got confused whether i should
    write this as instance variable or not. should i?? or shouldn't i
    i think this is obejct,,,,,,,but..i think it is instance variable as well..coz
    it is located in the class scope..confusing.....
    or not..

    hi i m just now finished my assignment and doing
    documentation
    and i got a single line here
    BufferedReader bf; //instance variable
    constructor{
    bf = new BufferedReader(new
    w InputStreamReader(System.in));
    }and now i m doing documentation suddenly i got
    confused whether i should
    write this as instance variable or not. should i?? or
    shouldn't i
    i think this is obejct,,,,,,,but..i think it is
    instance variable as well..coz
    it is located in the class scope..confusing.....
    or not..Okay, first of all constructor {} isn't valid Java syntax, I'm assuming you just used it for brevity. Second, yes bf is an instance variable because it's not a) static (class-) variable or b) local variable.
    If you thought instance variables refer only to primitives (int, byte etc.) you're wrong. Object references can also be instance variables.
    So yes, it is both an object reference and an instance variable.
    Sincerely,
    Jussi

  • What's the difference between global variables and instance variables?

    hi im just a biginner,
    but what is the difference between these two?
    both i declare them above the constructor right.
    and both can access by any method in the class but my teacher said
    global variables are not permitted in java....
    but i don't know what that means....and i got started to confuse these two types,,
    im confusing.......
    and why my teacher said declaring global variables is not permitted,,,,,,
    why.....

    instance variables are kindof like Global variables. I'm not surprised you are confused.
    The difference is not in how they are declared, but rather in how they are used.
    There are two different "styles" of programming
    - procedural programming.
    - object oriented programming.
    Global variables are a term from Procedural programming.
    In this style of programming, you have only one class, and one "main" procedure. You only create one instance of the class, and then "run" it.
    There is one thread of control, which goes through various methods/procedures to accomplish your task.
    In this style of programming instance variables ARE "global" variables. They are accessible to all methods. There is only one instance of the class, and thus only one instance of the variables.
    Global variables are "bad" BECAUSE you can change them in any method you like. Even from places that shouldn't have to. Also if you use the same name as a global variable and a local variable, you can cause great trouble. This can lead to very subtle bugs, as the procedures interact in ways you don't expect.
    The preferred method in procedural programming is to pass the values as parameters to the methods, and only refer to the parameters, and local variables. This means that you can track exactly what your method is doing, and what it affects. It makes it simpler to understand. If you use global variables in your methods, it becomes harder to understand.
    So when are instance variables not global variables?
    When you are actually using the class as an Object, rather than just a program to run. If you are creating multiple instances of an object, all with different values for their instance variables, then they are not global variables. For instance you declare a Person object with an attribute "firstname". Your "main" program then creates many instances of the Person object, each with their own "firstname"
    I guess at the end of all this, it comes down to definitions.
    Certainly you can write procedural code in java. You can treat your instance variables, for all intents and purposes like global variables.
    I can only think to show a sort of example
    public class Test1
       User[] users;
       public void printUsers(){
         // loop through and print all the users
         // uses a global variable
          for(int i=0; i<users.length; i++){
            users.printUser();
    public void printUsers(User[] users){
    // preferred method - pass it the info it needs to do the job
    for(int i=0; i<users.length; i++){
    users[i].printUser();
    public Test1(){
    User u1 = new User("Tom", 20);
    User u2 = new User("Dick", 42);
    User u3 = new User("Harry", 69);
    users = new User[3];
    users[0] = u1;
    users[1] = u2;
    users[2] = u3;
    printUsers();
    printUsers(users);
    public static void main(String[] args)
    new Test1();
    class User{
    String firstName;
    int age;
    public User(String name, int age){
    this.firstName = name;
    this.age = age;
    public void printUser(){
    // here they are used as instance variables and not global variables
    System.out.println(firstName + " Age: " + age);
    Shit thats a lot of typing, and I'm not even sure I've explained it any good.
    Hope you can make some sense out of this drivel.
    Cheers,
    evnafets

  • How to fail the task sequence if an MDT variable is not populated?

    We are deploying Windows 7 using ConfigMgr 2012 SP1 CU3 integrated with MDT 2012 Update 1 using the MDT database locations table to populate the MachineObjectOU MDT variable.
    Currently the "Apply Network Settings" task will read the MachineObjectOU variable and add the computer account to the OU returned by the MDT database query.  If no value is returned it will not domain join the computer, instead it continues
    the task sequence and configures the machine as a workgroup machine.
    I would like the task sequence to fail if the MachineObjectOU variable is not populated by the MDT database query instead of continuing as a workgroup build.  What is the easiest way to do this?
    Thanks!
    FP

    I agree. 
    I would write a script that reads the Variable and checks that it has a valid content. 
    If it doesnt i would return an exitcode from my script and have the TS fail on that

  • Could not able to startup the instance

    After shutdown the instance, I could not able to starup the instance. ORA-12203 TNS:UNABLE TO CONNECT TO DESTINATION ,error showing. Database already down, then how to make to startup.

    ORA-12203: TNS:unable to connect to destination
    Cause:      Invalid address specified or destination is not listening. This error can also occur because of underlying network or network transport problems.
    Action:      Verify that the net service name you entered was correct. Verify that the ADDRESS portion of the connect descriptor which corresponds to the net service name is correct. Ensure that the destination process (for example the listener) is running at the remote node.
    Connect with your server. Export ORACLE_HOME and ORACLE_SID. Then login with SQLPLUS as sysdba and startup the instance.
    Regards
    Asif Kabir

  • Binding: Instance variable loses value.

    Hi all,
    Just making my first steps into Objective-C, I've done a lot of C, C++ and C# on win & linux. Anyhow, I've been hacking away happily and discovered a peculiar behaviour, and I'm not sure if it's my code or some obscure bug in Xcode.
    1. I have a Check Box(NSButton) directly bound to a BOOL instance variable called "checkValue" using KVC. The containing class is a custom NSView subclass.
    2. I manually implemented the setter according to KVC naming rules "setCheckValue".
    3. When debugging the UI (check box) calls the setter perfectly with the correct value, which shows up in the NSLog output.
    4. I hooked up the action for the check box as well, and inside the action handler the instance variable reports the value correctly. Everything looks fine.
    5. Now here's the rub. I put a mousedown event handler into the class as well, and it is called flawlessly when I click on the custom view. However, "checkValue" does not report the correctly set value.
    So, how can a class instance variable, which is set and reports correctly elsewhere in the same scope, all of the sudden take on a nonsense value in a event handler? If a variable has a value set, it should be the same everywhere within the same scope!
    Below is simplified code extracted from the original project for clarity. It produces exactly the same behaviour as the more complex project without the distracting code.
    #import "CheckBoxHandler.h"
    @implementation CheckBoxHandler
    @synthesize checkValue;
    //Apparently this is required for binding in NSView based classes
    //The same behaviour occurs even if you remove this.
    +(void)initialize
    [self exposeBinding:@"checkValue"];
    -(id)initWithFrame:(NSRect)frameRect
    self = [super initWithFrame:frameRect];
    if(!self)
    return nil;
    [self setCheckValue:YES];
    return self;
    //manual impelementation of KVC setter
    -(void)setCheckValue:(BOOL)v
    checkValue = v;
    NSLog(@"Setter Called: checkValue is %d", checkValue);
    //The action works fine as evidenced by Log output
    //Check and uncheck the box a few times.
    -(IBAction)checkBoxAction:(id)sender
    NSLog(@"UI State:%d Ivar State: %d", [checkBox state], checkValue);
    //Mouse clicking on the view calls into this event.
    //The problem is the value reported by [self checkValue] OR checkValue directly
    //do not match the UI state. In fact it always reports some nonsense value.
    -(void)mouseDown:(NSEvent *)event
    NSLog(@"Inside Mousedown: checkValue is: %d", [self checkValue]);
    @end
    I have a workaround, but it really bends my head when something doesn't behave as expected!

    I have synthesized against "checkValue", although I manually implemented the setter so I could set a breakpoint and observe the value. I thought [self checkValue] and self.checkValue both simply call the same getter, just different syntax.
    The setting of the value using the UI checkbox happens outside of the event call chain. I can check and uncheck the checkbox and the value changes correctly. The checkbox is in a separate space on the window, so clicking it does not activate mousedown on the view, this is correct behaviour. Clicking on the view does activate the mousedown event, this is done after I've set the checkbox so the value has been set well before the mousedown event. Thus it should already have the correct value in the event.
    For completeness this is the interface file:
    #import <Cocoa/Cocoa.h>
    @interface CheckBoxHandler : NSView {
    IBOutlet NSButton *checkBox;
    BOOL checkValue;
    -(IBAction)checkBoxAction:(id)sender;
    @property (assign, readwrite) BOOL checkValue;
    @end
    I'll change everything to self.checkValue just for the excercise. Ok, done. checkValue still reports a value of 1 in the mousedown event regardless of the value set elsewhere.

Maybe you are looking for