(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

Similar Messages

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • 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();

  • Dynamic Variables and New-Object - in a GUI

    so, i have not found anything that i can parlay into a solution for what i am attempting to do.  
    Basically i am using powershell to build a GUI to manage websites on various servers.  
    in a nutshell:
    - i have an array with the servers i want to query
    - a foreach loop gets me the site names for each server (number of sites can vary on a server).
    - need put checkboxes on a GUI for every site to do something (25-30 sites across 8 servers).
    currently i am passing the $dir.name variable to a function that will create the new variable using this command:
    $pName = $dir.name New-variable -name $pName -value (New-Object System.Windows.Forms.CheckBox)
    $pName.Location -value (New-Object System.Drawing.Size(10,$i))
    $pName.Size -value (New-Object System.Drawing.Size(100,20))
    $Pname.Text -value $dir.name
    $groupBox.Controls.Add($pName) 
    Problem is i am not able to do anything with my newly created variable.  I am trying to use the following code to position the new checkbox but i get nothing (same for text, size, etc.)  I am not seeing any errors, so i don't know what i have going
    wrong.  
    is this even possible?
    I am able to create static checkboxes, and i can create dynamic variables.  But i can't mix the two...

    Here is how we normally use listboxes to handle form situations like this one.  The listboxes can automatically select subgroups.
    The hash of arrays can be loaded very easily with a script or the results of the first list can be used to lookup and set the contents of the second.
    Notice how little code is actually used.  This is all of the setup code needed aside from the from definition:
    $FormEvent_Load={
    $global:serversToSites=@{
    Server1=@('S1_SITE1','S1_SITE2','S1_SITE3')
    Server2=@('S2_SITE1','S2_SITE2','S2_SITE3')
    Server3=@('S3_SITE1','S3_SITE2','S3_SITE3')
    $listbox1.Items.AddRange($serversToSites.Keys)
    $listbox1_SelectedIndexChanged={
    $listbox2.Items.Clear()
    $listbox2.Items.AddRange($global:serversToSites[$listbox1.SelectedItem])
    $listbox2_SelectedIndexChanged={
    [void][System.Windows.Forms.MessageBox]::Show($listbox2.SelectedItem,'You Selected Site')
    Here is the complete demo form:
    [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $listbox2 = New-Object 'System.Windows.Forms.ListBox'
    $listbox1 = New-Object 'System.Windows.Forms.ListBox'
    $buttonOK = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    $FormEvent_Load={
    $global:serversToSites=@{
    Server1=@('S1_SITE1','S1_SITE2','S1_SITE3')
    Server2=@('S2_SITE1','S2_SITE2','S2_SITE3')
    Server3=@('S3_SITE1','S3_SITE2','S3_SITE3')
    $listbox1.Items.AddRange($serversToSites.Keys)
    $listbox1_SelectedIndexChanged={
    $listbox2.Items.Clear()
    $listbox2.Items.AddRange($global:serversToSites[$listbox1.SelectedItem])
    $listbox2_SelectedIndexChanged={
    [void][System.Windows.Forms.MessageBox]::Show($listbox2.SelectedItem,'You Selected Site')
    $Form_StateCorrection_Load=
    #Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
    $form1.Controls.Add($listbox2)
    $form1.Controls.Add($listbox1)
    $form1.Controls.Add($buttonOK)
    $form1.AcceptButton = $buttonOK
    $form1.ClientSize = '439, 262'
    $form1.FormBorderStyle = 'FixedDialog'
    $form1.MaximizeBox = $False
    $form1.MinimizeBox = $False
    $form1.Name = "form1"
    $form1.StartPosition = 'CenterScreen'
    $form1.Text = "Form"
    $form1.add_Load($FormEvent_Load)
    # listbox2
    $listbox2.FormattingEnabled = $True
    $listbox2.Location = '237, 26'
    $listbox2.Name = "listbox2"
    $listbox2.Size = '120, 134'
    $listbox2.TabIndex = 2
    $listbox2.add_SelectedIndexChanged($listbox2_SelectedIndexChanged)
    # listbox1
    $listbox1.FormattingEnabled = $True
    $listbox1.Location = '13, 26'
    $listbox1.Name = "listbox1"
    $listbox1.Size = '120, 134'
    $listbox1.TabIndex = 1
    $listbox1.Sorted = $true
    $listbox1.add_SelectedIndexChanged($listbox1_SelectedIndexChanged)
    # buttonOK
    $buttonOK.Anchor = 'Bottom, Right'
    $buttonOK.DialogResult = 'OK'
    $buttonOK.Location = '352, 227'
    $buttonOK.Name = "buttonOK"
    $buttonOK.Size = '75, 23'
    $buttonOK.TabIndex = 0
    $buttonOK.Text = "OK"
    $buttonOK.UseVisualStyleBackColor = $True
    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    #Show the Form
    $form1.ShowDialog()
    You can easily substitute  CheckedListbox if you like checkboxes.
    ¯\_(ツ)_/¯

  • "requires unreachable" warning emitted when using static variables and the singleton pattern

    I'm implementing code contracts on an existing code base and I've come across this situation in a few places. Wherever we have additional logic with code contracts where a singleton instance is instantiated, all code contracts emit a "reference use
    unreached", or "requires unreachable" warning.
    The code below demonstrates this.
    static string instance = null;
    static string InstanceGetter()
    if (instance == null)
    instance = "initialized";
    AdditionalLogic(instance); // requires unreachable warning on this line
    return instance;
    static void AdditionalLogic(string str)
    Contract.Requires(str != null);
    Console.WriteLine(str);

    Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
    On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
    To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
    *2.17.8 Unloading of Classes and Interfaces*
    A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
    Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
    The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
    Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader.

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Static variable and non-static

    I have a quick question. The following syntax compiles.
    private String t = key;
    private static String key = "key";
    But this doesn't compile.
    private String t = key;
    private String key = "key";
    Can anybody explain how it is treated in java compiler?
    Thanks.

    jverd wrote:
    doremifasollatido wrote:
    I understand that completely. I didn't say that the OP's version with static didn't work. I was just giving an alternative to show that you don't need static, if you change the order that the instance variables are declared.My problem with the underlined is that, while technically true, I can see where a newbie would take it as "oh, so that's how I can get rid of static," and focus only on how to satisfy the compiler, rather than on learning a) when it's appropriate to make something static or not from a design perspective, and b) what the implications of that decision are, for both static and non.
    I have just a wee bit of a prejudice against the "what do I type to make the error messages go away" approach. :-)That sounds good to me. We're currently trying to fix an issue caused by the fact that one class has most of its variables as static, when they should really be instance variables. There should only be one active instance of this class at a time, but the values of the static variables stick around when you call "new ThisClass()". So, old data interferes with new data, and various errors happen. The class has many static methods to access the static variables, but it should have been more of a Singleton--an actual object with non-static variables. The active instance of the Singleton would need to be replaced at logout/login (as opposed to shutdown completely and restart the JVM), but then at least when the new instance were created, then all of the variables would be initialized to empty--the old instance would disappear. The solution at the moment (solution by others--I don't agree) is to clear each static Vector and then set the reference to null (setting to null would be enough to drop the old data, but certain people don't get that...). This is fragile because many variables were missed in this "cleanup" process, and it will be easy to forget to "cleanup" new variables in the future. This class has been misdesigned for years (much longer than I've been here). The calls to static methods permeate the application, so it isn't easy to fix it quickly. There are several of these misdesigned classes in our application--a mix of static and non-static, when nothing or almost nothing should be static.

  • Best Practice:  Using a static variables and methods vs singleton pattern

    Just curious, since when anything, within a class, is denoted as static it typically will be stored in main memory as a class property(method, variables, etc). Is it a good practice to be doing this all the time or is the singleton pattern a better choice. Please explain why. Thanks.

    I wouldnot make anything other than the constants and the instance itself static. And I cant think of a reason wjy one would.

  • Static variables and JAR files problem

    Hello All,
    I am trying to get two applets to communicate.
    Both are held in the same JAR file loaded from the same location. The JAR file also contains a class with some static variables which are used to comunicate between the two applets.
    The applets are on separate frames in the browser and the system works fine when I don't use a JAR file but when I put the class files into a JAR file, each applet has it's own static variables (not very static).
    Can anyone tell me why static variables stop working when the code is loaded from a JAR file.
    Thanks in advance,
    Alastair.

    Ok,
    I've just tried the below setup and I get the following security exception:
    java.security.AccessControlException: access denied (java.util.PropertyPermission java.home read)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
    at java.lang.System.getProperty(Unknown Source)
    at sun.plugin.security.PluginClassLoader.getPermissions(Unknown Source)
    at java.security.SecureClassLoader.getProtectionDomain(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at appSend.init(appSend.java:62)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    I now have one JAR file which contains the two classes.
    appSend.class & appReceive.class
    and a separate details.class file
    The two HTML files are in separate folders but the JAR file is still the same for both.
    Classes\ -> contains the JAR file (myCode.JAR) and details.class
    Sender\ -> contains the HTML file appSender.html (see below for
    Applet tag)
    Receiver\ -> contains the HTML file appReceiver.html (see below for
    Applet tag)
    appSender.html
    <HTML>
    <HEAD>
    </HEAD>
    <BODY BGCOLOR="000000">
    <CENTER>
    <APPLET
    name = "appSender"
    code = "appSend.class"
    archive = "myCode.JAR"
    codebase = "../Classes"
    width = "500"
    height = "300"
    >
    </APPLET>
    </CENTER>
    </BODY>
    </HTML>
    appReceiver.html
    <HTML>
    <HEAD>
    </HEAD>
    <BODY BGCOLOR="000000">
    <CENTER>
    <APPLET
    name = "appReceiver"
    code = "appReceive.class"
    archive = "myCode.JAR"
    codebase = "../Classes"
    width = "500"
    height = "300"
    >
    </APPLET>
    </CENTER>
    </BODY>
    </HTML>
    Is this how it should be? or have I made a mistake with the tags?
    Can the ClassLoaders in either applet see the details.class file through the codebase tag?
    I'm guessing from the security exception that the ClassLoader for each applet can only load classes from within the JAR file? and can't just use the codebase tag, which is not very helpful!
    Thanks for your help so far.
    Regards,
    Alastair.

  • Modifying static variable in 1object dosent effect value in another object

    Hi,
    I have a simple class that declares a static variable x...
    class DeclareStatic
         static int x = 10;
    }I have another class that modifies this static variable (x)...
    class ModifyStatic
         public static void main(String[] Args)
              DeclareStatic.x = 20;
    }The problem I have is when I run the next class to simply print out the static variable x, I get 10 (the originally assigned value), not 20 (the modified value)...
    class StaticTest
         public static void main(String[] Args)
              System.out.println(DeclareStatic.x);
    }It is my understanding that by definition of being static, there is only 1 copy of this static variable(x), shared amongst all objects. Therefore, when I attempt to modify this value with a direct reference (DeclareStatic.x =20;), why isn't the change refelected in other classes which access the variable?
    This also leads to the question how DO I modify a (non final) static variable from an object and have the change reflected in all other objects?
    I have spent some time researching this on-line and in my java books to no avail, any help is greatly appreciated as I am studying to sit the SCJP and attention to detail is everything!
    Thanks,
    Alan Kilbride ;o)

    Hi,
    I have a simple class that declares a static variable
    x...
    class DeclareStatic
         static int x = 10;
    }I have another class that modifies this static
    variable (x)...
    class ModifyStatic
         public static void main(String[] Args)
              DeclareStatic.x = 20;
    }The problem I have is when I run the next class to
    simply print out the static variable x, I get 10 (the
    originally assigned value), not 20 (the modified
    value)...
    class StaticTest
         public static void main(String[] Args)
              System.out.println(DeclareStatic.x);
    }It is my understanding that by definition of being
    static, there is only 1 copy of this static
    variable(x), shared amongst all objects. Therefore,
    when I attempt to modify this value with a direct
    reference (DeclareStatic.x =20;), why isn't the
    change refelected in other classes which access the
    variable?Because your test code never makes a reference to the ModifyStatic class. You could delete ModifyStatic from your system and the code would run exactly the same.
    Jim S.

  • BPEL and Static variables

    Hi all,
    does anyone know how to define/use static variables inside a BPEL process? Or, is there any way so I can keep data from a (synchroneous) invocation to be used during the next (synchroneous) invocation?
    thanks for your help, I have been working on this for many many days !
    Abdel.

    How about a BPEL process that maintains your static variables and uses a custom correlation token. Queries to the process can retrieve the variable requested, and if they use the custom correlation token then the process will act as a singleton.
    I suggest using event processing rather than simple receive to handle the messages.

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • Non-static variable cant accessed from the static context..your suggestion

    Once again stuck in my own thinking, As per my knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static context....'
    Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void main(String ar[]){      ////static context
    ������������ int counter=0; ///Non static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    �������������� System.out.println("Value of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    Jeff

    Once again stuck in my own thinking, As per my
    knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static
    context....'
    Now the thing is that, When we are declaring any
    variables(non-static) and trying to access it within
    the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void
    main(String ar[]){      ////static context
    ������������ int counter=0; ///Non
    static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    ��������������
    System.out.println("Value
    of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    w the question is that if we are trying to declare a
    variable out-side the method (Non-static) , Then we
    defenately face the error' Non-static varialble can't
    accessed from the static context', BUT here within
    the static context we declared the non-static
    variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    JeffHi,
    You are declaring a variable inside a static method,
    that means you are opening a static scope... i.e. static block internally...
    whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
    But if you put ... it will be considered as redundant by compiler.
    More over, static context does not get "this" pointer...
    that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller.

  • Require the definition of static members in derived classes

    What I would like to do is require the definition of static variable with a particular signature in all implementing/extending classes of T.
    I would have thought this could be done in the following way:
    public template T
    {public static final Object obj;}To me, this says that all classes implementing this interface must define a member with this exact signature. This is not the case.
    Basically, I'd like to replicate the behavior I see when I extend a serializable class. I get this warning : "The serializable class X does not declare a static final serialVersionUID field of type long".
    Anyone know how to do this? I've googled many search strings, and looks on the forums extensively. I could potentially use code weaving (Aspects), but this adds another level of complexity to my project.
    Thanks in advance,
    Luke

    There is a definite use for it.
    I have an ObjectFactory A. Upon initializing a copy of this object, it scans the given package for all classes. Each class is inspected via Reflection. If there is a variable with a particular signature, in my case public static final ObjectFactory.Constructor, we get a copy of the static variable and add it to a TreeMap.
    Then, whenever someone calls ObjectFactory.createInstance("class name"), I do a lookup, and invoke a method of the Contructor object to return an instance of that object. Also, the ObjectFactory allows the programmer to list all "extensions" loaded in this manner.
    The reason I'm doing this instead of simply putting a static initializer in the "extension" class that would register the extension with the ObjectFactory is:
    I want to control when and where extensions are registered.
    Does this makes sense?
    The only thing I am missing, is how to warn (other than through documentation) the programmer that they need to define this field, exactly in the same manner as classes extended from serialized classes receive a warning that "The serializable class X does not declare a static final serialVersionUID field of type long".
    I could do this using Aspect oriented programming, but that adds a layer of complexity that I do not need.
    Here is the code:
    public class ObjectFactory<T extends Object>
         private TreeMap<String,Constructor<T>> cons=new TreeMap<String,Constructor<T>>();
         public ObjectFactory(String pkg)
              ClassLoader cld=Thread.currentThread().getContextClassLoader();
              if(cld==null)
                   throw new NullPointerException();
              String path=pkg.replace(".","/");
              URL tmp;
              Enumeration<URL> resources;
              File dir;
              try
                   resources=cld.getResources(path);
                   while(resources.hasMoreElements())
                        try
                             tmp=resources.nextElement();
                             dir=new File(URLDecoder.decode(tmp.getPath(), "UTF-8"));
                             if(dir.exists())
                                  String[] files=dir.list();
                                  for(String file:files)
                                       try
                                            if(file.endsWith(".class"))
                                                 Class<?> c=Class.forName(pkg + '.' + file.substring(0, file.length() - 6));
                                                 try
                                                      Field f=c.getField("constructor");
                                                      //TODO add type checking
                                                      Constructor<T> con=Constructor.class.cast(f.get(null));
                                                      synchronized(cons)
                                                           cons.put(con.getName(),con);
                                                           System.out.println(con.getName());
                                                 catch(IllegalAccessException ignored)
                                                 catch(NoSuchFieldException ignored)
                                       catch(ClassNotFoundException e)
                        catch(UnsupportedEncodingException e)
              catch(IOException e)
         public interface Constructor<T>
              public T createInstance();
              public String getName();
         public T createInstance(String name) throws FactoryNotFound
              Constructor<T> c=cons.get(name);
              if(c==null)
                   throw new FactoryNotFound();
              return c.createInstance();
    import ObjectFactory.Constructor;
    public final class Extension
         public static final String desc="";
         public static final String name="Test01";
         public static final Constructor<Object> constructor=new Constructor<Object>()
              public Object createInstance()
                   return new Fighter();
              public String getName()
                   return name;
    }

  • Is is better to use static variables?

    Hi,
    Does anyone know if it's better to use static variables or to use normal variables?
    Concerning the size of the code, it seems that declaring a variable as static is more consuming (for example plus 6 bytes for an object reference).
    So this could mean that declaring variables as static should be avoided, but what about the execution time?
    Some years ago, some javacard gurus were claiming that it's was better to use static variables (less processing required by the JVM to resolve adresses of static variables), but is it still the case?

    Hi Lexdabear,
    Thanks for the answer.
    I did the test (I converted my all code to use static variables and methods as much as possible), and did a bench before and after, on a JCOP31 card.
    The conclusion is that today JVMs and processors are much powerful than 5 years ago, and that the difference is really difficult to measure, which anyway is a good thing for us ;-)

Maybe you are looking for