Datacorruption and static methods

public static void myMethod( String Argument)
     int i = 0 ;
What are the chances of data corruption in this static method?
IF there are chances of data corruption, am I corrupt in saying that chances of data corruption for argument and Variable i are same?
Where is function state stored in static method stored? What will happen to this if one thread pre-empts other?
public class a
     int j;
     public static void myMethod( String Argument)
          int i = 0 ;
How is integer j different from integer i? Where will JVM keep these variables ?

What are the chances of data corruption in this static
method? None. As long as this static method only acts on local variables (variables declared inside the method) each call to the method is completely separate from any other call.
Where is function state stored in static method
stored? What will happen to this if one thread
pre-empts other?I'm not sure what you mean by 'function state' but static methods are not associated with an Object, though they can modify and depend on the state of static (class) varaivbles.
How is integer j different from integer i? Where will
JVM keep these variables ? j is a member varaible. It is associated wth the instance of the class. i is a local variable and is created at the beginning of a method call and destroyed (eventually) after the method completes.

Similar Messages

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Abstract classes and static methods

    I have an abstract report class AbstractReportClass which I am extending in multiple report classes (one for each report, say ReportA, ReportB, ...). Each report class has its own static column definitions, title, etc., which I have to access through a static method getDataMeta() in a web application. Each report has the same exact code in getDataMeta, and no report may exist without these fields. My intuition tells me that AbstractReportClass should contain the code for getDataMeta, but I know that you can't mix abstract and static keywords.
    Am I missing a simple solution to unify the getDataMeta code in the abstract base class? or do I really need to have a static function getDataMeta with the same code in each of the base classes?
    My apologies if this has been discussed many times before.
    Thanks,
    -Andrew

    I'm not trying to be "right"; rather I just asked a question about whether I can do something that seems intuitive. Perhaps you might write code in a different way than I would or perhaps I wasn't clear about every little detail about my code? Do you regularly belittle people who ask questions here?
    I have a loadFromDB() member function in AbstractReport for which all sub classes have an overloaded version. All reports I'm displaying have 4 common fields (a database id and a name and a monetary value, for example), but then each other report has additional fields it loads from the database. Inside ReportX classes' loadFromDB(), I call the superclass loadFromDB() function and augment values to get a completely loaded object. In fact, the loadedData member object resides in AbstractReport.
    I can't use a report unless it has these common features. Every report is an AbstractReport. There is common functionality built on top of common objects. Isn't this the point of inheritance? I'm essentially saying that abstract class Shape has a getArea function and then I'm defining multiple types of Shapes (e.g. Rectangle and Circle) to work with...

  • Generics and static methods

    Hi,
    I need a sanity check to make sure I have not missed design pattern.
    I believe that it is not possible to call a static method defined in a generic type.
    For example:
    public class Red extends Color
        public static Color getHue()
    public class Green extends Color
        public static Color getHue()
    public class GenericColorTest<C extends Color>
        public void fooBar()
             Color hue= C.getHue();  // Is this a valid method call ?
    }Since the base class Color can not define static methods, it seems resonable that a generic type can't make the call to get getHue(). Or am I missing something ? Is there a way for the class GenericColorTest's generic type C to call a static method ?
    Thanks
    HB

    I think I can be ever more specific than gafter on this.
    Your call, "C.getHue()", just plain makes no sense. C is "some kind of Color object", and the class "Color" has no function (static or not) called "getHue()". So calling "C.getHue()" is a simple case of you trying to call a function that isn't in the class.
    In fact you can call static functions, but only if they are in the base class require by the generic definition (erm, sorry can't remember the exact term right now). So, for example, if there was a "getHue()" static function in your class "Color", then sure, you can call "C.getHue()" in your code. But since static functions can't be overridden, the "C.getHue()" will do exactly the same thing no matter which actual class C was at the moment, which doesn't seem to be what you want.
    The right thing to do is just make "getHue()" non-static. Then things will work great.

  • Data Curruption and Static methods

    public static void myMethod( String Argument)
         int i = 0 ;
    What are the chances of data corruption in this static method?
    IF there are chances of data corruption, am I corrupt in saying that chances of data corruption for argument and Variable i are same?
    Where is function state stored in static method stored? What will happen to this if one thread pre-empts other?
    public class a
         int j;
         public static void myMethod( String Argument)
              int i = 0 ;
    How is integer j different from integer i? Where will JVM keep these variables ?

    Sorry The
    int j ;
    should have been
    static int j;
    I thought the behaviour of a variable in a static method will be same as static variable.

  • Regarding Returning Parameter and Static method

    Hi frnds,
    I am learning oops ABAP. I want to use returning parameters in method and also STATIC METHOD.
    If any example it will be more helpful
    regards,
    satya

    Hi satya,
                 Check this out ,Its helpful.
    To get some values from a method , one can use the exporting, changing or returning parameters.If one uses RETURNING parameters, the following restrictions apply:-(1) No EXPORTING/CHANGING parameters can be used for the method.(2) Only one RETURNING parameter can be used.(3) RETURNING parameters are only passed by value.This program demonstrates the use of RETURNING parameters and the various ways   to call a method with RETURNING parameter to get the value into some variable.
    Sample Program
    </code>
    report ysubdel1 message-id 00.
    data : w_num type i.
    class c1 definition .
    public section. 
    methods : m1 importing input1 type i
                            input2 type i
                            returning value(result) type i .
    endclass.
    class c1 implementation.
    method  : m1.
    result = input1 * 2 + input2.
    endmethod.
    endclass.
    start-of-selection.
    data : obj1 type ref to c1 . 
    create object obj1.
    Syntax 1     
    call method obj1->m1 EXPORTING input1 = 5                                                        input2 = 4  
                                   RECEIVING result = w_num.  
      write:/5 w_num .
    Syntax 2
         w_num = obj1->m1( input1 = 10 input2 = 20 ).
      write:/5 w_num .
    Syntax 3     
    move obj1->m1( input1 = 2 input2 = 3 ) to w_num .  
    write:/5 w_num .
    </code>
    Static method example
    <code>
    REPORT  zstatic.                              .
    data : num type i.
    class testclass definition.
    public section.
      class-methods : testmethod.
    endclass.
    class testclass implementation.
    method : testmethod.
      num = 5.
      write:/5 num.
    endmethod.
    endclass.
    start-of-selection.
    call method testclass=>testmethod.
    </code>
    Reward Points if u find helpful.
    Thnks & Regards,
    Rajesh

  • Synchronized and static methods

    I've got a doubt: is it possible to apply syncrhonized to a static method? I know that synchronized takes a lock on the current object, but in the case of a static method there could be no object.
    So how can I synchronize a static method?
    Thanks,
    Luca

    previous X POST(s) :
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411296
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411285
    http://forum.java.sun.com/thread.jsp?forum=31&thread=390499
    http://forum.java.sun.com/thread.jsp?forum=31&thread=374388
    http://forum.java.sun.com/thread.jsp?forum=31&thread=325358
    BOTTOM LINE : Search the forum b4 posting.
    rgds.

  • Interfaces and static methods

    Hi All,
    Does anyone know why you can't declare static methods in an interface? Is there a way round this problem?
    Cheers...

    But this won't:public class StijnsClass
      public static void aMethod()
        System.out.println("StijnsClass.aMethod()");
      public static void main(String[] arg)
        StijnsClass stijnsInstance = new StijnsSubClass();
        stijnsInstance.aMethod();
        System.out.println("Nothing else to say, here?");
    class StijnsSubClass extends StijnsClass
      public static void aMethod()
        System.out.println("StijnsSubClass.aMethod()");
        super.aMethod(); // Wrong!!!
    }You will get:
    "StijnsClass.java:21: non-static variable super cannot be referenced from a static context".
    If you remove static from the subclass method definition, you will get:
    "StijnsClass.java:18: aMethod() in StijnsSubClass cannot override aMethod() in StijnsClass; overridden method is static"
    That's the point. You aren't extending the method; you are only hiding it. To make it work, both methods must be instance methods, ergo, static methods cannot be extended.

  • Polymorphism and static methods

    Say I have classes A and B:
    public class A {
         public static A newInstance() {
              return new A();
    public class B
    extends A {
    }How can I write the newInstance method in A so that:
    B.newInstance();returns an object of class B instead of A? I know I can override the method in B to make an object of the right type - but is there a way to write the A method so that the correct type is created by any subclasses?

    I suppose this is cheating...
    class A {
       public static A newInstance(Class c)
       throws InstantiationException, IllegalAccessException {
          return (A) c.newInstance();
    class B extends A {
    class Testx {
       public static void main(String[] args)
       throws InstantiationException, IllegalAccessException {
          B b = (B)B.newInstance(B.class);
          System.out.println(b.getClass().getName());  //B

  • Completely stuck, get/set, Contructors and Static Methods

    Hi any help would be very appreciated on this one,
    import java.util.Scanner;
    import java.io.*;*
    *import java.util.*;
    public class Course extends Program {
         public Course(String Coursecode, String Coursename){
              Coursecode = stuinput.courseCode;
    public void getCoursecode(){
         return stuinput.courseCode;
    //public String getCourseCode(){
    //     return this.courseCode;
           public static void printCourses() throws Exception
                stuinput[] courseObjArray = new stuinput[18]; //Make sure this is the same as the ammount in the text
                   Scanner sc = new Scanner(new File("courses.txt"));
                   int i=0;
                   boolean found = false;
                   while(sc.hasNextLine())
                   //Delimit this line with scanner
                   Scanner sc1 = new Scanner(sc.nextLine());
                   sc1.useDelimiter(":");
                   courseObjArray[i] = new stuinput(sc1.next(),sc1.next());
                   i++;
                   }//while
                   for(int i1 = 0;i1 < courseObjArray.length;i1++)
                   System.out.println(courseObjArray[i1].courseCode);
                   System.out.println(courseObjArray[i1].courseName);
                   System.out.println("-----------------");          
           //This print the indexOf what you want to search
              class stuinput
              String courseCode = null;
              String courseName = null;
              stuinput()
              stuinput(String courseCode,String courseName)
              this.courseCode = courseCode;
              this.courseName = courseName;
    import java.io.*;
    public class gradCheck {
         public static void main (String args[]) throws Exception {
                      Course.printCourses(); //Prints All Course but dont need that
    }This ^^^ Is basically the driver class, Im trying to run the printCourse() from the 1st Class I posted.....but it's giving me lots of errors with everything I try, I'm trying to get the values out of that text file and have them broken up so I can use them amoung various class's, I want to use those values inside the Course class, as well as the Program Class and other Class's that extend off of that,
    Any Ideas (im sure there are because im very new), as to how I might to that
    Thanks :-) would be much appreciated

    yes, I still have a lot to learn here I think, Thank you so much, that worked for me, I think I need to read a lot about all of this and understand it......thank you
    If I may, one more thing which I'm really stuck on and if I can get this right, I think my whole program and ideas will just fall into place...Ive been trying to a couple of weeks now and can't quit get it right
    in the above code,
    this bit,
              class stuinput
              String courseCode = null;
              String courseName = null;
              stuinput()
              stuinput(String courseCode,String courseName)
              this.courseCode = courseCode;
              this.courseName = courseName;
              }how do I pass this off to another class through the constructor
    public class Course extends Program {
         public Course(){
         }at the top....say If I want it to be used in the Program class.......or a student class that extends of the this current class above (Course Class)
    Thanks,

  • Advantages and disadvanteges with static methods

    Hi,
    Can anybody suggest me the advantages and disadvantages of static methods? In my project i am using templates which are used by different programs and in that templates i am using static methods.
    It is web application. is there any problems if made methods as static in templates that are used by diferent clients?
    Thanks
    Karimulla

    A static method can't be overridden, and static methods are usually only used for some utility methods and other things which don't belong to the class. I would probably not make the methods static.
    Kaj

  • What's wrong with static methods?

    Answers on an postcard please.

    I think the point here is that sometimes people come from a procedural background (or maybe no background) and they start with main, and one static method leads to another. They reach a tipping point where they are reluctant to define non-static methods to a class because it's all static elsewhere. And static method can't access instance data, so their data becomes largely static as well. When the dust settles, they are programming procedually in Java. So too many static methods is a sign that you may be programming procedurally instead of doing OOP, but using static appropriately is still cool.
    And let's not get pedantic. What goes wrong if I make my String class's getLength method static?
    public final class MyString {
        private int length;
        public static int getLength(String s) {
            return s.length;
    }It's a misuse of static, but it doesn't break my design.

  • Static Methods & Switch Statement

    Need help with a switch statement and static methods. My program offers the user a menu to choose what they want to practice.
    I want to use a switch statement to process the selection. Selecting 1, 2 or 3 causes the program to go to one of the following static methods:
    addition()
    subtraction
    multiplication()
    import javax.swing.JOptionPane;  // Needed for JOptionPane
    import java.text.DecimalFormat;  // Needed for DecimalFormat
    public class MathsFinal {
        static boolean exit = false;
        static int totalAnswersAsked = 0;
        public static void main(String[] args)
            int userChoice; 
            int correctAnswers = 0;
            do{
                //custom button text
                do{
                    boolean exitAsking = true;
                    String userChoiceString = JOptionPane.showInputDialog (null,
                            "1. Practice addition\n"
                            + "2. Practice subtraction\n"
                            + "3. Practice multiplication\n"
                            + "4. Quit the program\n"
                            + "\n"
                            + "Enter your choice",
                            "Enter your choice",
                            JOptionPane.QUESTION_MESSAGE);
                    int userAnswer, genNumOne, genNumTwo;
                    if(userChoiceString == null || userChoiceString.equals("4") )
                        { //closed it
                        exit = true;
                    }else if(userChoiceString.equals("1"))
                        { //addition
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne + genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "plus");
                    }else if(userChoiceString.equals("2"))
                        { //subtraction
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(genNumOne,0);
                        userAnswer = genNumOne - genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "minus");
                    }else if(userChoiceString.equals("3"))
                        { //multiplication
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne * genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "times");
                    }else
                        { //user didn't enter a number
                        JOptionPane.showMessageDialog(null,
                                "Please enter a number between 1 and 4",
                                "Wrong entry",
                                JOptionPane.ERROR_MESSAGE);
                        exitAsking = false;
                while(!exit);
            while(!exit);
            //create a DecimalFormat object for percentages.
            DecimalFormat userPercent = new DecimalFormat("#0%");
            //show results using information icon
            JOptionPane.showMessageDialog(null,
                    "You got " + (userPercent.format(((double)correctAnswers / (double)totalAnswersAsked)))  + " right!!",
                    "Thank you for playing",
                    JOptionPane.INFORMATION_MESSAGE);
            //ends the program
            System.exit(0);
        public static int getRandomNumber(int large, int small)
            return  (int)((large - small) * Math.random()) + small;
        public static int display(int genNumOne, int genNumTwo, int userAnswer, String operation)
            String selectAddition = JOptionPane.showInputDialog("What is" + " " + genNumOne + " " + operation + " " + genNumTwo + "?");
            if(selectAddition == null) { //pressed close
                exit = true;
                return 0;
             else if(userAnswer == Integer.parseInt(selectAddition))
              { //answer correct
                totalAnswersAsked++;
                //show results using information icon
                JOptionPane.showMessageDialog(null,
                        "Very good!",
                        "Well done",
                        JOptionPane.INFORMATION_MESSAGE);
                return 1;
             else if(userAnswer != Integer.parseInt(selectAddition))
              { // incorrect answer
                totalAnswersAsked++;
                JOptionPane.showMessageDialog(null,
                        "Sorry that was incorrect. Better luck next time",
                        "Bad luck",
                        JOptionPane.INFORMATION_MESSAGE);
                return 0;
            return 0;
    }

    hi,
    switch statement to process the selection. Selecting 1, 2 or 3
    import javax.swing.JOptionPane;  // Needed for JOptionPane
    import java.text.DecimalFormat;  // Needed for DecimalFormat
    public class MathsFinal {
        static boolean exit = false;
        static int totalAnswersAsked = 0;
        public static void main(String[] args)
            int userChoice; 
            int correctAnswers = 0;
           int userChoiceString=4;
            do{
                //custom button text
                    boolean exitAsking = true;
                    userChoiceString = Integer.parseInt(JOptionPane.showInputDialog (null,
                            "1. Practice addition\n"
                            + "2. Practice subtraction\n"
                            + "3. Practice multiplication\n"
                            + "4. Quit the program\n"
                            + "\n"
                            + "Enter your choice",
                            "Enter your choice",
                            JOptionPane.QUESTION_MESSAGE));
                    int userAnswer, genNumOne, genNumTwo;
                   switch (userChoiceString)
                   case 1:
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne + genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "plus");
                             break;
                        case 2:           
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(genNumOne,0);
                        userAnswer = genNumOne - genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "minus");
                              break;
                        case 3:
                        genNumOne = getRandomNumber(9,0);
                        genNumTwo = getRandomNumber(9,0);
                        userAnswer = genNumOne * genNumTwo;
                        correctAnswers += display(genNumOne, genNumTwo, userAnswer, "times");
                             break;
                        case 4: break;
                     default :
                        JOptionPane.showMessageDialog(null,
                                "Please enter a number between 1 and 4",
                                "Wrong entry",
                                JOptionPane.ERROR_MESSAGE);
                        exitAsking = false;
                } while(userChoiceString != 4);
            //create a DecimalFormat object for percentages.
            DecimalFormat userPercent = new DecimalFormat("#0%");
            //show results using information icon
            JOptionPane.showMessageDialog(null,
                    "You got " + (userPercent.format(((double)correctAnswers / (double)totalAnswersAsked)))  + " right!!",
                    "Thank you for playing",
                    JOptionPane.INFORMATION_MESSAGE);
            //ends the program
            System.exit(0);
        public static int getRandomNumber(int large, int small)
            return  (int)((large - small) * Math.random()) + small;
        public static int display(int genNumOne, int genNumTwo, int userAnswer, String operation)
            String selectAddition = JOptionPane.showInputDialog("What is" + " " + genNumOne + " " + operation + " " + genNumTwo + "?");
            if(selectAddition == null) { //pressed close
                exit = true;
                return 0;
             else if(userAnswer == Integer.parseInt(selectAddition))
              { //answer correct
                totalAnswersAsked++;
                //show results using information icon
                JOptionPane.showMessageDialog(null,
                        "Very good!",
                        "Well done",
                        JOptionPane.INFORMATION_MESSAGE);
                return 1;
             else if(userAnswer != Integer.parseInt(selectAddition))
              { // incorrect answer
                totalAnswersAsked++;
                JOptionPane.showMessageDialog(null,
                        "Sorry that was incorrect. Better luck next time",
                        "Bad luck",
                        JOptionPane.INFORMATION_MESSAGE);
                return 0;
            return 0;

  • Re: static methods in an interface?

    You cannot define a constructor in an interface, (part of the language specification), and static methods belong to the class so how could a derived concrete class possibly implement something that belonged to its ancestor abstract class? Look at the factory pattern & perhaps Singleton for more guidance and seriously consider why you're attempting to do this. In fact, post the reasoning behind this decision and see if there are any useful comments / suggestions on that.

    This certainly sounds like a candidate for the Factory pattern, (or one of its specialisations such as Flyweight). Check out the forum here or one of the many sites focused on this area. You'll see that you're trying to solve a common problem in an unnecessarily complex way.

  • Static Methods with all Final Parameters

    Gurus,
    I know the synchronization and static method question has been hashed out ad infinitum here. However, I was thinking of a slight twist. (Did a search but could not find something related to this. If this has already been posted, my apologies).
    Suppose you have a static method in which all of the parameters in the method signature are declared final. Let's assume also that you are not performing an operation with a high latency (say, database or network operations).
    Would it be "safe" to leave the static method unsynchronized in a multi-threaded environment? Would the final keyword(s) ensure that, throughout method execution, there is no longer a race condition?
    Would there be a difference between a primitive:
    static final public void doSomething(final int param) {}
    And an object that has mutator methods:
    static final public void doSomething(final List param) {}
    Basically, not having a formal CS background, I'm not sure how static methods are actually invoked on a low-level. It probably varies across JVM's, and maybe this question doesn't make much sense. However, I thought I would throw this out to see if anyone had implemented something similar.
    I might be giving "final" too much credit., but what would actually happen in a multi-threaded environment?
    Thanks much!
    - Saish
    "My karma ran over your dogma." - Anon

    I know the synchronization and static method question
    has been hashed out ad infinitum here. What question's that then?
    Suppose you have a static method in which all of the
    parameters in the method signature are declared final.
    Let's assume also that you are not performing an
    operation with a high latency (say, database or
    network operations).
    Would it be "safe" to leave the static method
    unsynchronized in a multi-threaded environment?Whether or not the parameters are final makes no difference - method parameters are local to the method and so are only visible to the current thread anyway. So making them final will have no effect on anything goning on in any other thread.
    Whether or not you are performing operations has no effect on whether or not you can call a method thread-safe. It might mean there is less contention and it might make race conditions less likely, but it won't eliminate them.
    So the answer is: If your would be thread safe with non-final parameters, then it will still be thread-safe when the parameters are all final. If it is not thread-safe with non-final parameters, then it will still not be thread safe with final parameters.
    Would the final keyword(s) ensure that, throughout
    t method execution, there is no longer a race
    condition?No. Absoloutely not.

Maybe you are looking for

  • How to call a form using personalization

    Hi All, We have a requirement in which we need to call a standard form from another standard form. Can we achive this using form personalization? If yes, please guide us on how? Thanks,

  • Kensington Expert Mouse Pro (64213) with FCP 5

    I was looking into buying the Kensington Expert Mouse Pro to use with Final Cut Pro 5. Does anyone know if you are able to program the 6 buttons on the top of the mouse as hotkeys for different tools within FCP? Thanks for your help! -Curtis Power Ma

  • Decimal value in a query

    Hi When we try to create a query that have a calculation, the result always presented as a decimal(10,3). Is possible to have a result as a decimal(10,4)? for example SELECT 0.125*0.1 the result should be 0.0125, but in query from SAP BO appears 0.01

  • Creating a storage repository

    Hi, I'm having an issue creating a storage repository in VM manager 3.0.1. I have 2 blades connected via fiber channel to SAN storage. When discovering the server, the storage gets detected automatically as an "unmanaged fiber channel array". I am ho

  • Color changes after update

    I have just upgraded to 10.4.10 this morning, Some of my Aperture library files have now taken on a "magenta hue", especially noticeable in the neutral area's. The files are Nikon D200.nef images. I have had made no other recent changes or upgrades t