Calling a method within a class form another class(ViewController)

I am creating an SQL project in XCODE. I have one view. My main view controller is loading the database to a table/array. I want to add another class (with no NIB) just to handle the display of the table in a UITableView. So, I added a skeleton cocoa touch class file to my classes folder to handle this function when parameters change.
So, in my app delegate, the "applicationdidFinishLaunchingWithOptions" method loads my mainViewController and NIB.  On the "viewDidLoad" method in my mainViewController, I read a URL into an SQLite database and close the database.  Herein lies the problem: I want to call my new class (TableViewHandler) and pass it the array created in the mainViewController and use the array to populate the UITable.
How do I call a class from within another class (which has no NIB) to populate the table?  Especially if my TableViewHandler has no "viewDidLoad", "viewDidAppear", etc.
Regads,
-Kevin

This is what my exact problem.
i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
both ShopBook.java and DataBean.java lies in the package shoppack.
in ShopBook i tried to instantiate the object to DataBean as
DataBean db = new DataBean();
it shows the compiler error, unable to resolve symbol DataBean.
note:
first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
when i'm trying to compile the ShopBook its telling this error.
hope i'm clear in explaining my problem. can u please help me?
thank u in advance.
regards,
Fazli

Similar Messages

  • Calling a method of one class from another withing the same package

    hi,
    i've some problem in calling a method of one class from another class within the same package.
    for eg. if in Package mypack. i'm having 2 files, f1 and f2. i would like to call a method of f2 from f1(f1 is a servlet) . i donno exactly how to instantiate the object for f2. can anybody please help me in this regard.
    Thank u in advance.
    Regards,
    Fazli

    This is what my exact problem.
    i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
    both ShopBook.java and DataBean.java lies in the package shoppack.
    in ShopBook i tried to instantiate the object to DataBean as
    DataBean db = new DataBean();
    it shows the compiler error, unable to resolve symbol DataBean.
    note:
    first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
    when i'm trying to compile the ShopBook its telling this error.
    hope i'm clear in explaining my problem. can u please help me?
    thank u in advance.
    regards,
    Fazli

  • Trying to understand methods - calling methods within own class - help

    I'm trying to write a simple program to search for letters in a string. I'm having a ton op problems; java seems so complicated with a lot of rules.
    The main problem I'm having (for now) is calling a method within the same class as main.
    import java.io.*;
    class LookForLetters{
        public static void main(String[] args)
         int i = 0;     
         int j = 0;
         int l = 0;
         int m = 0;
         String question1 = "Enter the line to be searched"; 
         String question2 = "Enter the line to be searched";       
         returnResponse stringtosearch = new returnResponse(question1); // here's where my problem is
            char[] chartosearch = stringtosearch.toCharArray();
         returnResponse letterstofind = new returnResponse(question2);
            char[] chartofind = letterstofind.toCharArray();     
         int findlength = chartosearch.length();
         int searchlength = chartofind.length();
         int[] k = new int[searchlength];
         for(i = 0; i < findlength; i++)
             for(j = 0; j < searchlength; j++)   
              if(chartosearch[i] == chartofind[j])
                  k[l] = i;
                  l++;
                  System.out.print("T");
             System.out.print(i + " " + l);
                if(l == 0)
                    System.out.print(chartofind[i] + " is the not in the sentence.");
                    System.out.println();       
                else
                    System.out.print(chartofind[i] + " is the ");
                 for(m = 0; m < l; m++)
                     System.out.print(k[l] + " ");
                    System.out.print("letter of your sentence");
                    System.out.println();
                    l = 0;
        public String returnResponse(String question){
         String response = " ";
         System.out.print(question);
         try
             InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReaderbr = new BufferedReader(isr);
             response = br.readLine();            
         catch(IOException e)
             System.out.print("error");
         return response;
    }The compiler says that it can't find the returnResponse method. when I try to instantiate the whole class, it says the package is not included. Please help.

    JoachimSauer wrote:
    DaneWKim wrote:
    thank you very much for your response. I'm sure it's obvious that I'm really confused. I'm used to C and assembly programming, so the OO concepts are really foggy.That particular line doesn't even deal with any OO concept. But the fact that you already know C helps me give a (hopefully) more useful answer:
    What is the return type of the method you're trying to call?
    What is the type of the variable you want to assign the return value to?
    Are those compatible? Or even more general: do they both exist?I changed it to:
            String stringtosearch = returnResponse(question1);
            char[] chartosearch = stringtosearch.toCharArray();
         String letterstofind = returnResponse(question2);
            char[] chartofind = letterstofind.toCharArray();I guess I'm getting confused with medthods, class and types. There's a whole host of new vocabulary and rules with OO and java that have me a bit confused. I appreciate your help.

  • Calling a method in Runnable Class

    Hello I am trying to water this down but how can I call a method in my class
    If I am passed only thread t.
    MyClass mc = new MyClass();
    Thread t = new Thread(mc);
    t.start(); //works because it is a method of Thread
    t.myMethodInMyClass (); // wont work because it cant find it
    I have attempted casting to MyClass but I get CCException.
    Any help would be wonderful..
    cheers and thanks in advance.
    Scott

    Well, you could potentially have too many things in one class. You may want to try and modularize your classes more. But 'if in several situations [you] need different things to run'... well, the logic is just going to have to be there for that in some form.
    Now, if you've already performed the logic to determine what to run and you are going to have to perform the logic again (in your run() method), then there is a flaw in your design.

  • Call a method of a class in a constructor of another class?

    Is this good programming or should i do it in another way?
    Consider an ordering system, where I have three classes, "Booking", "Table" and "Customer.
    My idea is to create a booking assigned to a table and a customer, the fields in the booking class is a Customer and a Table and the constructor assigns values to these field.
    In my Table class i have a method that books the table "bookTable(Customer customer)" and sets the availablility to 'false'.
    So my question is, is it good programming to call the method 'bookTable()' in the table class from the constructor of the Booking class? Or should i do it in another way?
    Edited by: DJHingapus on Jul 6, 2009 5:12 AM

    This sounds the wrong way around. What is the return value of bookTable(Customer)?
    I'd expect it to return a Booking object that it creates.
    Generally, you want the constructor to do as little as possible (while still only ever returning in a valid state, of course!).
    The problem you can get when you call other methods is that you introduce the possibility of other objects getting access to your object before the constructor has finished running (i.e. before the object is completely initialized). This can lead to nasty problems that are hard to find and debug.

  • How to call main method in one class from another class

    Suppose i have a code like this
    class Demo
    public static void main(String args[])
    System.out.println("We are in First class");
    class Demo1
    public static void main(String args[])
    System.out.println("We are in second class");
    In the above program how to call main method in demo calss from Demo1 class......???????

    No, i dont know how to call other than main methods from other classes
    And one more doubt i have i.e. Like in C can we see the execution of the program like how the code is being compiled step by step and how the value of the variable changes from step to step like(Add Watch).........

  • Help with creating a method within a class

    I need help creating another method within the same class.
    Here is part of my progam, and could anyone help me convert the switch statement into a seperate
    method within the same class?
    import javax.swing.JOptionPane;
    public class Yahtzee
         public static void main (String[] args)
              String numStr, playerStr, str, tobenamed;
              int num, times = 13, roll, x, y, maxRoll = 3, z = 0, t;
              int firstDie, secondDie, thirdDie, fourthDie, fifthDie, maxDie = 5, reroll;
              int rerolling = 0, categoryChoice, score, nextDie1, nextDie2, nextDie3, nextDie4;
              Die die1, die2, die3, die4, die5;
              do
              numStr = JOptionPane.showInputDialog ("Enter the number of player: ");
              num = Integer.parseInt(numStr);
              while (num < 1 || num > 6); //end of do loop
              String [] player = new String[num];
              // boolean //finsih later to make category choice only once.
              for (x = 0; x < num; x++)
                   playerStr = JOptionPane.showInputDialog ("Name of Player" + (x + 1) + " :");
                   player[x] = playerStr;  
              } //end of for loop
              die1 = new Die();
               die2 = new Die();
               die3 = new Die();
               die4 = new Die();
               die5 = new Die();
              int scoring [][] = new int [num][13];//scoring aray
              int[] numDie = new int[maxDie];
              String[][] usedCategory = new String [num][times];
              for (x=0; x < 13; x++)
                   for (y = 0; y < num; y++)
                      usedCategory[y][x] = " ";
              for (int choices = 0; choices < times; choices++)
                   //player turns for loop.
                   for (x = 0; x < num; x++)
                        //rolls the die;
                          for (y = 0; y < maxDie; y++)
                               numDie[y] =  die1.roll();
                     numStr = JOptionPane.showInputDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
                                                                            + "\nDie1: " + numDie[0]
                                                                                + "\nDie2: " + numDie[1]
                                                                                + "\nDie3: " + numDie[2]
                                                                                + "\nDie4: " + numDie[3]
                                                                                + "\nDie5: " + numDie[4]
                                                                                + "\nWhich dice do you want to reroll");
                    reroll = numStr.length();
                    if (reroll == 0)
                        t = maxRoll;
                   else{                                                      
                    //reroll
                         for(t = 0; t < maxRoll; t++ )
                             for (y = 0; y < reroll; y++)
                                    rerolling = numStr.charAt(y);
                                 //create another mwthod later.
                                    switch (rerolling)
                                         case '1':
                                              numDie[0] =  die1.roll();
                                              break;
                                         case '2':
                                              numDie[1] =  die1.roll();
                                              break;
                                         case '3':
                                              numDie[2] =  die1.roll();
                                              break;
                                         case '4':
                                              numDie[3] =  die1.roll();
                                              break;
                                         case '5':
                                              numDie[4] =  die1.roll();
                                              break;
                                         default:
                                         t = maxRoll;//to be changed
                                    } //end of switch class
                              }//end of reroll for loop
                                   JOptionPane.showMessegeDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
                                                                                      + "\nDie1: " + numDie[0]
                                                                                          + "\nDie2: " + numDie[1]
                                                                                          + "\nDie3: " + numDie[2]
                                                                                          + "\nDie4: " + numDie[3]
                                                                                          + "\nDie5: " + numDie[4]
                                                                                          + "\nWhich dice do you want to reroll"
                                               switch (rerolling)
                                         case '1':
                                              numDie[0] =  die1.roll();
                                              break;
                                         case '2':
                                              numDie[1] =  die1.roll();
                                              break;
                                         case '3':
                                              numDie[2] =  die1.roll();
                                              break;
                                         case '4':
                                              numDie[3] =  die1.roll();
                                              break;
                                         case '5':
                                              numDie[4] =  die1.roll();
                                              break;
                                         default:
                                         t = maxRoll; //not really anything yet, or is it?
                                    } //end of rerolling switch class
                                       //categorychoice = Integer.parseInt(category);
                              }//end of t for loop            
                   }//end of player for loop.

    samuraiexe wrote:
    well, i should have said it is a yahtzee program, and i ask the user what they want to reroll and whatever number they press, the switch will activate the case and the array that it will reroll.
    HOw would i pass it as an argument?You put it in the argument list. Modifying your original code a bit:
    public static void switchReroll (int[] dice, int position) {
         switch (position) {
         case '1':
                 dice[0] =  die1.roll()
                 break;
         case '2':
                 dice[1] =  die1.roll();
                 break;
         case '3':
                 dice[2] =  die1.roll();
                     break;
         case '4':
                 dice[3] =  die1.roll();
                 break;
         case '5':
                  dice[4] =  die1.roll();
                 break;
         default:
                 t = maxRoll;//to be changed
        } //end of switch
    }which you could then call as this:
    switchReroll(numDie, reroll);Note that your code still isn't done; the above won't compile. This is just an example of how you could pass the stuff as an argument (and note how the values have different names in the main method than in the switchReroll method -- this works, but also note that it's the same array of ints in both).
    By the way -- you really don't need a switch statement for this. You can do the same thing with a couple lines of code, which would lessen the advantage for a separate method. But I'd suggest continuing down this path, and then you could change the implementation of the method later.

  • Calling main method of a class

    Hi
    I have to call the Main method of a class in some other class becuass that class is accepting command line aurguments.
    I test it and everything is working fine.
               String[] strings = new String[3];
               strings[0] = "E:/practice.cap";
               strings[1] = "-o";
               strings[2] = "E:/practice.txt";
               Main.main(strings);I now want to know is there any drawback of doing this ?
    BR
    regards

    Muhammad Umer wrote:
    Good Explanation. But my question is not to explain the importance of main method in classes :)As far as the Java language and APIs go, there's nothing wrong with calling main just like any other method, because it is just another method. It's only special to the JVM, and to programmers who assume that it's the entry point to the program.
    As far as Java is concerned, you can call as many mains as you want. The only potential problem arises if some particular main is written in a way that relies on it being the entry point to the whole program. That is, if the author wrote it with the assumption that it would only be called by the JVM at startup time, and would not be called arbitrarily from within your code (EDIT: and if proper behavior relies on that assumption being upheld). However, this is just a particular case of a general issue that we always have to be aware of, namely, make sure you understand how a method is intended to be used, and use it in that fashion, or accept the consequences.
    EDIT: However, having said that, it's unusual to call main explicitly, so if you can, I would suggest pulling the functionality that you want out of that main into a different method, and then both your code and the main can call that method. If you cannot do that, then at the point where you call main, clearly document why you're doing it. Otherwise, whoever reads the code a few months or years from now--maybe somebody else, maybe you--will be wondering if the programmer really knew what he was doing, or if that is a mistake. That kind of second-guessing is the source of a lot of maintenance nightmares.
    Edited by: jverd on Nov 3, 2011 8:43 AM

  • Calling a method within an application?

    Hi I'm a student taking an intro Java class and right now I have to develop and application that prompts for someone to input a character of the alphabet and it will display the corresponding number on a telephone that it is listed under. The main method gets the input from the user and we are required to retrieve the corresponding digit to the character from a separate method using either a switch statement or a nested if-then-else statement to determine what the digit is. I'm having trouble calling that method in the main class which is another requirement. any suggestions?
    public class Hmwk08
         * Main driver begins program execution.
         * @param args program arguments
        public static void main(String[] args) throws Exception
            char letter;
            char ch;
            int relatesTo;
            PrintStream win = new PrintStream(System.out);
            Scanner in = new Scanner(System.in);
            String newLine = System.getProperty("line.separator");
            win.println("Given a letter of the alphabet, this program" + newLine
                        + "will tell you the corresponding digit on a" + newLine
                        + "telephone keypad.");
            win.println();
            win.print("Enter a letter: ");
            letter = in.nextLine().charAt(0);
            letter = Character.toUpperCase(letter);
         * Get the digit on a telephone keypad that corresponds
         * to the specified character. If the character is neither
         * a letter nor a digit, this method will retun the
         * asterisk character: '*'
         * @param letter the specified character
         * @return the corresponding digit
        private static char getPhoneDigit(char letter)
            char digit;
            digit = '*';
            if(letter == 'A' || letter == 'B' || letter == 'C')
                digit = '1';
            return digit;
    }

    Your method is static so you can call your method without creating a Hmwk08 object.
    char result = getPhoneDigit(letter);Would suffice in your main method
    Mel

  • Calling a Method in other Class

    I want to call a method in another class when an action is preformed can anyone suggest how I might do this??
         addSquare.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
         

    I want to call a method in another class when an
    action is preformed can anyone suggest how I might do
    this??
            addSquare.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent e)
                 {               OtherClass oc = //getrefererncetootherclass
                   oc.methodtocall(params, to, pass);

  • How to call a method of a class where the name of method is string

    i have a method of a class in the form of a string and i have the object of the class to which it belongs .what i want to do is call this method.
    for ex:
    S1 s=new S1();
    // this is the object of my class. this class has one method called executeMe()
    String methodname="executeMe";
    //i have the name of the method with me in the form of string.
    so how can i call the class's method in this scenario from the string like what should i write in sucha way that i get s.executeMe(); it is not presumed that this will only be the method that will be called. there maybe some other method too and it has also to be called this way. so please guide.

    S1 s = new S1();
    String name = "executeMe";
    Method m = s.getClass().getDeclaredMethod(name,null); // no parameters
    m.invoke(s,null);Built from memory, maycontain flaws.

  • How to call a method in one JSP from another JSP?

    say that I have 2 JSPs.
    JSP one has a button.
    JSP two has some method that, say, find the square root of the number passed from JPS one.
    How to - when click - the button on page one call the method on page two?
    Please note that I can not use object binding, but I want passing the actual parameter and call the method on page two.
    Please note that this is an update of a previous post on the same topic called "Object scope".
    Thank you all very much.

    No, i dont know how to call other than main methods from other classes
    And one more doubt i have i.e. Like in C can we see the execution of the program like how the code is being compiled step by step and how the value of the variable changes from step to step like(Add Watch).........

  • How do i call the method in a class using servlet

    i am doing a project which need to use servlet to call a few methods in a class and display those method on the broswer. i tried to write the servlet myself but there are still some errors .. can anyone help:
    The servlet i wrote :
    package qm.minipas;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class test extends HttpServlet {
    Database database;
    /** Initializes the servlet.
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    database = FlatfileDatabase.getInstance();
    /** Destroys the servlet.
    public void destroy() {
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("this is my class wossname"+FlatfileDatabase.getInstance()); // this is calling the toString() method in the instance of myJavaClass
    out.println("this is my method"+FlatfileDatabase.getAll());
    out.println("</body>");
    out.println("</html>");
    out.close();
    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    my methods which i need to call are shown below:
    public Collection getAll() {
    return Collections.unmodifiableCollection(patientRecords);
    public Collection getInpatients() {
    Collection selection=new ArrayList();
    synchronized(patientRecords) {
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(next.isInpatient())
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByAdmissionDate(Date dateOfAdmission) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(dateOfAdmission.equals(next.getDateOfAdmission()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByAdmissionDates(Date from,Date to)
    throws IllegalArgumentException {
    if(to.before(from))
    throw new IllegalArgumentException("End date must not be before start date");
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    Date nextAD=next.getDateOfAdmission();
    if((nextAD.after(from)||nextAD.equals(from))
    &&(nextAD.before(to)||nextAD.equals(to)))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByDischargeDates(Date from,Date to)
    throws IllegalArgumentException {
    if(to.before(from))
    throw new IllegalArgumentException("End date must not be before start date");
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    Date nextAD=next.getDateOfDischarge();
    if(nextAD==null)
    continue;
    if((nextAD.after(from)||nextAD.equals(from))
    &&(nextAD.before(to)||nextAD.equals(to)))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByConsultant(String consultant) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(consultant.equalsIgnoreCase(next.getConsultant()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByDischargeDate(Date dateOfDischarge) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(dateOfDischarge.equals(next.getDateOfDischarge()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getBySurname(String surname) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(surname.equalsIgnoreCase(next.getSurname()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByWard(String ward) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(ward.equalsIgnoreCase(next.getWard()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);

    please provide a detail description of your errors.

  • Calling a method from abstarct class

    Hi Experts,
    Am working on ABAP Objects.
    I have created an Abstract class - with method m1.
    I have implemented m1.
    As we can not instantiate an abstract class, i tried to call the method m1 directly with class name.
    But it it giving error.
    Please find the code below.
    CLASS c1 DEFINITION ABSTRACT.
      PUBLIC SECTION.
        DATA: v1 TYPE i.
        METHODS: m1.
    ENDCLASS.                    "c1 DEFINITION
    CLASS c1 IMPLEMENTATION.
      METHOD m1.
        WRITE: 'You called method m1 in class c1'.
      ENDMETHOD. "m1
    ENDCLASS.                    "c1 IMPLEMENTATION
    CALL METHOD c1=>m1.
    Please tell me what is wrong and how to solve this problem.
    Thanks in Advance.

    Micky is right, abstract means not to be instantiated. It is just a "template" which you can use for all subsequent classes. I.e you have general abstract class vehicle . For all vehicles you will have the same attributes like speed , engine type ,  strearing , gears etc and methods like start , move etc.
    In all subsequent classes (which inherit from vehicle) you will have more specific attributes for each. But all of these classes have some common things (like the ones mentioned above), so they use abstract class to define these things for all of them.
    Moreover there is no sense in creating instance (real object) of class vehicle . What kind of physical object would vehicle be? there is no such object in real world, right? For this we need to be more precise, so we create classes which use this "plan" for real vehicles. So the abstract class here is only to have this common properties and behaviour defined in one place for all objects which will have these. Abstract object however cannot be created per se. You can only create objects which are lower in hierarchy (which are specific like car , ship, bike etc).
    Hope this claryfies what we need abstract classes for.
    Regards
    Marcin

  • Calling a method in a class extended from thread

    I'm trying to use two threads of type ThreadTest to call the addNum method in the class below. I found that i couldnt call the addnum method with the instances I created but had to make the addnum method static and then call it with the class name ThreadTest.Is there anyway to get round this? i'm doing this exercise to try and understand synchronisation. Thanks
    import java.lang.Thread;
    import java.util.*;
    class ThreadTest extends Thread implements Runnable{
         private int x;
         private static ArrayList intnumbers = new ArrayList();
         public ThreadTest(int no)
              x=no;
         public void run()
              for (int i=0; i<x; i++)
                   try
                   System.out.println(i);
                   Thread.currentThread().sleep((long)(Math.random() * 1000));
              }catch(InterruptedException e ){e.getMessage();}
         public static void addNum(int n)
              synchronized(intnumbers){
                        intnumbers.add(new Integer(n));
    public static void main(String[] args)
         Thread  testThread = new Thread(new ThreadTest(50));
         Thread  testThreadb = new Thread(new ThreadTest(50));
         testThread.start();
         testThreadb.start();
              ThreadTest.addNum(10);
        //*** this gives an error
        //testThread.addNumber(10);
        //testThreadb.addNumber(10);
    }

    ok here goes again. ;).
    import java.lang.Thread;
    import java.util.*;
    class ThreadTest extends Thread implements Runnable{
         private int x;
         private static ArrayList intnumbers = new ArrayList();
         public ThreadTest(int no)
              x=no;
         public void run()
              for (int i=0; i<x; i++)
                   try
                   System.out.println(i);
                   Thread.currentThread().sleep((long)(Math.random() * 1000));
              }catch(InterruptedException e ){e.getMessage();}
         public static void addNum(int n)
              synchronized(intnumbers){
                        intnumbers.add(new Integer(n));
    public static void main(String[] args)
         Thread  testThread = new ThreadTest(50);
         testThread.start();
         //gives error so how can i create 2 instances of testThread and call addNum with them?
         //testThread.addNum(10);
    //works ok but I want to call addNum with 2 different threads
         ThreadTest.addNum(10);
    }

Maybe you are looking for