Packages and Main method.

What is the reason for the following. When you explicitly specify a package name for a class that contains the main method, why do you have to specify the fully qualified class name when you invoke the JVM?
For example:
package Exercises.Chp8.ExerciseTwo;
import Exercises.Chp8.Interfaces.*;
class Exercise2 implements myInterface {
     public void method1() {
          System.out.println("method 1 implemenmted");
     public void method2() {
               System.out.println("method 2 implemenmted");
     public void method3() {
               System.out.println("method 3 implemenmted");
public class testExercise2 {
     public static void main(String[] args) {
          Exercise2 ex = new Exercise2();
          ex.method1();
          ex.method2();
          ex.method3();
I would have to issue the following command:
java Exercises.Chp8.ExerciseTwo.testExercise2
for the java to run. If I specify java testExercise2, it displays a stack trace of the classLoader and an error messages reads regarding "wrong name". Can someone explain why this is?

Hi,
Please refer the following URL.
It is very well documented in the java site.
Please refer these URL's
http://java.sun.com/docs/books/tutorial/java/interpack/packages.html
http://java.sun.com/docs/books/tutorial/java/interpack/createpkgs.html
http://java.sun.com/docs/books/tutorial/java/interpack/usepkgs.html
http://java.sun.com/docs/books/tutorial/java/interpack/managingfiles.html
Also please refer this URL, which has a discussion about packages.
http://forum.java.sun.com/thread.jsp?forum=31&thread=151016
I hope this will help you.
Thanks
Bakrudeen

Similar Messages

  • Servlet with dopost and main() methods

    I have pre-existing servlet code for maintenance purposes.
    It received a request by POST action from the client. This class also has main() method where class is instasiated and processed.
    Can anyone help me understand reason for having dopost and main() methods.
    TIA

    Before the days of JUnit developers would write a main method for a class as a way to test the class. Some older developers still do it. I know because I am dealing with the problem now.

  • Deploying an rich client (Applet and main method)in iPlanet.

    I would like to know how to deploy an applet client and a main() method client in the iPlanet Application Server. Adv. thnax for your replies.

    Dear punit,
    Thanx for ur reply.
    but then where will i mention the JNDI name which we usually supply in DD during the deployment of a WAR file.
    When i try to run the standalone appln. i get an error, because i have not supplied a jndi name in the server. where will client find out the jndi name from, because nothing is specified in the server(but in the case of servlet we spcify the JNDI name in DD XML file.)
    R u working currently on iAS6.0.
    Thanx and see if u can reply me ASAP.

  • How To Pass A Value Read By A Loop To Main Method

    Hey everybody,
    I'm at this with my code.I'm reading the values of a text file in a loop.I want to pass these values to main method.The importhant point is I want to do this without using a field. The code is below. Thanks.
    //Main
    public static void main(String[] args)throws FileNotFoundException
              DoubleClass AvgScore=new DoubleClass();
    IntClass Messenger=new IntClass();
              PrintWriter writer1=new PrintWriter("D:\\JavaExercises\\CH07EX14out.txt");
              Scanner scan1=new Scanner(new FileReader("D:\\JavaExercises\\CH07EX14data.txt"));
         //1 ogrencinin notlarini okut ve ortalamasını hesaplat
         while(scan1.hasNext())
              writer1.print(scan1.next()+" ");
    calcAvg(AvgScore,scan1,Messenger);
    //AvgScore formatlanarak yazdirilacak
    writer1.print(""+AvgScore+" ");
    writer1.print(""+calcGrade(AvgScore)+"\n");
    writer1.close();
    //calcAvg
    public static void calcAvg(DoubleClass x,Scanner y,IntClass z)
         int counter=0;
         double TotalScore=0;
    int NumTests=1;
    int Score=0;
    //Bir ogrenci icin toplam notu ve test sayisini bul.
         while(counter<=4)
              Score=y.nextInt();
    TotalScore+=Score;
    counter++;
    NumTests++;
    //Bir ogrenci icin not ortalamsi bul.
    x.setNum(TotalScore/NumTests);
              }

    Malkavian187 wrote:
    Guys please pay attention,
    I already said I can't use a field(class scoped variable)and can't use a return type method.
    I ve heard that it can be done by passing a reference or primitive variable to my calcAvg method.And than assignin the read values back to this variable.
    But I can't figure out how to make it. I need a complete solution.Including modifications to calcAvg and main method.
    Take care,Malkavian187,
    Maybe you haven't seen other posters asking homework to be done for them, so here is basically what we tell them: DO IT YOURSELF.
    And we realize that very possibly you could fail your class from that and have to drop out. This may be a good thing because it will help keep the demand for technical workers up, and thus, keep the pay high.
    On the other hand, if you choose to actually do the assignment then we will be happy to give comments on your code. Please post it when you have some and until then, best wishes with what ever you choose to do.
    BTW: the solution you allude to requires a field also... and in reality, you already gave the answer--just implement it. If you do not know how: well, maybe you should do one of the following:
    1-read and study the Java Tutorial
    2-pay more attention to class
    3-read your textbook for your class
    4-go to class
    5-stay awake in class
    6-pay attention in class
    7-talk to your teacher
    8-withdraw from the class
    9-change your major

  • Init and main

    can anybody help me understand the difference between init and main methods.
    I am a beginner,so please take it easy if thequestion seems stupid.
    thank you
    saumya

    init() comes into picture only in servlets !??That isn't what he said, that was just an example. The init() method is used by a lot of APIs, but all for the same basic principal:
    The class will be instantiated (the constructor will be called), but the process the class represents may run right away. There may be more initialisation needed. The init() method is called after all initialisation is done, and before the process begins to run. Thus, if you want to prepare your class you use the init() method (so you know it will always occur after full initialisation and before execution).
    but you mean,if i am developing an applet then no
    need to right main() ?That is correct. You do not need a main() unless your app is a stand-alone application.
    and if i am developing a stanalone application
    suppose in swing i need not right init() ?That depends. Generally no. But some classes/APIs may require you to.

  • Static main methods and run()

    I am having trouble with main methods, and how to structure code, im not 100% sure on what static methods are, and im not sure how to use it when calling other methods etc cos its static and stuff - i read that i should put stuff in the constructor - but im not sure how this will work with a run()
    I have written a program to draw some objects (just an oval at a certain position)
    anyway here is the main method:
    public static void main(String[] args) {
            // TODO code application logic here
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Main game = new Main();
                    game.createAndShowGUI();
                    //Create some graphics objects at the desired position!
                    GOA[0] = new GraphicsObject(300,200);         *
                    GOA[1] = new GraphicsObject(350,200);         *
                    game.frame.updateGraphics(GOA);            *
        }I am getting "non-static variable GOA cannot be referenced from a static context" at * i cant just make everything static, how should this be structured? where should the run() be?
    Thanks for any help

    Ok, i might as well include the whole thing - its not too big , and i would like to see if any of it is right really.
    ackage joefootball2;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferStrategy;
    public class Main {
        GameWindow frame;
        //Create the graphics object array to pass to the painting stuff
        GraphicsObject[] GOA;
        private void createAndShowGUI() {
            //Create and set up the window.
            frame = new GameWindow();
            frame.DrawWindow();
        public static void main(String[] args) {
            // TODO code application logic here
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Main game = new Main();
                    game.createAndShowGUI();
                    //Create some graphics objects!
                    GOA[0] = new GraphicsObject(300,200);
                    GOA[1] = new GraphicsObject(350,200);
                    game.frame.updateGraphics(GOA);
    class GameWindow extends JFrame
        DrawPanel canvas;
        public void updateGraphics(GraphicsObject[] GOA)
            canvas.updateObjects(GOA);
        public void DrawWindow()
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            canvas = new DrawPanel();
            canvas.setDoubleBuffered(true);
            this.getContentPane().add(canvas);
            this.setVisible(true);
            this.setSize(800, 600);
            this.setResizable(false);
    class DrawPanel extends JPanel
        //Create the graphics object array to draw
        GraphicsObject[] GOA;
        public void updateObjects(GraphicsObject[] givenGOA)
            GOA=givenGOA;
        public void paint(Graphics g)
            for (int i=0 ; i<GOA.length ; i++)
                g.drawOval(GOA.x-5, GOA[i].x-5, 10, 10);
    class GraphicsObject
    //for now, just make the graphics object a point to draw a circle
    int x; int y;
    }thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • Synchronizing methods and a static main method

    I have a class with a static main method, calling 3 different jdbc updates.
    I want to make sure this is thread safe when called for various clients.
    It's goes:
    args[0] = clientI
    update 1:update field1 where clientid = client1
    update 2:update field2 where clientid = client1
    update 3:update field3 where clientid = client1I assume I am in jeopardy of mixing up my data?
    I don't think I can synchronize a main method, nor would it do any good to synchronize the class?
    Should I break the updates into methods, then synchronize them, or synchronize parts of the code?
    you opinion would help greatly.

    You haven't provided enough information.
    Are those updates occurring sequentially? Then it's threadsafe.
    Are they running in different threads? Then to make them threadsafe you'll need proper synchronization, or a database transaction.
    Of course, looking at those particular updates, I don't see any reason why you'd need to worry about thread safety. They look to be independent of each other. Or perhaps you meant you need them to be atomic? That is, any query will see either the old values of all three fields, or the new values of all three fields. Nobody will be able to see the new values for fields 1 and 2, but the old value for field 3. If that's the case, then those three updates need to be in a database transaction.

  • Camera Raw will not install on my mac,os 10.7.5. When I click on the install package the main install screen opens and that is as far as I can proceed with the down load. I have to force quit the software and try again. I have deleted and downloaded the s

    Camera Raw will not install on my mac,os 10.7.5. When I click on the install package the main install screen opens and that is as far as I can proceed with the down load. I have to force quit the software and try again. I have deleted and downloaded the software several times to no avail. I need some help.

    Appreciate your help Ian and others.   I have since uninstalled FCS and reinstalled FCXP only to get the same thing. Loading FCXP stalls at "Looking for Compressor Support".  When I first downloaded FCXP from the App store I didn't notice that FCS was being placed in it's own folder.  It's not something I did manually.  Although moved into it's own folder with FCXP on the same drive.  I was not able to open FCS apps. They would load and then "quit unexpectantly".  They opened just fine before I downloaded FCXP.  Do I need to purchase Compressor so that FCXP recognizes it? It seems this is where it stalls. It doesn't explain however why my computer "FREEZES" while doing this.  I am in the process of re-installing Lion to see if this helps, otherwise I am at a complete loss. 

  • Creation of developement class,package and access key

    COULD ANYBODY EXPLAIN about
    creation of developement class,package and access key
    and who will create them?

    Working With Development Objects
    Any component of an application program that is stored as a separate unit in the R/3 Repository is called a development object or a Repository Object. In the SAP System, all development objects that logically belong together are assigned to the same development class.
    Object Lists
    In the Object Navigator, development objects are displayed in object lists, which contain all of the elements in a development class, a program, global class, or function group.
    Object lists show not only a hierarchical overview of the development objects in a category, but also tell you how the objects are related to each other. The Object Navigator displays object lists as a tree.
    The topmost node of an object list is the development class. From here, you can navigate right down to the lowest hierarchical level of objects. If you select an object from the tree structure that itself describes an object list, the system displays just the new object list.
    For example:
    Selecting an Object List in the Object Navigator
    To select development objects, you use a selection list in the Object Navigator. This contains the following categories:
    Category
    Meaning
    Application hierarchy
    A list of all of the development classes in the SAP System. This list is arranged hierarchically by application components, component codes, and the development classes belonging to them
    Development class
    A list of all of the objects in the development class
    Program
    A list of all of the components in an ABAP program
    Function group
    A list of all of the function modules and their components that are defined within a function group
    Class
    A list of all of the components of a global class. It also lists the superclasses of the class, and all of the inherited and redefined methods of the current class.
    Internet service
    A list of all of the componentse of an Internet service:
    Service description, themes, language resources, HTML templates and MIME objects.
    When you choose an Internet service from the tree display, the Web Application Builder is started.
    See also Integrating Internet Services.
    Local objects
    A list of all of the local private objects of a user.
    Objects in this list belong to development class $TMP and are not transported. You can display both your own local private objects and those of other users. Local objects are used mostly for testing. If you want to transport a local object, you must assign it to another development class. For further information, refer to Changing Development Classes
    http://help.sap.com/saphelp_46c/helpdata/en/d1/80194b454211d189710000e8322d00/content.htm
    Creating the Main Package
    Use
    The main package is primarily a container for development objects that belong together, in that they share the same system, transport layer, and customer delivery status. However, you must store development objects in sub-packages, not in the main package itself.
    Several main packages can be grouped together to form a structure package.
    Prerequisites
    You have the authorization for the activity L0 (All Functions) using the S_DEVELOP authorization object.
    Procedure
    You create each normal package in a similar procedure to the one described below. It can then be included as a sub-package in a main package.
    To create a main package:
    1.       Open the Package Builder initial screen (SE21 or SPACKAGE).
    2.       In the Package field, enter a name for the package that complies with the tool’s Naming Conventions
    Within SAP itself, the name must begin with a letter from A to S, or from U to X.
    3.       Choose Create.
    The system displays the Create Package dialog box.
    4.       Enter the following package attributes:
    Short Text
    Application Component
    From the component hierarchy of the SAP system, choose the abbreviation for the application component to which you want to assign the new package.
    Software component
    Select an entry. The software component describes a set of development objects that can only be delivered in a single unit. You should assign all the sub-packages of the main package to this software component.
    Exception: Sub-packages that will not be delivered to customers must be assigned to the HOMEsoftware component.
    Main Package
    This checkbox appears only if you have the appropriate authorization (see Prerequisites).
    To indicate that the package is a main package, check this box.
    5.       Choose  Save.
    6.       In the dialog box that appears, assign a transport request.
    Result
    The Change package screen displays the attributes of the new package. To display the object list for the package in the Object Navigator as well, choose  from the button bar.
    You have created your main package and can now define a structure within it. Generally, you will continue by adding sub-packages to the main package. They themselves will contain the package elements you have assigned.
    See also
    Adding Sub-Packages to the Main Package
    http://help.sap.com/saphelp_nw04/helpdata/en/ea/c05d8cf01011d3964000a0c94260a5/content.htm
    access key used for change standard program.
    www.sap.service.com

  • When is the inteface variable in an EJB mains method initiated?

    hI,
    the code bellow is part of a simple EE 6 example from Yuri Vasilievs book Beginning Database-Driven...
    Can somone tell me when the variable customerSession bellow will be initiated in the CustomerSessionClient class bellow.
    When I run theCustomerSessionClient (main methode) in my netbeans environment the customerSession is allways null?
    Bellow first the inteface class and then the CustomerSessionClient class
    package ejbjpa.client;
    import javax.ejb.Remote;
    * @author xxx
    @Remote
    public interface CustomerSession {
    public String getCustomerAddress(Integer customer_no);
    import ejbjpa.ejb.CustomerSession;
    import javax.ejb.EJB;
    * @author xxx
    public class CustomerSessionClient {
    @EJB
    private static CustomerSession customerSession;
    public static void main(String[] args){
    System.out.println("Billing address of the customer whose id is: "+customerSession.getCustomerAddress(1));
    Brg
    Javanalle
    Edited by: 873848 on Jul 20, 2011 8:56 PM

    Can somone tell me when the variable customerSession below will be initiated in the CustomerSessionClient class below.It will never be initialized.
    When I run theCustomerSessionClient (main method) in my netbeans environment the customerSession is always null?I agree.
    That's just a command-line client. It doesn't execute in an EJB container, so the @EJB annotation never takes effect.

  • Package and class path

    for two yrs i am trying to get package right but no result
    i am using window 98
    i have my jdk in d:\jdk1.2\bin; and this works fine if i do not try to use package;somtimes it works well half way with package!
    suppose i want to create a package called rubberband and put classes in it
    i created a folder called rubberband in d:\ and then
    package rubberband;
    import java.awt.*;
    public class RubberbandTest extends Frame{}
    class RubberbandTestPanel {}
    class Colorchoice{}
    this is one unit
    and there are other classes
    package rubberband;
    import java.awt.*;
    abstract class Rubberband {}
    package rubberband;
    import java.awt.*;
    class RubberbandPanel extends Rubberband {}
    and so on
    i opened executive.bat and added to class path as follows:
    path:d:\rubberband\bin;before the already existing d:\jdk1.2\bin;
    then when i come to compile and run the program i have problems
    like:class so and so not found
    please help please step by step tell me what to do

    Another sample might answer your "different location" question.
    Suppose program YourProg in package yourPkg located in directory C:\javaprogs needs to access a class file ExtraClass in package extraPkg in directory C:\differentDir.
    1) Of course the source file must exist in file
    C:\javaprogs\yourPkg\YourProg.java
    and
    C:\differentDir\extraPkg\ExtraClass.class must exist.
    2) Inside the YourProg source, you must import ExtraClass:
    import extraPkg.ExtraClass;
    3) To compile YourProg, you must include location of extraPkg.ExtraClass in the classpath (or the compiler will complain about the inport line above):
    (a -- from C:\javaprogs directory): javac -classpath C:\differentDir yourPkg\YourProg.java
    (b -- from any directory): javac -classpath C:\javaprogs;C:\differentDir yourPkg\YourProg.java
    4) To run YourProg (assuming it contains a main method), you must include all locations in classpath:
    (a -- from C:\javaprogs directory): java -classpath .;C:\differentDir yourPkg.YourProg
    (b -- from any directory): java -classpath C:\javaprogs;C:\differentDir yourPkg.YourProg
    If you get a NoClassDefFoundError, that means that the java was run without the proper location included in the classpath passed to the -classpath argument. The -classpath argument should be ';'-separated and contain no spaces (so if a long directory name contains space you should enclose in double quotes, as this example:
    java -cp "C:\Program Files\somedir;C:\anotherdir" NameOfAClass

  • JAVA PACKAGES and JSP

    i Have two problems one is i am designing a website which consists of a form. I am trying to write the Connectiviy and all other insert statements in seperate java packages and include them in JSP files.
    i Have two java packages one is DBUtil(having two java files both dealing with connectovity) and another one is StudentUtIl which has java files that open the connections with database connection and insert data into DB., I am having a big Problem here. How can i call the function in the other java package in the files in this java package. i have openDB()and Close() in the other Db and i want to call these functions in JAVA classes in the other package. How to include a package. Both these packages are in the same File system mounted on a Local directory

    Thank you for the reply. I am giving the code i have given the full class name . and now it is giving the following error :
    Cannot reference a non-static method connectDB() in a static context.
    I am also giving the code. Please do help me on this. i am a beginner in java.
    import java.sql.*;
    import java.util.*;
    import DButil.*;
    public class StudentManager {
    /** Creates a new instance of StudentManager */
    public StudentManager() {
    Connection conn = null;
    Statement cs = null;
    public Vector getStudent(){
    try{
    dbutil.connectDB();
    String Query = "Select St_Record, St_L_Name, St_F_Name, St_Major, St_Email_Address, St_SSN, Date, St_Company, St_Designation";
    cs = conn.createStatement();
    java.sql.ResultSet rs = cs.executeQuery(Query);
    Vector Studentvector = new Vector();
    while(rs.next()){
    Studentinfo Student = new Studentinfo();
    Student.setSt_Record(rs.getInt("St_Record"));
    Student.setSt_L_Name(rs.getString("St_L_Name"));
    Student.setSt_F_Name(rs.getString("St_F_Name"));
    Student.setSt_Major(rs.getString("St_Major"));
    Student.setSt_Email_Address(rs.getString("St_Email_Address"));
    Student.setSt_Company(rs.getString("St_Company"));
    Student.setSt_Designation(rs.getString("St_Designation"));
    Student.setDate(rs.getInt("Date"));
    Studentvector.add(Student);
    if( cs != null)
    cs.close();
    if( conn != null && !conn.isClosed())
    conn.close();
    return Studentvector;
    }catch(Exception ignore){
    return null;
    }finally {
    dbutil.closeDB();
    import java.sql.*;
    import java.util.*;
    public class dbutil {
    /** Creates a new instance of dbutil */
    public dbutil() {
    Connection conn;
    public void connectDB(){
    conn = ConnectionManager.getConnection();
    public void closeDB(){
    try{
    if(conn != null && !conn.isClosed())
    conn.close();
    }catch(Exception excep){
    The main error is occuring at the following lines connectDB() and closeDB() in the class student manager. The class dbutil is in an another package.with an another file called connectionManager which establishes the connection with DB. The dbutil has the openconnection and close connection methods. I have not yet written the insert statements in StudentManager. PLease do Help me

  • Full screen mode, packages and the like

    I am trying to keep my code neat byt putting various related functions into clases with their associated methods. All is working sort of okay until I want to carry out a drawimage to the graphics device g . g is in one class and the drawimage method is in another. How do I pass the graphics device to the image class and assocaited method?? Help
    I am using netbeans and each class is in the same package. Any help on this is appreciated.
    * Main.java
    * Created on 10 August 2005, 09:19
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    package dna;
    import java.awt.*;
    import javax.swing.*;
    * @author damian creedon
    public class PerfectDNA extends JFrame {
    /** Creates a new instance of Main */
    public PerfectDNA() {
    * @param args the command line arguments
    public static void main(String[] args) {
    DisplayMode displayMode;
    displayMode = new DisplayMode(1024, 768, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
    PerfectDNA eden = new PerfectDNA();
    eden.run(displayMode);
    private static final long DEMO_TIME = 10000;
    public void run(DisplayMode displayMode){
    setBackground(Color.blue);
    setForeground(Color.white);
    setFont(new Font("Dialog", 0, 24));
    ScreenManager screen = new ScreenManager();
    try {
    screen.setFullScreen(displayMode, this);
    try {
    Thread.sleep(DEMO_TIME);
    catch (InterruptedException ex) { }
    finally {
    screen.restoreScreen();
    ImageManager images = new ImageManager();
    images.loadImages();
    images.drawImages();
    public void init(){
    public void paint(Graphics g) {
    public void repaint(Graphics g){
    * ScreenManager.java
    * Created on 10 August 2005, 10:52
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    package dna;
    import java.awt.*;
    import javax.swing.*;
    * @author damian creedon
    public class ScreenManager {
    public GraphicsDevice device;
    /** Creates a new instance of ScreenManager */
    public ScreenManager() {
    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    device = environment.getDefaultScreenDevice();
    public void setFullScreen(DisplayMode displayMode,JFrame window){
    window.setUndecorated(true);
    window.setResizable(false);
    device.setFullScreenWindow(window);
    if (displayMode != null &&
    device.isDisplayChangeSupported())
    try {
    device.setDisplayMode(displayMode);
    catch (IllegalArgumentException ex) {
    // ignore - illegal mode for this device
    public Window getFullScreenWindow() {
    return device.getFullScreenWindow();
    public void restoreScreen() {
    Window window = device.getFullScreenWindow();
    if (window != null) {
    window.dispose();
    device.setFullScreenWindow(null);
    * ImageManager.java
    * Created on 10 August 2005, 13:49
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    package dna;
    import java.awt.*;
    import javax.swing.*;
    * @author damian creedon
    public class ImageManager {
    private Image bgImage;
    private Image opaqueImage;
    private boolean imagesLoaded;
    /** Creates a new instance of ImageManager */
    public ImageManager() {
    public void loadImages() {
    bgImage = loadImage("images/background.jpg");
    opaqueImage = loadImage("images/opaque.png");
    imagesLoaded = true;
    private Image loadImage(String fileName) {
    return new ImageIcon(fileName).getImage();
    public void drawImages() {
    g.drawImage(bgImage, 0, 0);
    }

    Hiya,
    I tried this
    public void paint(Graphics g) {
    drawImages(g);
    and get this error
    Compiling 2 source files to C:\My Projects\java\My Projects\dna\build\classes
    C:\My Projects\java\My Projects\dna\src\dna\PerfectDNA.java:66: drawImages(java.awt.Graphics) in dna.ImageManager cannot be applied to ()
    images.drawImages();
    C:\My Projects\java\My Projects\dna\src\dna\PerfectDNA.java:77: cannot find symbol
    symbol : method drawImages(java.awt.Graphics)
    location: class dna.PerfectDNA
    drawImages(g);
    2 errors
    BUILD FAILED (total time: 2 seconds)
    The method called is
    public void drawImages(Graphics g) {
    g.drawImage(bgImage, 0, 0,null);
    Further help would be appreciated.

  • How to set packages and classpath

    Hi,
    I want to know about packages and classpath. I have these questions
    1, If I put a class in a package(work.util) is it necessary to put the java file in the same directory/directory hierarchy as mentioned in the package declaration. I have to compile this class, run it from main method and must be able for other classes to import.
    2. If a package have subpackages(work.util.db) do I have to set the classpath to subdirectory also to run that class.
    3. If a class is in package is it possible to run the class without prefixing the package name. I need to do this in the text editor so that I can run any program by pressing a hot key.
    rgds
    Antony Paul

    1, If I put a class in a package(work.util) is it
    necessary to put the java file in the same
    directory/directory hierarchy as mentioned in the
    package declaration.Strictly speaking, this isn't covered by the spec - it depends on what compiler and ClassLoader you are using. If you're using Sun's JDK, then yes.
    2. If a package have subpackages(work.util.db) do I
    have to set the classpath to subdirectory also to run
    that class. No. You should add the directory above work/util/db to your classpath. You should not add work, or work/util or work/util/db.
    E.g., if your Java files are in C:/MyProject/JavaSrc/work/util/db, and the package name is work.util.db, then you should have C:/MyProject/JavaSrc on your classpath (or have "." (dot) on your classpath, and compile and run from that same directory).
    3. If a class is in package is it possible to run the
    class without prefixing the package name. I need to do
    this in the text editor so that I can run any program
    by pressing a hot key.If you mean "in order to run work.util.db.Main do I need to type java work.util.db.Main, or just java Main", then you do indeed need the fully qualified class name (otherwise, how would the runtime environment know which class you mean? - there could be any number of classes called Main in any class, and it would have to search every directory and subdirectory on your classpath to find them.

Maybe you are looking for

  • Safari won't open a window, then it crashes

    After my latest update on my macbook I can't open safari. The program is "running" but then crashes without ever opening a window. So far I have deleted and reinstalled safari 3 times and still get the same message.

  • Mail Receiver adapter - dynamic file name without mail package

    I know that we can get the dynamic attachment name using mail package... As per the FAQ Mail adapter, the Mail package use is deprecated and hence we do not want to go that route. I have seen the following wiki entry for setting the file attachment n

  • LCD Monitor Resolutions

    Having a slight problem with a Viewsonic VX2235wm LCD Monitor installed approx 3 weeks ago. Installed on a Windows XP Home OEM computer with a MSI NVIDIA GEFORCE NX6600-TD 256MB PCIE TVO DVI   card installed I have been using same setup only as Digit

  • Fan started making a loud noise

    Help just switched on my computer and the fan is so loud .......any answerrs

  • Firefox 29 Does not Appear to Support Java 8 Plugin

    Why won't firefox recognize the Java 8 plugin after a fresh install. I have FF 29. I had to install Java 7u55 instead. I even uninstalled Java 7u51 prior to the attempt.