About static variable initialization

Here is an exercise where you have to guess the output :-)
public class MyClass{
    private static int x = getValue();
    private static int y = 5;
    private static int getValue(){
        System.out.print("Running getValue ");
        return y;
    public static void main(String[] args){
        System.out.println(x);
}This code outputs "Running getValue 0" I don't understand why?

because class initialisation will call getValue() before it initialises 7 to 5, thus setting x to the value y has before being initialised which is 0.
What this tells you is that you should never program rubbish like that, and in general not rely on the value of uninitialised members.

Similar Messages

  • Clarification about static variables declaration

    I'm getting "Illegal Start of Expression" error, When i try to declare a static variable within a static metho or nonstatic method.
    Could you please clarify me,
    Is it possible to declare a static varible within a static method or non static method ?
    Thanks

    Hi Vikas,
    First, note that this forum is devoted to Sun Java Studio Creator IDE. General Java questions can be asked on forums here: http://forum.java.sun.com/
    Second, note that static variable can be defined only as member of class. It cannot be defined inside of method.
    Thanks, Misha
    (Creator team)

  • A basic question about static variables and methods

    What would be the effects if I declare lots of static variables and static methods in my class?
    Would my program run faster?
    Would the class take more memory spaces? (If so, how do I estimate an appropriate number of variabls and methods to be declared static?)
    Thank you @_@

    when you declare a static var the var isn't created for every instance of the class, it just "live" in the class
    when you declare a static method is the same, so if you have:
    class MyClass
    static int myMethod()
    //Method work
    you dont need to have a instance of the class to call myMethod, you can do such things like this.
    int value = Myclass.myMethod();
    if myMethod isn't static you can't do this.. so, if
    class MyClass
    int myMethod()
    //Method work
    you CAN'T call
    int value = MyClass.myMethod();
    instead, you have to write
    MyClass m;
    m = new MyClass();
    value = m.myMethod();

  • About  static variable

    anybody can tell why the answer is B,? i think it should be D.
    thanks
    1. public class test (
    2. private static int j = 0;
    3.
    4. private static boolean methodB(int k) (
    5. j += k;
    6. return true;
    6. )
    7.
    8. public static void methodA(int i) {
    9. boolean b:
    10. b = i < 10 | methodB (4);
    11. b = i < 10 || methodB (8);
    12. )
    13.
    14. public static void main (String args[] } (
    15. methodA (0);
    16. system.out.printIn(j);
    17. )
    18. )
    What is the result?
    A. The program prints �0�
    B. The program prints �4�
    C. The program prints �8�
    D. The program prints �12�
    E. The code does not complete.
    Answer: B

    Because the boolean OR (||) in java short-circuits.
    since the first part of this expression:
    b = i < 10 || methodB (8); is true, the second part (the call to methodB() is never excecuted.
    ~Tim
    (the boolean OR (|) is the non-short-circuiting version)

  • (JC) static variable and derived object

    Hi there!
    It is glad to know you from Java Card Forum. Can I ask for your help on the following question?
    It is about static variable. The following is my sample code:
    ========================================
    package com.Test01;
    import javacard.framework.*;
    import javacard.security.*;
    import javacardx.crypto.Cipher;
    public class Test01 extends Applet {
    OwnerPIN Pin;
    static DESKey[] keys;
    protected Test01(byte[] buffer, short offset, byte length) {
    keys = new DESKey[4];
    length = 0;
    while (length < 4) {
    keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);
    length = (byte)(length + 1);
    public static void install(byte buffer[], short offset, byte length) {
    new Test01(buffer, offset, length);
    ===========================================================
    If there are two instances, A and B, created in the package.
    My issues:
    1. Are keys[0]~ keys [3] kept while B is deleted?
    2. Does each instance have itsown object while "keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);"? or they share the same object?
    3. follow item 2, if A and B share the same object, is the object kept while B is deleted? Where can I get the information in Sun's spec?
    Thank you very much.
    Best regards,
    kantie

    Thanks a lot. You mean that keys variable will be removed while instance B deleted, right? I think the idea of database applet is very good, but I can't force applet provider the way of their implementations : )
    I still got question, does it get no use to set the keys variable to be "static"? So that I can keep it to other instances, if applied.
    And I think that any object derived under the static variable shall be kept, until the package is deleted.
    For example, if you declare a static pointer, and it points to an object newed by the instance at the first time. We say every instances (A and B) of this package (PckM) share this same static pointer and this same object, right? There are two situations:
    1. if this referred object is removed when B is deleted, so the memory of this object will be released. Then user might create an instace C of another package (PckN), and instance C new its objects just overlapping on the released memory. In this case, it will cause instance A to be crashed, because its static pointer has been referred to illeagle address.
    2. if this referred object is kept when B is deleted, then instance C will new its objects in other free memory. In this case, instance A will work well, because its static pointer still refers to correct object.
    What do you think? Am I missing any concepts?
    Thank you for your great opinions.
    Best regards,
    kantie

  • How to load value to a static variable on the run

    hi all
    i have a question about static variable. i need to have a variable to keep a value from DB shared by all instances. the variable is given value when the first instance is created. but from time to time, the value in DB may change, but i still need to maintain this shared value among instances. the static variable has life time as long as the program runs, does that mean if i need to change the value, i need to stop the program, and restart to load the new value? thanks.

    can the static variable be accessed within a
    non-static method, for instance, set the value by
    setXXX() method?Yes, and oddly enough, that usually how I access all my variables...
    Example...
    public class StaticTester {
           static String theString = " My Message ";
           public void setMessage(String mess){
                      theString = mess;
           public String getMessage(){
                      return theString;
           public static void main(String[] theArgs){
                      StaticTester myTest = new StaticTester();
                    System.out.println(myTest.getMessage());
                    myTest.setMessage(" a New Message ");
                 System.out.println(myTest.getMessage());
    }Hope this helps...
    - MaxxDmg...
    - ' He who never sleeps... '

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • Loading the final static variables at run time.. Please help

    Hello, fellow developers & Gurus,
    Please help me figure out the best way to do this:
    I need to load all my constants at run time. These are the public static final instance variables. The variables values are in the DataBase. How do I go about loading them.

    Your original question was diffeent, but your further posts show what you really want to do:
    1) all constants in 1 class
    2) available readonly for other classes
    3) updatable during runtime by changing in the database
    Did I understand you right?
    Then smiths' approach solves point 2):
    Instead, make the variables available through a method
    call - that way you avoid the whole final variable
    versus read-only attributes problem.
    //GLOBAL VARIABLES EXPOSED AS PUBLIC PROPERTIES
    public final class GlobalProperties
    public static int getTableSize();
    public static int getRowSize();
    Each "constant" should be a private static variable, and these methods simply return their values.
    The variables are initialized in a static initializer by accessing the db. Ok.
    You habe a table with one row containing as columns all the constants.
    A method readConstants() does a "select constant1, constant2, ... from const_table" and sets all the variables.
    The static initializer calls this method.
    Right?
    Ok, then you simply call readConstants() everytime you want to synchronize with the actual content of const_table.
    Was it this?

  • Shared java static variables

    I have an application where I would like to
    read from some small configuration tables
    and cache them into java variables, in order to avoid each stored procedure call to redo
    those queries. The configuration data is
    pretty static, so I don't worry about refresh
    problems.
    My first attempt to do that was using static
    final variables (like Vector). In our oracle
    environment however (8.1.7) each session
    seems to have its own copy of static final
    variables, resulting in each session to
    perform those queries for initializing all
    over again.
    firstly, i would like to find out if there is another way to share this data among java
    sessions, but otherwise I am curious how
    I can get the claims made in http://technet.oracle.com/products/oracle8i/pdf/8ir2java.pdf , page 6 to work.
    Specifically, here is what the document says:
    "In Oracel8i Release 2, JServer introduces the concept of "hotloaded" classes. Various core classes that
    initialize static variables known to be constant are pre-initialized during database creation time. When you use
    one of these classes in your program, the class loader loads the pre-initialized form. In many cases, the time
    required to initialize the static variables is itself quite significant, and now with the introduction of hotloaded
    classes that time is completely eliminated. In addition, the objects in these particular static variables are shared
    among all sessions. Hotloaded classes therefore improve performance by eliminating class initialization and
    they reduce per-user-session footprint by increasing the amount of data shared between sessions. Hotloaded
    classes provide improved performance and scalability "for free", with no user intervention. "
    the kind of initialization I have been
    trying is like:
    public static final int inti = func();
    this also didn't seem to work:
    public static final int inti;
    static {
    inti = ....;
    thanks,
    null

    I have an application where I would like to
    read from some small configuration tables
    and cache them into java variables, in order to avoid each stored procedure call to redo
    those queries. The configuration data is
    pretty static, so I don't worry about refresh
    problems.
    My first attempt to do that was using static
    final variables (like Vector). In our oracle
    environment however (8.1.7) each session
    seems to have its own copy of static final
    variables, resulting in each session to
    perform those queries for initializing all
    over again.
    firstly, i would like to find out if there is another way to share this data among java
    sessions, but otherwise I am curious how
    I can get the claims made in http://technet.oracle.com/products/oracle8i/pdf/8ir2java.pdf , page 6 to work.
    Specifically, here is what the document says:
    "In Oracel8i Release 2, JServer introduces the concept of "hotloaded" classes. Various core classes that
    initialize static variables known to be constant are pre-initialized during database creation time. When you use
    one of these classes in your program, the class loader loads the pre-initialized form. In many cases, the time
    required to initialize the static variables is itself quite significant, and now with the introduction of hotloaded
    classes that time is completely eliminated. In addition, the objects in these particular static variables are shared
    among all sessions. Hotloaded classes therefore improve performance by eliminating class initialization and
    they reduce per-user-session footprint by increasing the amount of data shared between sessions. Hotloaded
    classes provide improved performance and scalability "for free", with no user intervention. "
    the kind of initialization I have been
    trying is like:
    public static final int inti = func();
    this also didn't seem to work:
    public static final int inti;
    static {
    inti = ....;
    thanks,
    null

  • Question about static properties in implementation (.m) file

    I've been using some static properties in my implementation files so they can be accessed by class methods like so for example:
    #import etc
    static Class foo; // <-- Here is where I've been defining static properties
    @implementation Bar
    - init {
    foo = [Class new]; // initialize property
    + getObject { // now any where else in my code I can use [Foo getObject]
    return foo;
    - dealloc {
    [foo release];
    I've been doing this so that in other classes, I can simply go like:
    [Foo getObject]
    Can someone give me some more details about what's going on here though? It's been working but I'm nervous because I don't know much about it.
    ie. What kind of property is it? (nonatomic, retain)? Is this bad practice?
    Thanks to anyone who can shed some light on this.

    First off, it's not a property. It's a static variable. And the code you have isn't a good idea. Static variables should NOT be set via instance methods.
    Think about the following code:
    // In some other class
    Bar x = [[Bar alloc] init];
    Bar y = [[Bar alloc] init];
    Think about what just happened. In the 'foo' class you have now created two 'foo' objects and the first one is now leaked.
    The proper way to initialize static variables is with the 'initialize' class method. This is only ever called once, the first time the class is referenced.
    static Class foo;
    @implementation Bar
    + (void)initialize {
    foo = [[Bar alloc] init];
    - init {
    // Do nothing with 'foo'
    + (Bar)getObject {
    return foo;
    - (void)dealloc {
    // Do nothing with 'foo'
    The only downside, sort of, is that 'foo' is never dealloc'ed except when the app exits. But this isn't typically a problem.

  • JUnit Test Debug: Static variable lost value!!!

    Hi, I am writing JUnit code.
    env: JDeveloper + JUnit Plugin + Selenium RC
    While I am debugging, I found the static variable lost between 2 different test, I mean a test is a @Test, do somebody know why??
    Thank you very much!!

    1.) The File you initialize in the method is not the same as the instance file variable that you initially initialized to null. You declared a new File in that method.
    2.) Read about layout managers. The behavior you are seeing is because of the default layout manager's behavior.

  • Local static variable not unique between dylib, Xcode 4.4.1 bug?

    I am wondering if this is a Xcode bug or it is the way the c++ standart is.
    I would expect to  see 1 in the console but i see 0.
    Anybody know why? Here is the code
    In one dylib I have
    // Header file
    class Foo {
       int i_ = 0;
       Foo(const Foo&) = delete;
       Foo& operator= (Foo) = delete;
       Foo()
    public:
       void inc()
          ++i_;
       int geti()
          return i_;
       static Foo& get()
          static Foo instance_;
          return instance_;
       Foo( Foo&&) = default;
       Foo& operator= (Foo&&) = default;
    int initialize()
       Foo::get().inc();
       return 10;
    class Bar
       static int b_;
    // cpp file
    #include "ClassLocalStatic.h"
    int Bar::b_ = initialize();
    and in my application project i have
    // main.cpp
    #include <iostream>
    #include "ClassLocalstatic.h"
    int main(int argc, const char * argv[])
       std::cout << Foo::get().geti();
       return 0;
    Thanks

    thanks for your answer, You are right there is 2 foo singleton at different memory addresses.
    I didn't think about when the dylib was loaded. I can't even tell when it is loaded. But I know if i but breaks point I break in the initialize function before breaking in main, but that might be because of this actual setup. So when does a dylib will be loaded? At the first call a program sees that need the dylib?
    Here I'explain why it is done this way. My Singleton is a UnitTestRegistry, the Bar class is a UnitTest class and the static variable b_ is a class containing metadata info on the unit test.
    I have a macro to define the unit test it is called Make_UnitTest()
    So in a cpp I do
    Make_UnitTest(MyTest)
         // Test Stuff
    The macro will get expanded to
    class MyTest_UnitTest: public UnitTestBase
         static UniTestMetaData b_;
         virtual void executeTest();
    int MyTest_UnitTest::b_ = initializeAndRegisterUnitTest("MyTest_UnitTest", factoryFunction);
    MyTest_UnitTest::executeTest()
    // Test Stuff
    And in the function initializeAndRegisterUnitTest I call the getInstance of the unit test  registry. This way my unit test are registred at loading time of the program/dll. If you know a better way to automatically register (i know it cuold be manual but i find it too cumbersome), but it wont fix the problem which is that I have two intance of my singleton because the function is inline in a header.
    Well this behavior is surprising to me, I didn't know it would do this. But hey it is good to learn right!
    Just to make it clear there is no real global!! The singleton is like a global but it is not completly one and the b_ is certainly not global it is a class static memeber...

  • Error on compile - non-static variable can not be referencedfrom static con

    Error on compile happening with addButton?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    public class Log implements ActionListener {
    JButton addButton;
    public static void addComponentsToPane(Container pane) {
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
         c.gridy = 3;
    c.gridx = 0;
         JLabel callsignLabel= new JLabel("Callsign");
    pane.add(callsignLabel, c);
         c.gridy = 3;
    c.gridx = 1;
         JLabel nameLabel= new JLabel("Name");
    pane.add(nameLabel, c);
         c.gridy = 3;
    c.gridx = 2;
         JLabel timeLabel= new JLabel("Time");
    pane.add(timeLabel, c);
         c.gridy = 3;
    c.gridx = 3;
         JLabel dateLabel= new JLabel("Date");
    pane.add(dateLabel, c);
         c.gridy = 3;
    c.gridx = 4;
         JLabel frequencyLabel= new JLabel("Freq ");
    pane.add(frequencyLabel, c);
         c.gridy = 3;
    c.gridx = 5;
         JLabel locationLabel = new JLabel("Country/State");
    pane.add(locationLabel, c);
    c.gridy = 5;
    c.gridx = 0;
         addButton = new JButton("Add");
    pane.add(addButton, c);
         addButton.addActionListener(this);

    Thank you for the reply
    I am new to Java
    What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
    If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again.

  • Non-static variable being used in static context

    I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
    What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
    However when i try to compare the string in the file with the one in the text field using the following code:
    if ((line.compareTo(username)) == 0)
    i get the following error...
    "non-static variable being used in a static context"
    Any ideas?

    The static method doesn't know about instances of the class instead you pass the instance to the method:
    static public void myMethod(MyClass instance, String var) {
      if(instance.line.compareTo(var))
    And then the call would be:
    MyClass.myMethod(anInstance, userName);

  • To use a static variable in another class,but report NullPointerException

    when TableMain is running,I run testRecord so that let TableMain add a occur informatin and
    happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping me to check my code;(error report info is in end)
    import java.awt.event.*;
    import javax.swing.table.*;
    import java.io.*;
    public class TableMain extends JFrame{
    JTable table;
    static OwnModel model;
    String[] columnHeader={"occur","time"};
    class OwnModel extends DefaultTableModel{
    public OwnModel(Object[] columnNames,int numRows){
    super(columnNames,numRows);
    public boolean isCellEditable(int row,int column){
    return false;
    public TableMain(){
    model=new OwnModel(columnHeader,0);
    table=new JTable(model);
    JScrollPane scroll=new JScrollPane(table);
    JButton save=new JButton("save record");
    JButton delete=new JButton("delete record");
    JPanel buttons=new JPanel();
    buttons.add(save);
    buttons.add(delete);
    JLabel sign=new JLabel("occur record");
    Container cp=getContentPane();
    cp.add(BorderLayout.NORTH,sign);
    cp.add(BorderLayout.CENTER,scroll);
    cp.add(BorderLayout.SOUTH,buttons);
    this.setSize(300,500);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String[] args){
    new TableMain();
    import java.util.Vector;
    import java.util.Calendar;
    import java.text.SimpleDateFormat;
    public class testRecord{
    public static void main(String[] args){
    SimpleDateFormat simpledf=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    String tableName="friends";
    Calendar occurtime=Calendar.getInstance();
    Vector record=new Vector();
    record.add("send 'desc' sql, "+"operated table is :"+tableName);
    record.add(simpledf.format(occurtime.getTime()));
    System.out.println("model is "+Guide.model);
    System.out.println("record is "+record);
    Guide.model.addRow(record);
    error report:
    model is null
    record is [send 'desc' sql,operated table is :friends, 2004/05/26 11:39:03]
    Exception in thread "main" java.lang.NullPointerException
    at testRecord.main(testRecord.java:14)

    but I just use this constructor once,never use twice
    with same jvm;I thinks my idea is not too very badIt's a public constructor (if I'm looking in the right
    place) - it could be called from anywhere. To
    intialize a static variable outside the declaration,
    use a static initializer:private static String whatever;static {
    whatever = "whatever";
    }Or simply (in this case):private static String whatever = "whatever";

Maybe you are looking for

  • Photos syncing from folder to iPhone all out of order?

    I have 2 folders synced to my iPhone 4 photo app. They were previous camera rolls before I set up my phone as a new device. They are all named in order and taken in order, for example IMG_001.jpg was my first picture in my old camera roll. IMG_822.jp

  • My device is not recognized by my computer

    My computer is not recognizing the device I plagged in.  It's an ipod nano 7th. for a month no trouble till now. Got a new cord and still same problem. Any ideas on what to do?

  • Made trouble for myself by moving data folder.  Need help to fix.

    I did something that was not smart. I was trying to access photos via online and I moved my iphoto data folders to the desktop. Now, I don't know how to move the data folder back and I don't want to screw it up even worse. If I go into iphoto the thu

  • JDBC connection issue with multiple DBs on same instance

    I have two databases on one sql server 2012 instance.  One called 'demotime' the other called 'demotime_dev'.  how ever when I change in my JDBC connection the DB from demotime to demotime_dev.  the connection still remains established with the demot

  • Using Flash to load a .mov

    I have a 126MB quicktime file for using on the web. In order for it to display correctly, it needs to be fully loaded first. Can I use Flash to display a "Loading" message and status bar for this purpose? Here it is: http://sgww.org/miracle/share/pre