Trying to understand Static methods

Hi all,
I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time.
I am looking at a piece of code that had me thinking for a bit. I cant post the code itself but here is an example of how the code is structured
The first class declares a couple of non static arrays and makes them available via the getters and setters. It also has one method that calls a static method in another class.
package com.tests.statictest;
import java.util.ArrayList;
public class ClassA{
     ArrayList arrayList1 = new ArrayList();
     ArrayList arrayList2 = new ArrayList();
     public ClassA(){
          arrayList1.add("TEST1");
          arrayList1.add("TEST2");
          arrayList2.add("Test3");
          arrayList2.add("Test4");
     ArrayList getArrayList1(){
          return arrayList1;
     ArrayList getArrayList2(){
          return arrayList2;
     ArrayList getJoinedArrayList(){
          return ClassB.joinArrays(arrayList1,arrayList2);
}The second class contains the static method that is called by the above class to join the two arrays. This class is used by many other classes
package com.tests.statictest;
import java.util.ArrayList;
public class ClassB{
     public static ArrayList joinArrays(ArrayList list1, ArrayList list2){
          ArrayList list3 = new ArrayList();
          list1.addAll(list2);
          return list1;
}And here is my test class
package com.tests.statictest;
public class ClassC{
      public static void main(String args[]){
           ClassA classA = new ClassA();
          System.out.println(classA.getArrayList1());
          System.out.println(classA.getArrayList2());
          System.out.println(classA.getJoinedArrayList());
     }The output to the above program is shown below
[TEST1, TEST2]
[Test3, Test4]
[TEST1, TEST2, Test3, Test4]My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time? Woulnt the static method in ClassB corrupt the data?

ziggy wrote:
Hi all,
I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time. There is no such thing as a "static object" in Java. The word "static" simply means "belonging to a class as a whole, rather than an individual instance."
My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time?ClassA isn't a thread, so it can't be "executed", per se.
Woulnt the static method in ClassB corrupt the data?"Staticness" doesn't have anything to do with it; the issue at hand is operations on a shared data structure, which is a concern whether you're dealing with static or non-static members. There is nothing inherent in ClassB that will "corrupt" anything, however.
~

Similar Messages

  • Trying to understand Methods

    I have a code that asks for integer input and outputs the sum of the integer.
    import java.util.Scanner;
    public class Assignment3a {
      public static void main (String[]args){
        Scanner input = new Scanner (System.in);
        //declaration
        int i, n, mod=0, sum = 0;
        //get user input for 'How many inputs'
        System.out.print ("How many numbers in input? ");
        i = input.nextInt();
        //number of itterations
        for (int entry=1; entry <= i; entry++){
          System.out.print ("Enter a positive integer: ");
          n = input.nextInt();
          while (n < 0){//If number is negative
            System.out.print ("ERROR! Should be positive. Enter a positive integer: ");
            n=input.nextInt();
          while(n>0){//sum of integers
            mod= n % 10;
            sum= mod + sum;
            n = n / 10;}
          System.out.println ("The sum of digits is " + sum + ".");
          mod = 0;//reset integers
          sum = 0;
    }What I need is to use a method which does the sum of digit part. Here is a vague idea, of what I think it would be. Obviously, there are several error. Would someone show me the right way?
    import java.util.Scanner;
    public class test {
      public static void main (String[]args){
        Scanner input = new Scanner (System.in);
        //declaration
        int i, n, mod=0, sum = 0;
        //get user input for 'How many inputs'
        System.out.print ("How many numbers in input? ");
        i = input.nextInt();
        //number of itterations
        for (int entry=1; entry <= i; entry++){
          System.out.print ("Enter a positive integer: ");
          n = input.nextInt();
          if (n < 0){//If number is negative
            System.out.print ("ERROR! Should be positive. Enter a positive integer: ");
            n=input.nextInt();
          else{//sum of integers
            displaySum(n,mod,sum);
            System.out.println (sum);
      public static void displaySum(int n, int mod, int sum){  
        mod= n % 10;
        sum= mod + sum;
        n = n / 10;
    }Edited by: acastelino2001 on Apr 22, 2010 2:27 PM

    acastelino2001 wrote:
    I think you misunderstood me or may be I wasn't clear enough. the program should call a method (in this case displaySum) to solve the sum. The issue I'm having is, that I don't fully understand how methods work...Then it seems to me that you need to read the tutorials; otherwise anything we give you, while it might do the job, won't be your own work.
    However, a method is essentially a named function which does a specific piece of work. It takes input in the form of parameters and hands back a result, in the form of a return value; however neither are absolute requirements (a method can have no parameters, and can define a return type of 'void', which indicates that it does not return a value).
    The real craft of programming is to set up methods that break down the problem you've been assigned into single tasks, and for that reason I agree completely with flounder that calculateSum() is the first thing you should look at. Once you've got that working, you can then use its result to create a displaySum() method that prints it out.
    Winston

  • Calling a static method from another class

    public class Command
        public static void sortCommands(String command, String order, List object)
             if(command.equalsIgnoreCase("merge") && order == "a")
                  object.setAscending(true);
                  Mergesort.mergesort(object.list);                  // line 85
    }and
    public class Mergesort
         public static void mergesort (int[] a)
              mergesort(a, 0, a.length-1);
         private static void mergesort (int[] a, int l, int r)
         private static void merge (int[] a, int l, int m, int r)
    }Error:
    Command.java:85: cannot find symbol
    symbol : variable Mergesort
    location: class Command
    Mergesort.mergesort(object.list)
    What am I doing wrong here? Within the Command class I am calling mergesort(), a static method, from a static method. I use the dot operator + object so that the compiler would recognize the 'list' array. I tried using the
    Mergesort.mergesort(object.list);notation in hopes that it would work like this:
    Class.staticMethod(parameters);but either I am mistaken, misunderstood the documentation or both. Mergesort is not a variable. Any help would be appreciated, I have been hitting a brick wall for hours with Java documentation. Thanks all.

    [Javapedia: Classpath|http://wiki.java.net/bin/view/Javapedia/ClassPath]
    [How Classes are Found|http://java.sun.com/j2se/1.5.0/docs/tooldocs/findingclasses.html]
    [Setting the class path (Windows)|http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/classpath.html]
    [Setting the class path (Solaris/Linux)|http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/classpath.html]
    [Understanding the Java ClassLoader|http://www-106.ibm.com/developerworks/edu/j-dw-javaclass-i.html]
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Using static methods to instantiate an object

    Hi,
    I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
    Example:
    class A
       static int i = 0;
       public A(int _i)
           i = _i;
       public static A newA(int _i)
            return new A(_i);
    class B
        public B()
            A.newA(5);
            A.newA(3);
            System.out.println(A.i);
        public static void main(String[] args)
            B b = new B();
    }Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
    -Bruce

    It
    seems like you are the only one having trouble
    understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
    Allow me to point out the confusing points in your posts:
    you would think class B would have two
    instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
    Is there really two instances of class
    A or just one?You have created two instances.
    >I think it would be the same one because if you
    check the int i it would be 3 and not 5.
    I fail to see what that has to do with the number of instances that have been created...?
    Maybe static instantiated objects have the
    same reference within the JVM as long as you
    don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
    What do you mean by "the same reference within the JVM"? The same as what?
    What happened to the first call "A.newA(5)"?
    I think it was overidden by the second call
    "A.newA(3)".As i already asked, what do you mean by this?
    If you change the line for the constructor
    in A to i = i * i you will get "9" as the
    output, if you delete the call "A.newA(3)"
    you will get "25" as the output. Yes. What part of this is cauing a problem?

  • Trying to understand the Serialization interface

    Im trying to understand the Serialization of objects?
    As an example, I create a Library class that implements Serializable, that stores a collection of Book objects
    If I am only looking at saving a Library object to file, does the Book class require Serialization also or just the Library?
    I have read the API on serialization, no answer there, if it is it's not easy to understand or read into the API...

    There are some really important things to know about when doing serialization. For example one important thing to know about that not is mentioned here is that your serializable classes must define its own private static final long serialVersionUID because if you not do that will you not be able to deserialize (read in) the data you have saved later if you change anything in your serializable class. It is a bit tricky to manage files to which you have serialized different versions of your class, that is versions where you have added more serializable members to the class after you have serialized files. Well, it is not a problem if you don´t care if you have to type in all your saved data again every time you change anything instead of deserialize it (read it) from your file of course :)
    Situations like this may be handled if you define your own (private) writeObject(ObjectOutputStream) and your own readObject(ObjectInputStream) methods in your serializable class but there is a better a lot smarter way to handle this. Use of a serialization proxy! how to use that is described in the excellent book Effective Java 2nd ed. With a serialzation proxy for every serializable version of your class (where a version corresponds to a version of your class with differences in its number of serializable members) may your class deserialize data written from elder versions of your class also. Actually is it first since I read the last chapter of Effective Java that I think I have myself begin to understand serialization well enough and I recommend you to do the same to learn how to use serialization in practice.

  • Static method

    If I'm trying to write a method that accepts a String argument and prints it on the screen, but the method itself is supposed to return nothing, what exactly does that mean???
    This is the question itself:
    Write the definition of a class� Telephone . The class� has no constructors� and one static� method� printNumber . The method� accepts a String�argument� and prints it on the screen. The method� returns nothing.
    However, all I really am asking for is maybe some tips on understanding the concept itself. I've been looking through the tutorials online, but I just haven't found anything that explains this outright.
    To give an idea of where I am going completely, embarassingly wrong, here is what I tried to write (which I know!! it's probably far off!):
    import java.util.Scanner;
    public class Telephone
    void printNumber ()
    String lineIn;
    Scanner scan = new Scanner(System.in);
    lineIn = scan.nextLine();
    System.out.println(lineIn);
    Now please, laugh quietly to yourself and then help :P
    Thanks!

    the method itself is supposed to return nothing, what exactly
    does that mean???
    Now please, laugh quietly to yourself and then help
    :P
    Thanks!"return nothing" most probably means that the method has a void return type, and no return statement in the body of the method. Looks like you got that part right in your code.
    I would guess that the other part would be solved by adding the static key word to your method declaration. It should also probably be public, so that other classes can call it.
    So:
    public static void printNumber()
       // body of method goes here
    }Good luck,
    RD-R
    � {�
    Mon Mar 07 00:38:07 EST 2005
    Pseudo-random saying number 525 of 635
    A limerick packs laughs anatomical
    Into space that is quite economical.
            But the good ones I've seen
            So seldom are clean,
    And the clean ones so seldom are comical.

  • Non-static method/object cannot be referenced from a static context...?????

    What does this mean. I know about static, but I don't understand why I get this so many times.
    I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
    public class Test extends JFrame
        public Test
            setSize( 100, 100 );
            show();
    public static main( String args[] )
        Test window = new Test();
        draw();
    public void draw()
        blablabla whatever I want to do, a lot of times I can't.....
    }Why is this, what is the reason for Java to forbid this and what can I do about it?

    Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
    There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
    On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
        Test window = new Test();
        // maybe some code to generate something to draw???
        window.draw();
    }This is what I think you are trying to do.
    On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
    Doug

  • Abstract static methods

    Hello,
    I've written an abstract class, called AbstractNetworkParticipant. I've also written two sub classes that extend this class. I'm in the process of writing a Viewer class that I'm intending to parameterized with some subclass of AbstractNetworkParticipant,
    public class Viewer<T extends AbstractNetworkParticipant> I would like to include a couple of static methods that return Strings for Labeling information to a particular subclass in the Viewer.
    So for example, if I have NetworkUser and NetworkAdministrator, both of which extend AbstractNetworkParticipant, I would like to set the text of a JLabel labeling the participant's name to "User Name", or "Administrator Name" depending on the type of participant being viewed.
    I would like the method that returns these strings to be static, so that I don't have to have an instance of the current subclass when I initializes the JLabel. An abstract method cannot be static. I attempted to make a non-abstract static method in the abstract class,
      public static getDescriptor() {
         return "Participant";
      }and then override it in each sub class to a more descriptive string (User, or Administrator). However, when I reference the method, it always invokes the method defined in the abstract parent class, rather than in the subclass, whichever it may be.
    Can anyone suggest a solution. Should I just forget about the method being static? Is there a better way to implement a solution to this problem?
    Thanks
    Edited by: paulwooten on Mar 27, 2009 9:58 AM

    paulwooten wrote:
    The whole point of my original post was in order to learn something about Java that I'm not particularly familiar with. I was having a difficult time articulating the problem precisely, so I tried to draw an analogy between C++ and Java. It turns out I was mistaken in the way C++ works. Fortunately I described my problem adequately enough to both 1. be corrected about how virtual functions actually work in C++, and 2. get advice on how to approach the problem in Java. I never claimed I was a C++ expert, or that I was asking a question about C++. I was just trying to explain my problem as precisely as possible.
    I don't mean to disrespect, but your post, and slimy's aren't nearly as constructive as all the other posts that actually addressed my question; either to me personally, or to anyone else who has a similar question and may happen to read this thread. It's not like I dumped a bunch of C++ code here and begged someone to translate it for me. I asked a question, to the best of my ability, several other forum members replied (without giving me a mini lecture on how to learn Java), and now the problem is resolved.Sorry for the confusion. I wasn't complaining about your post. My post wasn't directed at you at all. It's fine to know C++, and to ask how to do something similar in Java. As you said, that wasn't even how you asked your original question. You asked a legitimate question to learn Java, a few people made suggestions, you made a comparison to C++, and people corrected your understanding both of C++ and Java. That's all well and good, and it's a fair way to learn. I see no problem with any of that.
    What exactly does "learn Java properly" mean? Read the tutorials and pretend like no other programming languages exist?I was referring to slimy's post where he talked about "knowing C++ properly if you use it as an input to Java". The point of my post was supposed to be that "you can know C++ properly, but +you shouldn't always use that as your input to Java+". A very simple example I've seen of what I meant by "non-proper" Java code, in real [but +bad+ ] Java code at a real company is for String comparison:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (abc.compareTo(xyz) != 0) { // Not "proper" Java
       doSomething();
    if (xyz.compareTo(another) == 0) { // Not "proper" Java
       doSomethingElse()
    }To me, that looks like someone who copied their C++ knowledge (or, at least, C knowledge) to the extreme. In C, the only function to test equality of two C "strings"--i.e., "null-terminated char arrays" is 'strcmp', and you test equality of the strcmp result to 0 to determine whether two "null-terminated char arrays" represent the same thing:
    char abc [] = "abc";
    char xyz [] = "xyz";
    char another [] = "xyz";
    if (strcmp(abc, xyz)) { // could include explicit != 0, but not needed in C
       doSomething();
    if (!strcmp(xyz, another)) { // anything non-zero is true in C, so !0 is true
       doSomethingElse();
    }"compareTo" sounds like "strcmp", and the comparison to 0 is the same in my above examples.
    But, in Java, there is a real "equals" method for Strings, and it should be used:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (!abc.equals(xyz)) { // "proper" Java
       doSomething();
    if (xyz.equals(another)) { // "proper" Java
       doSomethingElse()
    }I would argue that using "compareTo" to test equality of Strings in Java is "non-proper" Java, and using "equals" to test equality of Strings in Java is "proper" Java. That was my definition of "learning Java properly".
    I certainly don't think anyone learning Java needs to pretend that no other programming languages exist--it is fine to know other languages, and to look for the similarities (and differences). However, someone learning Java (or any other language new to them) does need to know that things don't work the same in all languages, so, if they base all of their knowledge by trying to get Java to work exactly the same as C++ (or whatever previous language they knew), their Java will not be "proper" Java. There are often multiple ways to do things "properly" in Java, but copying a C++ program verbatim into Java syntax is not necessarily going to result in the best Java code that you could have. When doing the translation from another language to Java (I realize that isn't your goal, but for some people, that is the goal), you need to be sure that your Java code follows Java rules and standards, and not just assume that the architecture of your Java code should be the same as the architecture of your code in the original language.
    I hope that clarifies my intentions. As I said, I wasn't directing my previous comment to you. I think your question and learning approach are absolutely fine.

  • No warning for 'name clash' of static methods

    The background is that I am trying to design a package which allows conversion methods to be 'plugged-in' to a class within a class hierarchy so that users can choose how objects are converted to double values. (For example, a 'city-block' conversion might be used instead of the Euclidean-distance one for class TwoD below.) I am trying to use generics to ensure that only converters specific to the appropriate class can be 'plugged-in' and also to simplify the definition of new converters.
    The issue that has arisen is a case which is not 'type-safe', in that the behaviour is not what I would expect from the type specifications, yet no warning is given. The full code is below.
    public abstract class Base {
        public abstract Converter getConverter();
        public double convert() {
            return this.getConverter().convert(this); // produces a warning
    public class OneD extends Base {
        static Converter<OneD> converter;
        int x;
        public OneD(int x) {
            this.x = x;
        public static void setConverter(Converter<OneD> c) {
            converter = c;
        public Converter getConverter() {
            return converter;
    public class TwoD extends OneD {
        static Converter<TwoD> converter;
        int y;
        public TwoD(int x, int y) {
            super(x);
            this.y = y;
        public static void setConverter(Converter<TwoD> c) {
            converter = c;
        }                                   // compiles OK with no warning
        public Converter getConverter() {
            return converter;
    public abstract class Converter<T> {
        public abstract double convert(T val);
    public class OneDConverter extends Converter<OneD> {
         public double convert(OneD val) {
            return val.x;
    public class TwoDConverter extends Converter<TwoD> {
        public double convert(TwoD val) {
            return Math.sqrt(val.x * val.x + val.y * val.y);
    public class Test {
        public static void main(String[] args) {
            OneD x1d = new OneD(1);
            TwoD x2d = new TwoD(1, 1);
            OneD.setConverter(new OneDConverter());
            TwoD.setConverter(new TwoDConverter());
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
            TwoD.setConverter(new OneDConverter());
              // wrong type of converter; should not be allowed
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
    }This produces the output:
    Convert OneD(1): 1.0, Convert TwoD(1, 1): 1.4142135623730951
    Convert OneD(1): 1.0, Convert TwoD(1, 1): 1.0The first line of this shows that the all is working OK, but in the second line we see that the wrong type of converter has been plugged-in to class TwoD, with no complaints or warnings at compile or run-time. I understand why this is so (as a result of erasure), but I am surprised that no warning is given that the static method setConverter() in class TwoD clashes with the one in OneD. Is this really type-safe behaviour? (If the two methods are made instance methods instead of static, the code does not compile because of a 'name clash' error.)
    Incidentally, an 'unchecked warning' arises because of the use of the raw class Converter in class Base, but I cannot figure out how to avoid this. The warning is right, and signals that we cannot be sure that the converter is the appropriate type for the argument. It is up to subclasses to ensure this and I cannot figure out how to guarantee that it will be so.

    public abstract class Base {
    public abstract Converter getConverter();
    public double convert() {
    return this.getConverter().convert(this); // produces a warning
    }Some of the problems you're seeing can be resolved
    by organizing your code better:
    abstract class Base<T extends Base<T>> {
        public abstract Converter<T> getConverter();
        public double convert() {
            return this.getConverter().convert(getThis());
        abstract protected T getThis();
    class OneD extends Base<OneD> {
        static Converter<OneD> converter;
        int x;
        public OneD(int x) {
            this.x = x;
        public static void setConverter(Converter<OneD> c) {
            converter = c;
        public Converter<OneD> getConverter() {
            return converter;
        protected OneD getThis() { return this; }
    class TwoD extends Base<TwoD> {
        static Converter<TwoD> converter;
        int y;
        int x;
        public TwoD(int x, int y) {
            this.x = x;
            this.y = y;
        public static void setConverter(Converter<TwoD> c) {
            converter = c;
        public Converter<TwoD> getConverter() {
            return converter;
        protected TwoD getThis() { return this; }
    abstract class Converter<T> {
        public abstract double convert(T val);
    class OneDConverter extends Converter<OneD> {
         public double convert(OneD val) {
            return val.x;
    class TwoDConverter extends Converter<TwoD> {
        public double convert(TwoD val) {
            return Math.sqrt(val.x * val.x + val.y * val.y);
    class Test {
        public static void main(String[] args) {
            OneD x1d = new OneD(1);
            TwoD x2d = new TwoD(1, 1);
            OneD.setConverter(new OneDConverter());
            TwoD.setConverter(new TwoDConverter());
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
            TwoD.setConverter(new OneDConverter());  // error
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
    }

  • Static methods inside class in jsp can't make it work

    Hello all i can't understand it why i can't declare the method as static method ?
    public class Request{
              Request(){}
              private String paramValue;
              public static String getRequestParam(HttpServletRequest request, String paramName, String defaultValue){
                   paramValue = request.getParameter(paramName);
                   return paramValue != null ? paramValue : defaultValue;
    im geting this error :
    The method getRequestParam cannot be declared static; static methods can only be declared in a static or top level type
    can't i do inner class ?
    or other sulotion for me not to make instences of class's but to use the class static methods?

    Hi, try this:
    public class Request{
              Request(){}
              private static  String paramValue;
              public static String getRequestParam(HttpServletRequest request, String paramName, String defaultValue){
                   paramValue = request.getParameter(paramName);
                   return paramValue != null ? paramValue : defaultValue;
          }it should work. the problem in you code is that you are trying to referance an non-static object with a static one!
    Message was edited by:
    Adelx

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Dont understand Synchronized method to complete program

    I'm trying to finish theis program but i don't understand synchronized methods. I checked the java tutorial and i am still confused. Can someone help me approach finishing this program. Here is the spec and the first part of the program i have done.
    ===================================================================================
    When the above is working, create a class called Food. The objective here is to demonstrate the behavior of threads that share data, and use synchronized methods.
    Simulating an animal eating, simply means that the thread will sleep for some length of time.
    There is one instance of the Food class that is shared by both of the animals. Pass it to the constructor of the Animal class.
    There is a method in the Food class called eat(). This method is synchronized, i.e., only one Animal can be eating at a time.
    The rabbit eats the food (the thread will sleep) for a longer time than the turtle, thus giving an advantage to the rabbit.
    But, the turtle must wait until the rabbit is done eating until it can eat, so the advantage is reduced. Print out a message in the eat method when the animal begins to eat, and when it is done eating. Indicate which animal it is that starts to eat.
    Try making the eat method not synchronized, and observe the different behavior if the eat method allows the rabbit to begin eating before the turtle is done eating
       import java.util.Random;
        public class Animal extends Thread implements Runnable{
          private String name;
          private int position;
          private int speed;
          private int restMax;
          public static boolean winner = false;
          Random random = new Random();
           public Animal (String name, int position, int speed,int restMax){
             this.name = name;
             this.position = position;
             this.speed = speed;
             this.restMax = restMax;
           public void run(){
             try{
                while( winner == false){
                   if(position < 100){
                      Thread.sleep(random.nextInt(restMax));
                      position += speed ;
                      System.out.println(name+" is in "+ position+" position ");
                   if (position >= 100){
                      winner = true;
                      System.out.println(name+" is the winner");
                      System.exit(0);
                 catch(InterruptedException e){
           public static void main(String[] args){
             Animal rabbit = new Animal("trix", 0, 5, 150);
             Animal turtle = new Animal("maury",0, 3, 100);
             rabbit.start();
             turtle.start();
       }

    Example:class Donkeyphile implements Runnable {       
        private Donkey donkey;
        private long time;
        Donkeyphile(Donkey donkey, long time) {
            this.donkey = donkey;
            this.time = time;
        public void run() {
            for (int i = 0; i < 10; i++) {
                donkey.love(time);
        public static void main(String[] args) {
            Donkey donkey = new Donkey();
            Donkeyphile jverd = new Donkeyphile(donkey, 500);
            Donkeyphile yawmark = new Donkeyphile(donkey, 100);
            Thread j = new Thread(jverd, "Jverd");
            Thread y = new Thread(yawmark, "Yawmark");
            j.start();
            y.start();
    class Donkey {
        synchronized void love(long time) {
            String name = Thread.currentThread().getName();
            System.out.println(name + " hugs the donkey.");
            try { Thread.sleep(time); } catch (InterruptedException e) { }
            System.out.println(name + " releases the donkey.");
    }

  • Trying to understand Android OS updates delays

    This is not another hate mail, it´s more about trying to understand the facts and motives regarding the OS updates (or lack of).
    Hopefully this material will arrive at someone from Sony with enough power to do something about it.
    Ever since I can remember, Sony has been THE brand for electronics. I can´t remember a TV or VCR in my house that it wasn´t Sony, and they lasted for LOTS of years.
    When a couple years ago I finally had the money (and the need) for a Smartphone, i chose the X10 Mini, which is a great little phone from a great brand, but it´s stuck at Android 2.1... which makes it a crippled android nowadays...
    It really bothered me the lack of OS updates, so I chose to buy a Galaxy Nexus, but it´s really expensive in my country. So my second option was a Galaxy Ace 2, but they haven´t arrived to my country yet, so I went with my third option: Xperia Sola, knowing beforehand that it´s a great phone, a great brand, but I might get slow OS updates.
    I bought it about 10 days ago when I saw they were starting to roll out the updates.
    10 days later I still don´t have my update. And not only that, but I don´t see much light at the end of the tunnel...
    I found a thread with the SI numbers that were updated, and there were a bunch on Oct 1, another bunch on Oct 4, and one code on Oct 8, and no other update since...
    I also read that those who did get the update, were having bugs with the OS, and also found threads from other Xperia models, whose updates began rolling 3 months ago, and there is still people who hasn´t gotten the update...
    As a customer, and a owner/CEO of a small company, I have a really hard time understanding how a HUGE company like Sony can be making such mistakes...
    I have been thinking objective reasons, and I can only think of one. I know it´s a wild guess, but I´m starting to think that our salvation might be the very thing that means our condemnation: CYANOGENMOD!!!
    Think about it: Why would Sony spend more money hiring twice as much programmers, when they can make only one update per phone, and sit down and see how CM releases begin to appear, for all tastes and needs. And... IT´s FREE!!!
    Also, if there is a software related problem (way more likely than a hardware problem), then the CM developers take the fall, instead of Sony. And I´m beginning to see custom OS installers that are more user friendly, so it might be something that they take in accout when neglecting OS updates.
    If that´s the line Sony is following, it´s a very risky move and it won´t work. Sony Mobile will crash and burn, but it´s still a better business plan that "let´s get lazy and make ULTRA slow updates so we don´t spend a lot of money programming".
    If you can´t afford more programmers, stop including so much bells and whistles and make your OS near vanilla. Include a couple of Xperia menus, a custom theme and voila!
    The main reason I wanted the Galaxy Nexus is Vanilla OS, which means inmediate OS updates. Sony on the other hand, takes a year or two to release it after its launch. If they release it at all...
    Another though...  why not stop making that many different phones! Really! There are like 5 Xperia models i can´t tell one from the other... even with specs side by side!
    You are trying to make too many phones and you are failing with all of them! (Software and software updates are also part of the phone, one of the most importants...)
    I know hiring programmers is expensive, but you are sacrificing one of the most expensive values for a company EVER: Customer credibility! Which as you know better than me, takes years to create.
    If Apple had problems with carriers and code aprooving and stuff, they might get away with it, becouse they alone have all the devices. If iOS 6 is delayed a few months, it´s delayed for everyone, and besides Apple fanboys rarely complain about Mac products, but Android is a more independent and educated market.
    I´m not saying that Apple users are ignorant, not at all, but I´m pretty sure most iPhone owners don´t even know what processor or how much RAM their phone has. They just "swallow" the Apple Way of Life. (it´s a good phone becouse Apple says so).
    The Android user on the other side, because of the fragmentation of the market, has many brands and models to choose from. An Android user about to buy a new phone will most likely go online looking for different models, specs, reviews in webs and forums...etc.
    You can´t say "I don´t know how HTC and other companies get their updates so soon, but we take a lot more becouse Google and the Operators must aproove the code.", because there are many other brands that have exactly the same difficulties or more, since they are smaller, and we can SEE online that they are indeed delivering solid and relativly fast updates.
    Did we miss something? Does HTC use Witchcraft to get their code aprooved?
    My underlying point is this: You are getting lazy... VERY lazy with software programming for your phones, and WE KNOW IT!
    It´s not the "difficulties" you claim, becouse every brand has those difficulties.
    This isn´t 1999 you know. We are in the information age. If you lie to us and tell us that your phones have the latest OS, I can go online and see that you don´t (Hello!!!). If I see that the company lies to it´s customers, I will stop buying their products. If I´m so dissapointed with how Sony handles OS updates and their customers queries about it, then I want for the first time ever to sell my Cell Phone becouse I´m not happy with it, or the brand behind it.
    We also live in the "Here and now" age. You can´t expect your customers to read about new Android releases on news and blogs, and wait YEARS with arms crossed waiting for their update... The world doesn´t work like that. Not anymore at least...
    It´s not a matter of how many recources you have, it´s about how you use and balance them. GIVE MORE IMPORTANCE TO SOFTWARE UPDATES! IT´S WAY MORE IMPORTANT THAT YOU THINK! LISTEN TO YOUR CUSTOMERS!!!
    You guys are Sony are smart and design great products, but you are not GOD! You are not our wife, no one has sworn alliagence to you.
    If you stop giving us good products and start lying to us, we hate you and stop giving you our money. Simple as that.
    My sola is beatiful, I love the design, the screen, the hardware... but it hasn´t been updated yet to 4.0, not to mention 4.1, which REALLY is the latest version... so stop advertising that your phones have the latest Android OS, unless you want angry customers switching to other companies, which you are getting.
    I also read some stories that Androind 4.0 was announced for the Xperia PLAY, and then it was called off... Do you have any idea how pissed I would be and ripped off I would be if I bought my phone based in that information and then you say it won´t be available?
    Well, actually right now my possition is worse, since you SAY you will update my phone, but you don´t say when, and I read online about people still not getting their updates months after the rollout started, so I´m in the limbo right now...
    As a company, one of the worse things you can do is calling your customers stupid, and when I see the answers you give in this forum, then I feel insulted. I feel like they are talking to an idiot or ignorant person with the so called "diplomatic" answers, which are basicly empty excuses for not doing your job right.
    You gave us the frikking CDs, DVDs and Blu-Rays!!! Don´t tell us you can´t tweak an already built OS in a year!
    I really hope you change their OS update policies really soon, before you lose the already small cellphone market share you have, or at least change your P.R. and C.M. policies towards a more open one.
    We all are humans and make mistakes, but we customers really appreciate honesty and truth.
    Have an open conversation with your customers! Don´t lie about your shortcomings! Accept then and ask the community to help you solve them, ask them what they biggest problems are, what features are most important to them, how often do they expect updates... LISTEN TO THEM!!
    "Succes is a meneace. It tricks smart people into thinking they can´t lose."
    Ps: Nothing personal with the mods from this forum, I´m not killing the messenger, I know that you can ONLY give the info you are allowed to give, and even if you wanted, you probably don´t know the answers yourself, since you work in the Communications department, not Developement or anything technical, and if you can't give any given info, then they probably won´t give it to you either... My message is to the company as a whole. I just hope you will be a good messenger and give this to whoever needs to read it.

    My bad, it´s closer to 40 the number of phones released hehe
    I know it´s all about money, and I know Sony is obligated to neglect users who haven´t given them money after an x ammount of time. However, it´s not a matter of making the phones obsolete earlier, so the users want to buy a new phone faster and therefore getting more money.
    A person will buy a new phone when he/she has the money to do so and wants to do so.
    It´s not a matter of WHEN. It´s a matter of WHAT.
    The question is not "When will that user buy a new phone?", but rather "When that user buys a new phone, whenever that is, what phone will it be?"
    I have a love/hate relationship with Apple. I would never use a iPhone. I would love having any Mac, if someone gives it to me, but I would never spend my harn earned dollars on such an overpriced piece of hardware over general principals.
    However, i do recognice that Steve Jobs was a business genius. Weather you like or love his ideas and methods, he turned a garage project into the biggest company in the world, with a market value higher than Exxon with 1/3 of it´s assets.
    Apple is a money making machine, and that is where the "hate" part of my relationship comes from.
    However, it surprised me a lot to see that they released iOS 6 for the iPhone 3GS, released in 2008!
    That get´s you thinking, that inside all that "SELL NOW" culture Apple is, they also support their older devices that people bought years ago but can't buy a new phone now. However, when they can do it, it will surely be another iPhone. Because they FEEL that the company listens and cares for them.
    Also if you jump from iOS 6 on the 3 GS to a brand new iPhone 5, the transition will be virtually non-existant, except for Siri and a couple of features.
    However jumping from Android 1.5 or 2.1 to Jelly Bean, might not be so easy on some users, making them more likely to give iPhone a shot.
    Since they have to adapt to another phone anyway, they might as well try the apple...
    And for old users, it gives people a sense of continuity and care about the user. Otherwise we feel like being kicked out of a restaurant right after we payed the bill.

  • Can you set a global EntityResolver (via system property, or static method)

    I'm trying to set a customized EntityResolver (telling the xml parser where to look for XML schema files).
    Usually, you'd use the standard syntax - somehting like:
    SaxParser parser=new SaxParser();
    parser.parser.setEntityResolver(myResolver);
    However, I was wondering whether you can set a "global" EntityResolver, to be used as default for all parsers ?
    Maybe this can be done through some system property, or a static method somewhere in the parsing XML ?
    (BTW, I need it because I'm using some third-party API, that encapsulates a SaxParser, but won't let me access it, so I can't configure it directly).
    thanks.

    I don't think you can.
    What is possible is to set content on the folder resource itself; that would be returned instead of the page you mentioned.

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

Maybe you are looking for

  • How do you remove apps from the App Store

    Just wondering if you delete or get rid of the old apps not being used. Always getting updates I don't need it's, annoying would like to get rid of them

  • Need info to configure SSL for Portal Server in EP6SP2

    Hello, We need to configure SSL for Portal Server. We are using J2EE 6.20 Patch 25 and EP6SP2P4. The ITS is already using https and it creats lots of Session issues since Portal is not in https. Is there any OSS Note or How to guide to configure Port

  • .mov!!!!!

    Can I or not import .mov file with compressor. Than convert it to mpeg2

  • Get xmlType column into xsql page

    I have a table with normal columns such as string types, plus one xmlType column. For example, the xmltype column can be <mark>ibm</mark>. In xsql page, I tried to select all the columns out (including the xmltype col). I want the xml column as part

  • XML wont load

    hello, im using this great tutorial from gotoandlean.com but have run into some problems im trying to load jpg's into a flash with xml, using the following code var x:XML = new XML (); x.ignoreWhite = true; var urls:Array = new Array(); var captions: