Static methods.. help

Hi
What is the difference by having a method as protected static instead of public static
I will greatly appreciate any answers

If a method is public static it can be called from anywhere. If it's protected it can only be called from the package or subclasses.
public class Foo {
  public static void blah() { ..... }
public class Foo2 {
  public static void main(String[] args) {
    Foo.blah();
}The above is legal. The following isn't:
package com.foo;
public class Foo {
  public static void blah() { ..... }
package com.foo2;
public class Foo2 {
  public static void main(String[] args) {
    Foo.blah();
}Hope that helps,
m

Similar Messages

  • Non-static method help..

    Hello..
    I am new to Java and trying to create a Binary Tree, however I have encountered an error "non-static methos cannot be referenced from static context?" and I am unsure how to correct it.. I have C++ background and am unfamiliar with this type of error?
    My BTNode class:
    public class BTNode
        private Object data;
        private BTNode left, right;
        public BTNode(Object initialData, BTNode initialLeft, BTNode initialRight)
                data = initialData;
                left = initialLeft;
                right = initialRight;
        public BTNode()
                { this(null, null, null); }
        public BTNode(Object newdata)
                { this(newdata, null, null); }
        //NODE methods
        public Object getData()                     //return and set data in node
                {return data;}
        public void setData(Object data)
                {this.data = data; }
        public BTNode getLeft()                 //return and set left child
                {return left; }
        public void setLeft(BTNode left)
                {this.left = left; }
        public BTNode getRight()                //return and set right child
                {return right; }
        public void setRight(BTNode right)
                {this.right = right; }
        public boolean isLeaf()                 //return true if this is leaf node
                {return (left == null)&&(right == null); }
    // TREE Methods - for tree starting at this node
    // get specific data from a tree
            public Object getLeftmostData()
            { if(left == null)
                   return data;
              else
                  return left.getLeftmostData(); }
            public Object getRightmostData()
                  { if(right == null)
                   return data;
              else
                  return right.getRightmostData(); }
    // print data in a tree
            public void inorderPrint()
                        if (left != null)
                            left.inorderPrint( );
                        System.out.println(data);
                        if (right != null)
                            right.inorderPrint( ); }
            public void preorderPrint()
                        System.out.println(data);
                        if (left != null)
                            left.preorderPrint( );
                        if (right != null)
                            right.preorderPrint( ); }
            public void postorderPrint()
                        if (left != null)
                            left.postorderPrint( );
                        if (right != null)
                            right.postorderPrint( );
                        System.out.println(data); }
    // pretty print a tree
            //public void print(int depth);
    //Interface for Nodes in Binary Tree (3)
    //removing nodes from a tree
    //returns reference to tree after removal of node
            public BTNode removeLeftmost()
                        if (left == null)                               // we are as deep as we can get
                            return right;                               // remove this node by returning right subt ree
                        else
                            {                                           // keep going down recursively
                                left = left.removeLeftmost( );
                                                                        // when done, return node that act ivated this
                                                                        // method as root of t ree
                                return this; }}
            public BTNode removeRightmost()
                        if (right == null)                               // we are as deep as we can get
                            return left;                               // remove this node by returning left subt ree
                        else
                            {                                           // keep going down recursively
                                right = right.removeRightmost( );
                                                                        // when done, return node that activated this
                                                                        // method as root of tree
                                return this; }}
    //returns number of nodes in tree
            public static long treeHeight(BTNode root)
                        if (root == null)
                            return -1;
                        else
                            return 1 + Math.max(treeHeight(root.left),
                                    treeHeight(root.right));
            public static long treeSize(BTNode root)
                    if (root == null)
                        return 0;
                    else
                        return 1 + treeSize(root.left) + treeSize(root.right);
    //copying a tree: returns reference to root of copy
           // public BTNode treeCopy(BTNode root);
        public static BTNode insertNode(BTNode root, int key){
                if (root == null) // null tree, so create node at root
                    return new BTNode(new Integer(key));
                Integer data_element = (Integer) root.data;
                if (key <= data_element.intValue())
                    root.setLeft(insertNode(root.left, key));
                else root.setRight(insertNode(root.right, key));
                    return root; }
        public static BTNode findNode(BTNode root,int key){
                if (root == null)
                    return null; // null tree
                Integer data_element = (Integer) root.data;
                if (key == data_element.intValue())
                    return root;
                else
                if (key <= data_element.intValue())
                    return findNode(root.left, key);
                else return findNode(root.right, key); }
        public static BTNode removeNode(BTNode root, int key){
                if (root == null) return null;
                    Integer data_element = (Integer) root.data;
                if (key < data_element.intValue())
                    root.setLeft(removeNode(root.left, key));
                else if (key > data_element.intValue())
                    root.setRight(removeNode(root.right,key));
                else { // found it
                if (root.right == null) root = root.left;
                    else if (root.left == null) root = root.right;
                        else {                                         //two children
                                Integer temp = (Integer)
                                root.left.getRightmostData();
                                root.setData(temp);
                                root.setLeft(root.left.removeRightmost());
                return root; }
    Main class:
    import java.util.Random;
    public class Lab21 {
        /** Creates a new instance of Lab21 */ 
         * @param args the command line arguments
        public static void main(String[] args) {
            int UpperLimit = 50000;
            int Num_Nodes = 500;
            Random generator = new Random();
            int TR_create = generator.nextInt(UpperLimit);
            Integer cast = new Integer(TR_create);                  // Needed to cast initial value to BTNode object
            BTNode Tree_Root = new BTNode(cast);                    // Creating root object
            BTNode result = new BTNode();                           // Creating new node object to use for tree
            result.insertNode(Tree_Root,TR_create);                 // Inserting first Node
            if (UpperLimit <=0)
                    throw new IllegalArgumentException("UpperLimit must be positive: " + UpperLimit);
            if (Num_Nodes <=0)
                    throw new IllegalArgumentException("Size of returned List must be greater than 0.");
            for( int x = 0; x < Num_Nodes; ++x)  
                    int value = generator.nextInt(UpperLimit);
                    result.insertNode(Tree_Root,value);
            //BTNode.inorderPrint();
            System.out.println("The height of this tree is " + BTNode.treeHeight(Tree_Root));
            System.out.println("The smallest number in the tree is " + BTNode.getLeftmostData());
    }The error is occuring with the last line where I am trying to access getLeftmostData();
    Any help would be apprecited with this..
    Thankyou

    User 557835:
    You need to use the name of the instance rather than the name of the class. It should be something like this:System.out.println("The smallest number in the tree is " + result.getLeftmostData());User 135880

  • Help with writing a static method in my test case class inside blue j

    I have this method that I have to test. below is the method I need to test and what I have to create inside my test case file to test it Im having big time problems getting going. Any help is appreciated.
    public String introduceSurprise ( String first, String last ) {
    int d1 = dieOne.getFace();
    Die.roll();
    if (d1 %4 == 2){
    return Emcee.introduce(first);
    else {
    return this.introduceSpy (first,last);
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!

    hammer wrote:
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!Those instructions couldn't be anymore straightforward. Make a class called TestEmCee. Have it create an EmCee object. Call introduceSurprise on that object 3 times. Then print the results of calling it a 4th time.

  • Help on calling static method in a multithreaded environment

    Hi,
    I have a basic question.. pls help and it is urgent.. plss
    I have a class with a static method which does nothing other than just writing the message passed to a file. Now i have to call this static method from many threads..
    What actually happens ???
    Does all the thread start to execute the static method or one method executes while the other threads wait for the current thread to complete execution?. I am not talking about synchronizing the threads...my question is what happens when multiple threads call a static method??
    Pls reply.. I need to design my project accordingly..
    Thanks
    Rajeev

    HI Omar,
    My doubt is just this..
    I wanted to know what might happen if two threads try to access a static method.. Logically only one thread can use the method since it is only only copy... but i was wondering what might happens if f threads try to access the same static method.. My Situation is this.. I have a cache which is just a hash table which will be only one copy for the whole application.. No when i get a request I have to check if the id is avaible in the cache. if it is available i call method 1 if not i call method2. Now Ideally the cache should be a static object and the method to check the id in the cache will be a normal instance method..
    I was just wondering what might happen if i make the method static.. If i can make it static i can can save a lot of space by not creating the object each time.. u know what i mean.. That y i wanted to know what happens..
    Rajeev

  • Help with static method issue.

    Hi everyone,
    There's a recent thread on the forum along a similar vein as this one but I hope mine doesn't cause as much annoyance! My homework assignment involves implementing three interfaces provided by my professor in order to create weighted, undirected graphs. The classes I have to implement are Node, Edge and Graph. Here are the Edge and Node interfaces for reference; they weren't too hard to implement:
    public interface Edge {
         public Edge createEdge(String name, int ID, float weight);
         public Node getStartNode();
         public void setStartNode(Node n);
         public Node getEndNode();
         public void setEndNode(Node n);
         public String getName();
         public int getID();
         public float getWeight();
         public String toString();
    public interface Node {
         public Node createNode(String name, int ID, float weight);
         public Node[] getNeighbours();
         public Edge[] getEdges();
         public void addEdge(Edge e);
         public void removeEdge(Edge e);
         public String getName();
         public int getID();
         public float getWeight();
         public String toString();
    }Now, one of the graphs I should be aiming to create is this one ( [http://i35.tinypic.com/2iqn62d.gif|http://i35.tinypic.com/2iqn62d.gif] ) so I apologize for the code I'm about to show and its length. It's the Graph class:
    import java.util.ArrayList;
    public class Graph {
         public static void main(String [] args) {
              // Create all nodes
              int i = 1;
              Node food = new Node();
              food.createNode("Food", i, 0);
              i++;
              Node healthy = new Node();
              healthy.createNode("Healthy", i, 4f);
              i++;
              Node neutral = new Node();
              neutral.createNode("Neutral", i, 0);
              i++;
              Node unhealthy = new Node();
              unhealthy.createNode("Unhealthy", i, -4f);
              i++;
              Node orange = new Node();
              orange.createNode("Orange", i, 6f);
              i++;
              Node cabbage = new Node();
              unhealthy.createNode("Cabbage", i, 3f);
              i++;
              Node riceCake = new Node();
              unhealthy.createNode("Rice cake", i, 2f);
              i++;
              Node chocolate = new Node();
              unhealthy.createNode("Chocolate", i, -2f);
              i++;
              Node bacon = new Node();
              unhealthy.createNode("Bacon", i, -4f);
              i++;
              Node xmasPud = new Node();
              unhealthy.createNode("Christmas Pudding", i, -8f);
              i++;
              // Create all edges
              int n = 1;
              Edge food1 = new Edge();
              food1.createEdge("to healthy", i, -4.0f);
              food1.setStartNode(food);
              food1.setEndNode(healthy);
              n++;
              Edge food2 = new Edge();
              food2.createEdge("to neutral", i, 0);
              food2.setStartNode(food);
              food2.setEndNode(neutral);
              n++;
              Edge food3 = new Edge();
              food3.createEdge("to unhealthy", i, -4f);
              food3.setStartNode(food);
              food3.setEndNode(unhealthy);
              n++;
              Edge healthy1 = new Edge();
              healthy1.createEdge("to orange", i, 4f);
              healthy1.setStartNode(healthy);
              healthy1.setEndNode(orange);
              n++;
              Edge healthy2 = new Edge();
              healthy2.createEdge("to cabbage", i, 2f);
              healthy2.setStartNode(healthy);
              healthy2.setEndNode(cabbage);
              n++;
              Edge neutral1 = new Edge();
              neutral1.createEdge("to rice cake", i, 2f);
              neutral1.setStartNode(neutral);
              neutral1.setEndNode(riceCake);
              n++;
              Edge unhealthy1 = new Edge();
              unhealthy1.createEdge("to chocolate", i, -2f);
              unhealthy1.setStartNode(unhealthy);
              unhealthy1.setEndNode(chocolate);
              n++;
              Edge unhealthy2 = new Edge();
              unhealthy2.createEdge("to bacon", i, -4f);
              unhealthy2.setStartNode(unhealthy);
              unhealthy2.setEndNode(bacon);
              n++;
              Edge unhealthy3 = new Edge();
              unhealthy3.createEdge("to Christmas pudding", i, -8f);
              unhealthy3.setStartNode(unhealthy);
              unhealthy3.setEndNode(xmasPud);
              n++;
              // Assign edges to edgeList
              food.edgeList.add(food1);
              food.edgeList.add(food2);
              food.edgeList.add(food3);
              // Add node to nodeList
              nodeList.add(food);
              healthy.edgeList.add(healthy1);
              healthy.edgeList.add(healthy2);
              nodeList.add(healthy);
              neutral.edgeList.add(neutral1);
              nodeList.add(neutral);
              unhealthy.edgeList.add(unhealthy1);
              unhealthy.edgeList.add(unhealthy2);
              unhealthy.edgeList.add(unhealthy3);
              nodeList.add(unhealthy);
              // Now convert to arrays
              Node[] nodeArray = new Node; // Nodes
              nodeList.toArray(nodeArray);
              Edge[] edgeArray = new Edge[n]; // Edges
              food.edgeList.toArray(edgeArray);
              healthy.edgeList.toArray(edgeArray);
              unhealthy.edgeList.toArray(edgeArray);
              // Now turn it all into a graph
              createGraph("Food", 1, nodeArray, edgeArray, food); // doesn't work!
         public Graph createGraph(String name, int ID, Node[] nodes, Edge[] edges,
                   Node root) {
              graphName = name;
              graphID = ID;
              graphNodes = nodes;
              graphEdges = edges;
              graphRoot = root;
              return null;
         public String getName() {
              return graphName;
         public Edge[] getEdges() {
              return graphEdges;
         public void addEdge(Edge e) {
         public Edge getEdge(String name, int ID) {
              return null;
         public void removeEdge(Edge e) {
         public Node[] getNodes() {
              return graphNodes;
         public void addNode(Node n) {
              nodeList.add(n);
         public Node getNode(String name, int ID) {
              int ni = nodeList.indexOf(name);
              Node rNode = nodeList.get(ni);
              return rNode;
         public void removeNode(Node n) {
              nodeList.remove(n);
         public void setRoot(Node n) {
              graphRoot = n;
         public Node getRoot() {
              return graphRoot;
         private String graphName;
         private int graphID;
         private Node[] graphNodes;
         private Edge[] graphEdges;
         private Node graphRoot;
         private static ArrayList<Node> nodeList = new ArrayList<Node>();
    }The problem I have is that I don't know how to get around the fact that I'm making a static reference to the non-static method *createGraph*. I'd really appreciate your help. Thanks for your time!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    GiselleT wrote:
    public interface Edge {
         public Edge createEdge(String name, int ID, float weight);
    I want to kick your professor right in the grapes for this bit of idiocy. It's at the source of your problems.
    This looks very fishy and very bad. I wouldn't expect an Edge to create another Edge. Likewise for Node and Graph. You might have static factory methods in these classes, but by defining it in the interfaces, these methods have to be non-static. This leads to such ridiculous code as you have like this:
    Edge uselessEdge = new Edge();
    Edge actualEdge = uselessEdge.createEdge("abc", 1, 2.34);It's not your fault that it's useless. That's the way you have to do it with that senseless requirement.
    The problem I have is that I don't know how to get around the fact that I'm making a static reference to the non-static method createGraph.
    Static reference in non-static context errors are always addressed the same way: Either make the member in question static (usually the wrong choice) or create an instance.
    In this case, you need to do like you did with Edge, and create a useless dummy Graph whose only purpose is to create other Graphs:
    Graph graph = uselessGraph();
    Graph actualGraph = uselessGraph.createGraph(...);Then, inside the createGraph method, you'll create a Graph with new and do thatGraph.name = name; and so on for each of the parameters/members.
    Really, though, this is just an awful, awful approach though. Are you sure your prof really requires Edge to have a non-static createEdge method, and so on?

  • Help to solve the static method....pls.

    package readtext;
    import java.io.*; // For input & output classes
    import java.util.Date; // For the Date class
    public class Main {
    public Main() {
    public static void main(String[] args)
    throws IOException{
    BufferedReader in = new BufferedReader(
    new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
    *use ' ' as a separator, and rearrange back the datastream column
    String text;
    while ((text = in.readLine()) != null)
    int count = 0; // Number of substrings
    char separator = ' '; // Substring separator
    // Determine the number of substrings
    int index = 0;
    do
    ++count; // Increment count of substrings
    ++index; // Move past last position
    index = text.indexOf(separator, index);
    while (index != -1);
    // Extract the substring into an array
    String[] subStr = new String[count]; // Allocate for substrings
    index = 0; // Substring start index
    int endIndex = 0; // Substring end index
    for(int i = 0; i < count; i++)
    endIndex = text.indexOf(separator,index); // Find next separator
    if(endIndex == -1) // If it is not found
    subStr[i] = text.substring(index); // extract to the end
    else // otherwise
    subStr[i] = text.substring(index, endIndex); // to end index
    index = endIndex + 1; // Set start for next cycle
    String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
    // Directory name
    File aFile = new File(dirName, "data.txt");
    aFile.createNewFile(); // Now create a new file if necessary
    if(!aFile.isFile()) // Verify we have a file
    System.out.println("Creating " + aFile.getPath() + " failed.");
    return;
    BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
    * Display output at data.txt file
    // provide initial (X,Y,Z) coordinates for mobiles
    out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
    System.getProperty("line.separator"));
    out.flush();
    out.close();
    package readtext;
    import java.io.*; // For input & output classes
    import java.util.Date; // For the Date class
    public class create_table {
    public create_table() {
    public static void main(String[] args)
    throws IOException{
    BufferedReader in = new BufferedReader(
    new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
    *use ' ' as a separator, and rearrange back the datastream column
    String text;
    while ((text = in.readLine()) != null)
    substring(subStr); //problem at here
    String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
    // Directory name
    File aFile = new File(dirName, "data.txt");
    aFile.createNewFile(); // Now create a new file if necessary
    if(!aFile.isFile()) // Verify we have a file
    System.out.println("Creating " + aFile.getPath() + " failed.");
    return;
    BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
    * Display output at data.txt file
    // problem at here
    // provide initial (X,Y,Z) coordinates for mobiles
    out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
    System.getProperty("line.separator"));
    out.flush();
    out.close();
    static void substring(String[] subStr)
    int count = 0; // Number of substrings
    char separator = ' '; // Substring separator
    String text;
    // Determine the number of substrings
    int index = 0;
    do
    ++count; // Increment count of substrings
    ++index; // Move past last position
    index = text.indexOf(separator, index);
    while (index != -1);
    // Extract the substring into an array
    subStr = new String[count]; // Allocate for substrings
    index = 0; // Substring start index
    int endIndex = 0; // Substring end index
    for(int i = 0; i < count; i++)
    endIndex = text.indexOf(separator,index); // Find next separator
    if(endIndex == -1) // If it is not found
    subStr[i] = text.substring(index); // extract to the end
    else // otherwise
    subStr[i] = text.substring(index, endIndex); // to end index
    index = endIndex + 1; // Set start for next cycle
    *on top is the original code, bottom is after modified
    i would like to create a static method for the static void substring(String[] subStr). But when i use the substring() on the main program, the compiler give me error. Is that my substring () created wrongly?? pls help...

    package readtext;
    import java.io.*; // For input & output classes
    import java.util.Date; // For the Date class
    public class Main {
    public Main() {
    public static void main(String[] args)
    throws IOException{
    BufferedReader in = new BufferedReader(
    new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
    *use ' ' as a separator, and rearrange back the datastream column
    String text;
    while ((text = in.readLine()) != null)
    int count = 0; // Number of substrings
    char separator = ' '; // Substring separator
    // Determine the number of substrings
    int index = 0;
    do
    ++count; // Increment count of substrings
    ++index; // Move past last position
    index = text.indexOf(separator, index);
    while (index != -1);
    // Extract the substring into an array
    String[] subStr = new String[count]; // Allocate for substrings
    index = 0; // Substring start index
    int endIndex = 0; // Substring end index
    for(int i = 0; i < count; i++)
    endIndex = text.indexOf(separator,index); // Find next separator
    if(endIndex == -1) // If it is not found
    subStr = text.substring(index); // extract to the end
    else // otherwise
    subStr = text.substring(index, endIndex); // to end index
    index = endIndex + 1; // Set start for next cycle
    String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
    // Directory name
    File aFile = new File(dirName, "data.txt");
    aFile.createNewFile(); // Now create a new file if necessary
    if(!aFile.isFile()) // Verify we have a file
    System.out.println("Creating " + aFile.getPath() + " failed.");
    return;
    BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
    * Display output at data.txt file
    // provide initial (X,Y,Z) coordinates for mobiles
    out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
    System.getProperty("line.separator"));
    out.flush();
    out.close();
    package readtext;
    import java.io.*;                            // For input & output classes
    import java.util.Date;                       // For the Date class
    public class create_table {
       public create_table() {
       public static void main(String[] args)
       throws IOException{
      BufferedReader in = new BufferedReader(
              new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
       *use ' ' as a separator, and rearrange back the datastream column
       String text;
       while ((text = in.readLine()) != null)
        String[] subStr;
         String[] substring;
         int i;
       substring(subStr); //PROBLEM: substring in readtext can not apply
    String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
    // Directory name
    File aFile = new File(dirName, "data.txt");
    aFile.createNewFile(); // Now create a new file if necessary
    if(!aFile.isFile()) // Verify we have a file
    System.out.println("Creating " + aFile.getPath() + " failed.");
    return;
    BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
    * Display output at data.txt file
    // provide initial (X,Y,Z) coordinates for mobiles
    out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
    System.getProperty("line.separator") +
    "$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
    System.getProperty("line.separator"));
    out.flush();
    out.close();
    static void substring(String[] subStr)
    int count = 0; // Number of substrings
    char separator = ' '; // Substring separator
    String text;
    // Determine the number of substrings
    int index = 0;
    do
    ++count; // Increment count of substrings
    ++index; // Move past last position
    index = text.indexOf(separator, index);
    while (index != -1);
    // Extract the substring into an array
    subStr = new String[count]; // Allocate for substrings
    index = 0; // Substring start index
    int endIndex = 0; // Substring end index
    for(int i = 0; i < count; i++)
    endIndex = text.indexOf(separator,index); // Find next separator
    if(endIndex == -1) // If it is not found
    subStr[i] = text.substring(index); // extract to the end
    else // otherwise
    subStr[i] = text.substring(index, endIndex); // to end index
    index = endIndex + 1; // Set start for next cycle
    the problem is here
       String text;
       while ((text = in.readLine()) != null)
        String[] subStr;
         String[] substring;
         int i;
       substring(subStr); //PROBLEM: substring in readtext can not apply
    String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
    the system say that my substring(subStr[i]) (java.lang.String[])in read.text can not applied to (java.lang.String)...how can i solve for tis problem? is that i have to use for loop to create an array for subStr???

  • NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!

    I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
    Please reply soon!!! Thanks in advance.

    class a
    private static String aa = "";
    public static setVar (String var)
    aa = var;
    class b
    public void init()
    a.aa = "try";
    public static void main(String b[])
    b myB = new b ();
    b.init();
    hope this help;
    bye _drag                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Need Urgent Help with static methods!!!!

    If I have a static method to which a variable is being passed...for example
    static String doSomething(String str)
    //..doSomething with str and return
    If the method is invoked a second time by a separate entity when it is already in use by one entity(!!!not entity beans) .... will this lead to the second invocation overwriting str while the method is already in use and thus corrupting the variable that the method was passed from the first entity?

    It's also a common misunderstanding about parameters. The method does not receive a variable as its parameter, it receives a reference to an object. And inside the method, the parameter acts just the same as a local variable would. So if two threads call the method (static or not), each thread has its own copy of the parameter.

  • Help with JSP / Static methods in beans...

    Hi:
    I am creating several javabeans as part of my application. Is it ok, to make all of them static (no global variables are used) and access in JSP's and Servlets as XXBean.method(var1, var 1). Is this a problem ? (vs creating a new XXBean and using it in every page/servlet).
    I have gut feeling that static methods are better and give better memory usage and performance - as oppose in other scenario I am creating a new Bean for every page access - could not verify. and not sure not creating (new Bean) would give any problems.
    Thanks for sharing.

    No, static methods are not what you want. Just set the "scope" on your use-bean tag to "application".
    <jsp:useBean id="xbean" class="xpackage.XXBean" scope="application" />Alternatively, if what you are trying to do is a pure "function library", then create a tag lib, and add the function definitions like this:
    <function>
         <name>someMethod</name>
         <function-class>xpackage.XXBean</function-class>
         <function-signature>
         java.lang.String someMethod( java.lang.String )
         </function-signature>
    </function>There is a fairly concise description of how to do this at
    http://java.boot.by/wcd-guide/ch07s04.html

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

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

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

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

Maybe you are looking for

  • Read Only Access to Storage Container

    Is it possible to give Read Only access to a particular storage container without adding someone to Subscription and providing them the access key without anonymous request without going through SAS route

  • Computer crashed while Firefox was updating and corrupted the program so it won't open at all and I can't get my many bookmarks

    I have had recurrent problems with my computer crashing for the past several months that I was not able to fix. I was downloading and installing updates for Firefox when the computer suddenly and completely crashed - just an immediate shutdown. When

  • Capture of excise invocie for dealer

    Hi,   As per our requirement, we want to capture excise invocie for delaer, and we dont want to take benefit of aed,  WE ADDED BASE PRICE + Excise amount in base price  then in MIGO capture excise invocie we split the amount in asseceble value and BE

  • Libojc missing after split of gcc [SOLVED]

    All libojc*  files in /usr/lib that were in gcc 4.2.1-3.1 are missing from the new gcc package. They are also not present in the gcc-base package. Subbitted to flyspray : FS#8032 Last edited by Lone_Wolf (2007-09-18 12:56:32)

  • Help with- Flash Unsatisfied Link Error

    Any suggestions would be well received. Thanks. I've been trying to play a flash video using the sample player by changing the mediaURL. When I complile in Netbeans I get this message: keytool error: java.lang.Exception: Key pair not generated, alias