Can a static variable wil be serialized?

can a static variable wil be serialized? plz send reply soon

No. Serialization is about the state of the object, but static variables reflect the state of the class as a whole.
And don't say things like "reply soon." People will reply if and when they feel like it, without regard to you requests for "soon."

Similar Messages

  • Is static variable serialized ???

    hi
    I have a static integer memeber of a serializable class. When I serialize and then deserialize this object into another object I am getting the lastest value of this variable. It looks like the variable is being serialized.
    but i have read that static variables are not serialized.
    can anyone clarify why i m getting the latest (updated) value??

    This is not a good test. Once a class is loaded it remains loaded and all its static fields remain set with any values assign to them.
    Try this instead:import java.io.*;
    public class Ser implements Serializable {
        static int var = 9;
        void set() {
            var = 100;
    public class DumpSer {
        public static void main(String[] args) throws Exception {
            Ser kk = new Ser();
            kk.set();
            File outFile = new File("out.dmp");
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outFile));
            out.writeObject(kk);
            out.close();
    public class LoadSer {
        public static void main(String[] args) throws Exception {
            File inFile = new File("out.dmp");
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(inFile));
            Ser jj = (Ser)in.readObject();
            in.close();
            System.out.println("Val -> "+jj.var);
    }After compilation, first execute:
    > java DumpSer
    Then execute:
    > java LoadSer
    What do you see?

  • Static fields ARE being serialized

    Hi there,
    I wrote a small test class that serializes an object, writes the serialized object to file, read the serialized object from the file and then deserialize the object. The object being serialized contains normal fields, a transient field, and a few 4 static fields with varying access modifiers. For some reason the static variables ARE being serialized. From what I've read this should not happen, and for very good reasons.
    Here is the object being serialized:
    package serialization;
    import java.io.Serializable;
    import java.util.Formatter;
    public class MySerializableObject implements Serializable {
         private static final long serialVersionUID = 1L;
         private int a = 1;
         private int b = 2;
         private transient int c = 3;
         static public int d = 4;
         static protected int e = 5;
         static private int f = 6;
         static int g = 7;
         @Override
         public String toString() {
              Formatter formatter = new Formatter();
              formatter.format("a=%1$s b=%2$s c=%3$s d=%4$s e=%5$s f=%6$s g=%7$s", a,b,c,d,e,f,g);
              return formatter.toString();
         public void setNewD(int newVal) {
              d = newVal;
    }And here is the code that does the serialization:
    package serialization;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    public class FileContentsObjectSerializer {
         File file;
         public FileContentsObjectSerializer(String name) {
              this.file = new File(name);
              if (this.file.exists()) {
                   this.file.delete();
              try {
                   this.file.createNewFile();
              } catch (IOException e) {
                   e.printStackTrace();
         public void serialize(Object o) throws IOException {
              FileOutputStream fos = new FileOutputStream(this.file);
              ObjectOutputStream oos = new ObjectOutputStream(fos);
              oos.writeObject(o);
              oos.close();
              fos.close();
         public Object deserialize() throws IOException, ClassNotFoundException {
              FileInputStream fis = new FileInputStream(this.file);
              ObjectInputStream ois = new ObjectInputStream(fis);
              Object o = ois.readObject();
              fis.close();
              ois.close();
              return o;
         public static void main(String args[]) {
              MySerializableObject mso = new MySerializableObject();
              mso.setNewD(100);
              System.out.println("Object being serialized:"+mso.toString());
              FileContentsObjectSerializer ofs = new FileContentsObjectSerializer("c:/temptest.txt");
              try {
                   ofs.serialize(mso);
                   MySerializableObject result = (MySerializableObject) ofs.deserialize();
                   System.out.println("Deserialized Object:    "+result.toString());
              } catch (Exception e) {
                   e.printStackTrace();
    }And here is the results I get:
    Object being serialized:a=1 b=2 c=3 d=100 e=5 f=6 g=7
    Deserialized Object:    a=1 b=2 c=0 d=100 e=5 f=6 g=7As you can see, both results are exactly the same, even though the setNewD value is not called on the deserialized object.
    Any ideas?

    You are misinterpreting the result. Try this main instead:
        public static void main(String args[]) {
            MySerializableObject mso = new MySerializableObject();
            mso.setNewD(100);
            System.out.println("Object being serialized:"+mso.toString());
            FileContentsObjectSerializer ofs = new FileContentsObjectSerializer("c:/temptest.txt");
            try {
                ofs.serialize(mso);
                mso.setNewD(-100); //a-oogah!
                MySerializableObject result = (MySerializableObject) ofs.deserialize();
                System.out.println("Deserialized Object:    "+result.toString());
            } catch (Exception e) {
                e.printStackTrace();
        }

  • IS there static variables in oracle 9i??

    Hi,
    I have a requirement.
    I am establishing an orcale 9i connection from my .net application.
    Now I am calling an SP and it has a global count variable initialized to 0, and It fetches a count of * from one table and also there are other functionality that the SP does.
    Now I want to persisit this count variable's value , so that next time the SP is called ( in the same connection), I will make a check that if the count variable is not 0 then dont execute the query to populate the count variable.
    Normally in java, .net etc... we can create static variables for this purpose.
    Can the same be done in PL/SQL?
    If not what would be the alternative?
    Thanks folks.
    s

    Hi,
    Please have a look.
    SQL> create or replace package test_pkg
    2 is
    3 procedure test_1;
    4 end test_pkg;
    5 /
    Package created.
    SQL> create or replace package body test_pkg
    2 as
    3 global_cnt number(10):=0;
    4 procedure test_1
    5 is
    6 begin
    7 if global_cnt > 0
    8 then
    9 dbms_output.put_line('No RUN');
    10 else
    11 dbms_output.put_line('RUN');
    12 global_cnt := global_cnt + 1;
    13 end if;
    14 end;
    15 end test_pkg;
    16 /
    Package body created.
    SQL> set serveroutput on
    SQL> exec test_pkg.test_1
    RUN
    PL/SQL procedure successfully completed.
    SQL> exec test_pkg.test_1
    No RUN
    PL/SQL procedure successfully completed.
    SQL> exec test_pkg.test_1
    No RUN
    PL/SQL procedure successfully completed.
    SQL>
    -----------------------------------------------------------------------

  • 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... '

  • What is static variable.

    What is static variable. what is difference between  static variable and public variable?

    Static variables belong to the Class. Non-static variables belong to Class instances.
    Public variables can be accessed from outside of the Package. Non-public variables can only be accessed within the Package.
    So they are quite different thing. You can have Static variables, Public Static variables, and Private Static variables...

  • Can't we declare a static variable inside a memberfunction of a class?

    Hi,
    class A{
    public void fun()
    static int i=10;
    can' we declare static variable in member function of class?
    Thanks,

    It is a common idiom in C and C++, but it is forbidden
    in Java because it adds hidden dependencies.
    The C way of writing a serial number generator:
    int generate() {
    static int n = 0;
    return n++;
    }Pure C has only global functions. So it needs inner
    static variables to help to hide the data. I've had
    lots of headaches trying to make C programs with inner
    static variables work correctly because they usually
    are hidden in cross-reference listings.
    The Java way:
    public static class SerialNumberGenerator() {
    private static int n = 0;
    public static int generate() {
    return n++;
    }The code above is as static as the C code given
    before, but it tries to be more explicit (no hidden
    variables).Hum... have you tried to compile your sample ?
    (And anyway, what the hell would a static class be used for ???)
    But perhaps you meant:
    public final class SerialNumberGenerator {
       private static int n = 0;
       public static int generate() {
          return n++;

  • Can we define 'Static Variables' in BPEL process ?

    Is the idea of 'STATIC VARIABLES' supported in Oracle BPEL?
    What I mean by that is, I need all my in-flight BPEL process INSTANCES to read a common variable and then decide the next course of action.
    Is this possible?
    Thanks in advance,
    Mahendra

    Hi Hans,
    In Cocoa and Objective-C a static variable needs to be declared in the implementation file and not the header as you would normally do. Standard C variables can be set at the same time as the declaration but Cocoa objects need an extra step.
    For example:
    #import "TestObject.h"
    // declare your static variable here
    static NSArray *count;
    @implementation TestObject
    - (id) init {
    self = [super init];
    if (self != nil) {
    // set the variable here
    // the 'if' statement ensures it is only set once
    if (!count) {
    count = [[NSArray arrayWithObjects:@"One",@"Two",@"Three",Nil] retain];
    return self;
    @end
    Hope this helps,
    Martin.
    PowerMac G5 1.6Ghz   Mac OS X (10.4.9)   4 gig RAM & NVidia 6800 Ultra

  • Can I use static variable in EJB?

    Many books suggest developer don't use static variable in EJB,I want to know why?
    I know there isn't any problem if the static varibale is read only
    For writable static varible ,what will happen if I use a static Hashtable for share data
    Help me!Thank you very much!!

    Greetings,
    I know that "EJB business methods are not allowed to
    block on synchronized resources" Just where do you "know" that from?? The EJB 2.0 Specification, at least, is nowhere in agrement with this statement. If it comes from a book I would question the author's reasoning. Contractually, there's no sound basis for this. In the case of Session Beans, they have an expressedly direct and single-threaded association with a client. From a design viewpoint, it certainly seems unnecessary for a bean to "block" its one-and-only client, but to say that it "is not allowed to" do so is without merit. Entity Beans, on the other hand, are concurrently accessible. Yet, with regard to a transactional context being in effect, the container does indeed block on a bean's business methods. For the bean to do so itself is, therefore, unnecessary. Furthermore, the specification explicitly concedes that a "Bean Provider is typically an application domain expert" and "is not required to be an expert at system-level programming." (EJB 2.0 Spec. 3.1.1) From these statements alone it is reasonable to assume the above statement is meritless since the Bean Provider is not expected to even consider synchronization issues when developing a bean.
    But I'm mixed up why we could use "Hashtable" or otherApparently, because your sources are as well...
    collection classes in the EJB ,in these method many
    methods are synchronized In fact, not only "can we use" them but, with respect to multiple-row finders in Entity Beans we are [i]required to use them (or an iteration of them)! Not all Collection classes are synchronized (so called "heavy-weight collections"). As shown above, that the choice of a particular Collection class might be synchronized is of little consequence since a bean designed under strict adherence to the specification ensures that it is never concurrently writeable.
    Could someone provide a good way for this problem?
    Please Help Me!!!Regards,
    Tony "Vee Schade" Cook

  • 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.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Why Inner class cannot access static variables

    Why is it that inner class can use only static final variables of the outerclass, and not ordinary static variables of the outer class. "Yes the JLS sepcifies that only final static variables can be used inside an inner class, esp a non blank final variable". But why this restriction.
    Thanks.

    so what are final static variables treated as if they
    are not variables. So if the final static value is
    not loaded when the class is loaded how will the
    class know about the value.??The actual value wil be substituted for the name of a static final value at compile time. That's why you can use them in switch statements where you can't use any variable variable.
    This is something to watch out for, by the way, because if you use a public static final value from one class in another the actual value will be compiled into the using class, so if you change the value where it's defined the class using it will have the old value until it's recompiled.

  • 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

  • How to give different value to a static variable???

    Hi all:
    Is there any solution to set different values to a static variable???I had try two ways but all have errors!
    1.Way_1
    protected String tmp=null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    tmp = "string1";
    else if (sayorpress==1)
    tmp = "string2";
    protected static String RESOURCE_STRING = tmp; <---error
    Error:non-static variable tmp cannot be referenced from a static context
    2.Way_2
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    protected static String RESOURCE_STRING = "string1"; <---error
    else if (sayorpress==1)
    protected static String RESOURCE_STRING = "string2"; <---error
    Error:illegal start of expression at
    not an expression statement at
    Thank you very mich!!!

    Try this:
    protected static String RESOURCE_STRING = null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    yourClass.RESOURCE_STRING = "string1";
    else if (sayorpress==1)
    yourClass.RESOURCE_STRING = "string2";
    You cannot declare a static variable inside a method. But you can access a static variable thorugh your class.

  • Runtime error in linking with static variables....

    Hi,
    I am building a shared library which includes a compiled object generated from a class containing the static variables only and also I have another version of same class with same & some new static variables in it and using that to generate another shared library. Now when I tried to run a program
    which links with both the library it core dumps when it tries to return from the program i.e when it finishes.
    Can someone please help me explain why my program is behaving like that?? Can duplicate inculsion of static variables in different scope can cause problem ?? How can this be avoided ?
    Also please be advised that the class with static variables gets generated at the compile time using a script which uses a DTD whose version (specification) can be different in both the libraries therefore I can't just seperate the common stuff into one class and specific into another.
    Thanks.
    Rajeev.

    Not to worry...found the answer in another post. Seems like patches need to applied to the OS.

Maybe you are looking for

  • Send Correspondence Customer Statement Via Email

    Hi SAP Gurus, Currently, I already succeed with user exit EXIT_RFKORIEX_001 to send customer statement (F.27) via email. The program can attached PDF Files in the email that sent by SAP. However, the email that sent is blank without body text. Does a

  • UME with ABAP AS and LDAP Datasource

    Hello SDN´s We have tried very hard for the last days configuring the ume-xml for the following scenario: -     LDAP is used to authenticate the user -     AS ABAP is used to store the roles of the user (because they automatically becomes groups in t

  • IIS7 with jrun4 on windows server2008(64 bit)

    Hi, I have windows server 2008(64 bit) with jrun4 updater 7 installed. I want to use IIS 7 with these. when i launch webServer configuration to add iis,foll happens: 1.i get a window with values:host:localhost , server:default , webserver:iis IIS web

  • ViewerPreferences (e.g. HideWindowUI) in Adobe LiveCycle Designer

    Hi, When creating PDFs in Adobe Acrobat, you can set some ViewerPreferences: * HideWindowUI * HideMenubar * HideToolbar true These settings can be set via "Document Properties" => "Initial View" => "User Interface Options" However, when creating a fo

  • What's the best Visual Studio 2010 (VB) template for my project?

    Hi, I'm about to embark on a project which will end with a website that gathers users info (name, email, description, youtube address etc), then will display that info to other users via filtering. My initial instinct is to create an empty website, t