Class scope

which class method defined for every operation

If I understand your 'question' correctly (and please don't assume that I do), I think you mean to ask which method is called when you run a Java program.
If this is what you want to know, then the answer is:
public static void main(String[] args){
}or, as an alternative (after Java 5.0), which I have yet to see used anywhere:
public static void main(String... args){
}Is this what you need?

Similar Messages

  • Local inner class scope

    Hello all,
    I am working out of "Thinking in Java" and ran across something I simply don't get. A method is called and passed an argument. This method defines an inner class and returns reference to it. Later a method in the inner class is invoked, but it still has access to the argument passed to the method that created the inner class and completed.
    Here is the code (shortened from the book):
    interface Counter {
         int next();
    } // close interface Counter
    public class LocalInnerClass {
         private int count = 0;
         Counter getCounter( final String name ) {
              class LocalCounter implements Counter {
                   public int next() {
                        System.out.print( name );
                        return count++;
                   } // close next()
              } // close inner class
              return new LocalCounter();
         } // close getCounter()
         public static void main( String[] args ) {
              LocalInnerClass lic = new LocalInnerClass();
              Counter c1 = lic.getCounter( "Local inner " );
              for( int i = 0; i < 5; i++ ) {
                   System.out.println( c1.next() );
              } // close for
         } // close main()
    } // close classAnd here is what is produced from running this:
    Local inner 0
    Local inner 1
    Local inner 2
    Local inner 3
    Local inner 4The string "Local inner" is passed to the method getCouter as a final String. getCounter creates the class and exits. Later a method in getCounter uses that final String "next". This is where I am lost - getCounter is done and gone, so how the heck is name accessible to the inner class?!?!
    Just when I thought I was getting the hang of this ;)

    So trying to redeem myself...
    You can use "javap -c" to see what a compiler is really doing.
    So using javap (version 1.4.2_04) on the inner class gives the following....
    class LocalInnerClass$1LocalCounter extends java.lang.Object implements Counter{
    LocalInnerClass$1LocalCounter(LocalInnerClass,java.lang.String);
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   aload_0
       5:   aload_1
       6:   putfield        #2; //Field this$0:LLocalInnerClass;
       9:   aload_0
       10:  aload_2
       11:  putfield        #3; //Field val$name:Ljava/lang/String;
       14:  return
    public int next();
      Code:
       0:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
       3:   aload_0
       4:   getfield        #3; //Field val$name:Ljava/lang/String;
       7:   invokevirtual   #5; //Method java/io/PrintStream.print:(Ljava/lang/String;)V
       10:  aload_0
       11:  getfield        #2; //Field this$0:LLocalInnerClass;
       14:  invokestatic    #6; //Method LocalInnerClass.access$008:(LLocalInnerClass;)I
       17:  ireturn
    The second method in the above is the next() method.
    The next() method uses the "getfield" bytecode to retrieve a member variable of the class which is named "val$name".
    The first method in the above is a constructor which takes a string as the only parameter. That string is saved in the member variable of the class called "val$name".
    It is preserving a reference, so if a StringBuffer was used rather than a String then one could alter the value in the for loop of the original code and see the change.

  • ER: Override Methods feature should detect anonymous inner class scope

    Hi,
    Given the following code:
    public class Class1 {
        public static void main(String[] args) {
            Thread t = new Thread() {
                // line 4
            t.start();
    }When the cursor is placed on line 4, activating the Override Method dialog (Source menu), should show Thread methods that I can override, in addition to Object methods. Currently only the method from class Object are being shown. The same treatment should also apply to local method inner classes. This happens with the latest 11g preview 3, and all previous versions.

    Hi,
    I'll file an ER
    Frank

  • Sharing variables between classes

    Hi,
    I wrote a class to handle button functionality. I want the
    onPress event in this class to play a movieclip that is sitting in
    my .fla file, also access some boolean values in the .fla.
    What's the best way to implement this?

    Best practice is to avoid directly accessing non-static final fields of other classes - they should generally by private or if necessary protected.
    get/set methods are the usual way to do this. You can use public static final fields without having a getter.
    Static in the context of field definition identifies fields which exist at the class scope (1 copy per class) versus those (non-static) which exist at the instance scope (1 copy per instance of the class).
    If the value you want to share instance-speciifc, use a non-static field backed up by non-static get/set methods. If you want one copy per process, static fields with static get/set methods are best.
    Chuck

  • Syntax error on token "class", invalid Expression

    Hai,
    i am new to java beans and i have written the following code which gives an error
    Code jsp:
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>beancode</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <!--<form name="form1" action="beancode" method="POST"> -->
    Name: <input type="text" name ="nname"> <br><br><br>
    Address: <input type="text" name ="naddress"> <br><br><br>
         <input type = "submit" value="Submit">
    <% useBean id="sampl"; class="beancode.class"; scope="page"; %>
    <% setProperty name="sampl"; property="*"; %>
    <%--</jsp:useBean> --%>
    <table border="1">
              <tr><td>S.NO</td><td>NAME</td><td width="95">ADDRESS</td></tr>
    <%
              int count =1;
              while (rs.next())
         String name = rs.getString("Name");
              String address = rs.getString("ADDRESS");
    %>
              <tr>
                   <td>
    <%
                        out.print(count);
    %>               </td>
                   <td>
    <%                     out.println(name);
    %>                </td>
                   <td>
    <%                     out.print(address);
                        count++;
    %>               </td>
              </tr>
    <%          }
    %>
         </table>
    <!--</form> -->
    </body>
    </html>
    JAVA Class code:
    import java.sql.*;
    * @author
    public class beancode
    private String employid;
    private Connection con = null;
    // private ResultSet rs = null;
    private PreparedStatement st = null;
    String name, address;
    /** Creates a new instance of beancode */
    public beancode()
    {ok
    try
              Class.forName("com.mysql.jdbc.Driver");
              String url = "jdbc:mysql://localhost:3306/test";
              Connection con =DriverManager.getConnection(url,"root","shasi");
              Statement s = con.createStatement();
              ResultSet rs = s.executeQuery ("Select * FROM Test");
    catch(Exception e)
              System.out.println(e.getMessage());
    public void setemployid(String nname,String naddress)
              name = nname;
              address = naddress;
         public String getemployid()
              return(name);
         public String getemployadd()
              return(address);
    public void insert()
    try
    String s1="insert into samp values('"+name+"','"+address+"')";
    st = con.prepareStatement(s1);
    st.executeUpdate();
    st.clearParameters();
    st.close();
    catch(Exception m)
         public static void main(String args[])
                   beancode b = new beancode();
                   b.insert();
    The error
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 18 in the jsp file: /bean.jsp
    Generated servlet error:
    Syntax error on token "class", invalid Expression
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:397)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    PLEASE HELP ME OUT
    I AM WAITING PLEASE
    Thanks,
    Shasi

    You can try to use the xml form of tag use bean and not <% like this:
    <jsp:useBean id="sampl" class="beancode" scope="page" />
    <jsp:setProperty name="sampl"; property="*" />
    and in the class attribute specify the fully qualified class name without the extension

  • Narrow scope vs. efficiency

    narrow scope:
    for (cond) {
      byte[] buf = new byte[const];
      in.read(buf);
      out.write(buf);
    vs. efficiency:
    byte[] buf = new byte[const];
    for (cond) {
      in.read(buf);
      out.write(buf);
    }What do you prefere? Do you use a profiler to make the decision?

    But what about if buf is used throughout the procedure
    (locally). It should then be declared at the class
    scope for efficiency. You'll not be able to link the
    buf to the method by "{}".In the choise between class or method scope I probably would declare buf in the method scope. At least if the method isn't called very often. You'll have to use common sense. On one hand you want an as narrow scope as possible but on the other hand a narrow scope cannot motivate the creation of zillions of objects in an innermost loop.

  • Is there any difference between java Beans and general class library?

    Hello,
    I know a Java Bean is just a java object. But also a general class instance is also a java object. So can you tell me difference between a java bean and a general class instance? Or are the two just the same?
    I assume a certain class is ("abc.class")
    Second question is is it correct that we must only use the tag <jsp:useBean id="obj" class="abc.class" scope="page" /> when we are writng jsp program which engage in using a class?Any other way to use a class( create object)? such as use the java keyword "new" inside jsp program?
    JohnWen604
    19-July-2005

    a bean is a Java class, but a Java class does not have to be a bean. In other words a bean in a specific Java class and has rules that have to be followed before you have a bean--like a no argument constructor. There are many other features of beans that you may implement if you so choose, but read over the bean tutorial and you'll see, there is a lot to a bean that is just not there for many of the Java classes.
    Second question: I'll defer to someone else, I do way to little JSP's to be able to say "must only[\b]".

  • Class Variables

    So I'm writing a Class in AS2 and I'm having problems in this
    one method. I have a method that uses a Tween class and I want to
    use the onMotionFinished method of the Tween class to change a
    class scope variable, but I seem to loose scope once I'm inside the
    onMotionFinished method. I'll attach the method code, but basically
    when I trace "this" inside the onMotionFinished, I get the Tween,
    and even tracing this.obj._parent doesn't give the class instance,
    it gives level that the tweened object was created on. "_state" is
    the class level variable I'm trying to change, but when I trace it
    from within onMotionFinished I get "undefined". Any suggestions to
    getting back to the class level?

    BeniRose,
    > Actually I figured it out just a few minutes after
    posting! I
    > found it in some old code I had from a previous job. At
    > the begging of the method I include:
    >
    > var me = this;
    That will certainly do it (and of course, that "me" can be
    named
    whatever you like; it can be classRef, thisInstance, me, or
    whatever makes
    sense to you). Another approach is to use the Delegate class,
    which
    features a static create() method that lets you re-route
    scope:
    unblur.onMotionFinished = Delegate.create(
    this,
    function() {
    _state = "shown";
    Note the scope (via "this") as the first parameter, and the
    function as
    the second parameter. You're basically doing this:
    Delegate.create(scope,
    function);, and the function performs in the scope specified.
    Since you're getting into AS2 classes, I encourage you to
    use strong
    typing everywhere you can. It's a good habit to get in to,
    because the
    strong typing gives you better error messages and sometimes
    helps with code
    completion (note the :Void):
    unblur.onMotionFinished = Delegate.create(
    this,
    function():Void {
    _state = "shown";
    You'll have to import the Delegate class at the top of your
    custom class
    in order to use it.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Linking user input to class

    Hello there,
    I have some code that records a ball around the screen for 30seconds, but i am trying to make this length to the users discretion. I have a seperate class which askes for the user input but I can not link this input to the lengh of scene integeger. I was told to use global variables but I have tried but it gives me 2 errors in my class where I have tried to add the userinput to the time frame;
    1. ; expected
    2.Cannot resolve symbol variable string
    here is the code where I have declared the global variable;
    public class Example2 extends JFrame implements ActionListener {
    public static String inputValue;
    public void actionPerformed(ActionEvent e) {
         if (e.getActionCommand().equals("Timer")) {
    String inputValue = JOptionPane.showInputDialog("Length Of Scene");
    System.out.println("Length of Scene " + inputValue);
    and here's the code where I have tried to link the user input to the lengh of scene;
    public class Example extends Panel implements TalktativeGuy, MouseListener
         int timeFrame = String Example2.inputValue;
    any suggestions?

    Scope is the key.
        public static String inputValue;
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Timer")) {
                String inputValue = JOptionPane.showInputDialog("Length Of Scene"); The first statement is a member variable in class scope (by definition). It appears not to be instantiated and so has the value null. The last statement is a local variable urelated to the first statement. If you remove the type (String) from the last statement then it becomes the instantiation/assignment for the first statement (which will no longer be null).
    About the two errors you listed: the stack trace will tell you what class each is in, the sequence of method calls in the class and usually will also tell you the line number where the trouble lies. You can use this information to track down the errors.

  • Synchronized( this ) vs synchronized( SomeClass.class )

    I have seen synchronized bits of code declared in the following ways:
    1)
    synchronized( this )
      //some stuff
    }2)
    synchronized( SomeClass.class )
      //some stuff
    }Could anyone explain the diference or tell me where to read about it.
    Thanks In Adavance!

    Mattbunch is correct, but I will also check later.
    If you want to lock on a class level you lock on a
    static method.The term "locking on a class level" doesn't really mean anything.
    In the original post, the only difference betweensynchronized this() {} and synchronized(SomeClass.class) {} is which object they use as a lock. That's the only difference. There's no difference in what gets protected or how.
    Static methods are at the class scope, global, and
    they are locked for the class, not just the
    instance, understand?Again, that statement--the concept of being "locked for the class vs. for the instance"--doesn't really have any meaning. If you declare a static method synchronized, it obtains one particular object's lock (that of the Class object corresponding to that method's class), and if you declare an instance method syncrhonized, it obtains a different object's lock--that of the intstance whose method you're calling. That's the only difference--which lock you obtain. There's no inherent difference in the scope of the "protection".
    Also remember that locking on the static methods does
    not prevent another thread from entering a non static
    public method.You don't "lock on" a method. But assuming you mean "declaring a static method synchronized," it doesn't stop another thread from entering any other unsynchronized method, static or not, public or not, and it doesn't stop a thread from entering any synchronized instance method. It only stops threads from entering blocks or methods syncrhronized on the Class object for that class.

  • Muliple classes in applets

    am just starting to learn to use applets, and am a little confused with the structure. after imports, the applet generaly contines with pubic class xyz extend frame for example, which encomases most of the rest of the applet, so does that mean i can only use methords of xzy or can i put classes in side xzy.
    If you can understand what i mean, or can point me to an easy resourse on how i should structure, an applet and how i should layout different class's inside the applet i would be great full. Exaclty 5 duke doller greatfull (cos thats what i got left).

    Here's an example to illustrate.
    You can just as well put the two outer classes inside the applet. If you do then you won't need to pass a reference into the ControlPanel class to call methods in the DisplayPanel class. Instead you would put the DisplayPanel instance variable in class scope. In java:
    public class ExampleApplet extends JApplet
        DisplayPanel displayPanel;
        public void init()
            displayPanel = new DisplayPanel();
        class DisplayPanel...
        class ControlPanel extends JPanel
            JComboBox outerColor, innerColor;
            public ControlPanel(DisplayPanel dp)
                // create components for panel
        public static void main...
    }To call methods or get access to variables in another class you need a way to get a reference to that class.
    One benefit in keeping the classes separated is that you can isolate your event code, your drawing code and your gui display code. This can make it easier to conceptualize and maintain.
    /*  <applet code="ExampleApplet" width="400" height="400"></applet>
    *  use: >appletviewer ExampleApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Random;
    import javax.swing.*;
    public class ExampleApplet extends JApplet
        public void init()
            DisplayPanel displayPanel = new DisplayPanel();
            ControlPanel control = new ControlPanel(displayPanel);
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            cp.add(control, "North");
            cp.add(displayPanel);
         * Convenience method so you can run applet from command line
        public static void main(String[] args)
            JApplet applet = new ExampleApplet();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            applet.start();
            f.setVisible(true);
    class DisplayPanel extends JPanel
        Random seed;
        Color bgColor, outerColor, innerColor;
        public DisplayPanel()
            seed = new Random();
            bgColor = Color.white;
            outerColor = Color.blue;
            innerColor = Color.orange;
            setBackground(bgColor);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int dia = Math.min(w, h)/4;
            g2.setPaint(outerColor);
            g2.fill(new Ellipse2D.Double(w/2 - dia/2, h/2 - dia/2, dia, dia));
            g2.setPaint(innerColor);
            g2.fill(new Ellipse2D.Double(w/2 - dia/4, h/2 - dia/4, dia/2, dia/2));
        public void setBackground()
            Color color = new Color(seed.nextInt(256), seed.nextInt(256), seed.nextInt(256));
            setBackground(color);
            repaint();
        public void setOuterColor(Color color)
            outerColor = color;
            repaint();
        public void setInnerColor(Color color)
            innerColor = color;
            repaint();
    class ControlPanel extends JPanel
        DisplayPanel displayPanel;
        JComboBox outerColor, innerColor;
        public ControlPanel(DisplayPanel dp)
            displayPanel = dp;
            // create components for panel
            JButton bgColor = new JButton("background");
            bgColor.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    displayPanel.setBackground();
            String[] outerColorNames = {
                "blue", "yellow", "cyan", "magenta"
            outerColor = new JComboBox(outerColorNames);
            String[] innerColorNames = {
                "orange", "red", "green", "pink"
            innerColor = new JComboBox(innerColorNames);
            ColorListener l = new ColorListener();
            outerColor.addActionListener(l);
            innerColor.addActionListener(l);
            // layout components
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            add(bgColor, gbc);
            gbc.anchor = gbc.EAST;
            add(new JLabel("outer"), gbc);
            gbc.anchor = gbc.WEST;
            add(outerColor, gbc);
            gbc.anchor = gbc.EAST;
            add(new JLabel("inner"), gbc);
            gbc.anchor = gbc.WEST;
            add(innerColor, gbc);
        class ColorListener implements ActionListener
            Color[] outerColors = {
                Color.blue, Color.yellow, Color.cyan, Color.magenta
            Color[] innerColors = {
                Color.orange, Color.red, Color.green, Color.pink
            public void actionPerformed(ActionEvent e)
                JComboBox combo = (JComboBox)e.getSource();
                int index = combo.getSelectedIndex();
                if(combo == outerColor)
                    displayPanel.setOuterColor(outerColors[index]);
                if(combo == innerColor)
                    displayPanel.setInnerColor(innerColors[index]);
    }

  • Memory increases, GC does not collect.

    I am developing an AIR application using FlexBuilder (FlashBuilder) 4.0.1 (Standard) in an Eclipse plugin environment, on the Windows 7 64-bit platform.
    My application is intended to run full-screen, on a touchscreen device, as an application for small children (pre-k).
    The general operation is to present a series of scenarios, one by one, from a collection of separately developed swf files. (each swf file is a scenario).  The child responds to the swf file, the swf file sends an event to the player, which performs an unloadAndStop() on the Loader object that loaded the swf.  Then the next swf is loaded.
    The problem we are seeing is that each swf file adds about 15-25 MB to the Workingset Private allocation of the AIR application (or the ADL.EXE runtime).  Very little of this RAM is returned.  After about 140 of these scenarios, the AIR runtime consumes about 1.6 GB of RAM.  This, in itself, is not the problem - we could buy more RAM.
    The problem is that the Loader crashes here, and takes the whole AIR runtime with it.
    We also have a few "special purpose" swf files which are basically just wrappers around a s:VideoPlayer control, that plays a bindable file - .flv video, and the complete event fires the event that tells the AIR player to unloadAndStop the swf.
    Since the video player took no manual intervention to test, I built a set of these to simulate a high load, and found that:
    The .flv files are opened, but they are never closed. Since the s:VideoPlayer control is an MXML construct, there is no explicit way I can see to tell it to close the dang file when it's done.  (it's not documented, anyway).
    At exactly 32 video-swf items, the videos will continue to play, but there is no more audio.
    At exactly 73 video-swf items, (seemingly regardless of the SIZE of the .flv file I select), the 73rd item crashes the Loader (and AIR player).
    I supply unloadAndStop() with the (true) parameter.  I follow it with a System.gc().
    I explicitly remove ALL of my listeners. (in the AIR player application - I assume no control over items within the swf items that I am playing, since we assume we eventually may end up playing 3rd-party developed items; so we rely only on the return of a completion event, and a data structure).
    I explicitly close() ALL of my audio streams. (at the AIR player level - not in the swfs.)
    I explicitly stop() ALL of my timers.
    My loader is instantiated in an element called "myLoaderContainer" - and after I receive my completion event, I do a myLoaderContainer.removeAllElements();
    I have tried both the System.gc() call and the "unsupported"  LocalConnection().connect('foo') call.  both of these have zero effect. (in other words, I think there is probably no garbage to collect).
    Still, I find it strange that nowhere, is it written, any kind of hint about how often garbage collection will do it's thing, and having graphed the flash.system.System.privateMemory; usage against all of my functions, and narrowed it down to my loader, and seeing that this allocation is never reclaimed, even on loader.unloadAndStop(true); - I wonder exactly what is the (true) parameter for, in that method?
    I don't know what else I am supposed to do to force my Loader to *actually* unloadAndStop().
    One would think that unloadAndStop() would not mean: "cease all functioning, but continue to occupy memory until the parent application chokes on it's own heap."

    I recompiled the memory leaking program using AIR 3.0 and the leak remains. However my previous description of the problem was incorrect. It's not a bytearray I'm using. It's just a normal  array, of 9 floats. Now this array is is being updated in an event, on an indefinite basis (from hardware data provided by a separate process running as a socket server). The updating array  is a class scope array. On each update the index restarts to zero (ie. it's not a ballooning array). However, each item of that updating array is then being redispatched in the context of another socket event (request events by another process), using socket.writeDouble() - also on an indefinite basis.
    So while the array is being written in the context of one event, it's simultaneously being read in the context of another uncorrelated event.
    My only theory is that the speed at which the array is being written/read (since only nine floats) is causing some overflow in the number of temporary arrays that might be generated to accomodate such abuse. And that maybe such temps are becomining lost to the gc - that pehaps the gc can't keep up with the abuse. But that's just me speculating what theorys I could test for workarounds.
    In native code I'd use various thread controls (mutexes etc),  to control read/writes on the async socket events, but here I'm somewhat at a loss as to how to otherwise control the data flow. Indeed I ended up rewriting the program  in native code (c++) to get around the memory leak.
    Carl

  • How to use beans in more than one page

    hello members,
    can somebody tell me how to make beans availabe to more than one page ,i used scope variable as "application"
    in which i set the value of java bean and in that page it show all values of that bean even it modified
    but when redirect to another jsp page it does not show modifided value,it shows its default value
    what shld i use tell me
    following thing that i use in forwarded jsp page
    <jsp:useBean="same id in previous jsp page", class="same class", scope="application"/>
    and then i am using boolean variable which set false default ,but i set it manually though
    setfuction (assume) in original jsp page,but in redirected page it showing it value fasle
    i don't know why
    can somebody (Bean Bond) help me in this problem
    i will very thankfull to you
    plz..................

    My dear friend,
    your scope is wrong. Since you run a JSP page and you want it available everywhere, the only thing that all pages have common is session. So changing your bean scope to session will keep the bean variables and the rest you have on it.
    Try it and let me know.

  • Can't access ResultSet

    Hi
    I am trying to create a ResultSet "rs" object that I can reuse with a next and previous button. So I need to create it once and then be able access it so that the user can move through it. The following code is what I have so far. I am getting a variable not found error for display(rs). What's wrong with this code or the design in general.
    Note: when the SQL statement is in the actionPerformed method it works fine, just not when it's in the constructor.
    Thanks,
    Steve Hartfield
    // begin code
    class NextRecord implements ActionListener {
    private DataPanel screenvar;
    private JTextArea msgout;
    private Connection dbconn;
    private ButtonPanel control;
    public NextRecord( Connection dbc, DataPanel scv, JTextArea msg, ButtonPanel control ) {
    dbconn = dbc;
    screenvar = scv;
    msgout = msg;
         try {     // 2
    Statement statement =dbconn.createStatement();
    String query = "SELECT * FROM addresses " +
    msgout.append( "\nSending query: " +
    dbconn.nativeSQL( query ) + "\n" );
    ResultSet rs = statement.executeQuery( query );
    // statement.close();
         }     // 2
    catch ( SQLException sqlex ) {     // 3
         msgout.append( sqlex.toString() + sqlex.getMessage() );
              }     // 3
    public void actionPerformed( ActionEvent e ) {     //1
              display(rs);
    }     // 1
    public void display( ResultSet rs ) {
    try {
    int recordNumber = rs.getInt( 1 );
    if ( recordNumber != 0 ) {
    screenvar.id.setText( String.valueOf(recordNumber) );

    Well, your code could be a bit better structured but one thing to note is that the cursor is initally placed before the first record in the ResultSet. To move to the first row, you need to call rs.next(). Every time you call rs.next(), the cursor moves to the row of the ResultSet.
    Thus, if you wanted to perform the query and then simply print out the value in column 1 of each row you would do:
    while (rs.next())
    try
    System.out.println(rs.getString(1));
    catch (SQLException sqlex)
    System.out.println(sqlex.toString());
    }A ResultSet is, by default, not scrollable, i.e. you can only move forward through it. To create a scrollable result set - so you can move back and forward - look at the arguments that that be supplied to the createStatement() method of class Connection.
    Finally, your rs object is declared in NextRecord() and only has scope within this method. You will not be able to access it in ActionPerformed() unless you give it class scope i.e. declare it at the same point in your code as Connection, ButtonPanel etc.

  • Tax Calculator

    Hi,
    I'm new & working on my assignment. I'm working on a tax calculator applet. I'm having problems (cannot work) and would like to ask if anyone can correct my mistakes.
    Here's my code
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TaxCal extends Applet implements ActionListener {
         private TextField income, age, child, parent, course, maid, pay;
         private Button b2, b3;
         public void init() {
                   setBackground(Color.lightGray);
                   /* Create the input boxes, and make sure that the background
                   color is white. (On some platforms, it is automatically.) */
                   income = new TextField(10);
                   Panel incomePanel = new Panel();
                   incomePanel.setLayout(new BorderLayout(2,2));
                   incomePanel.add( new Label("Input your annual income"), BorderLayout.WEST );
              incomePanel.add(income, BorderLayout.CENTER);
                   age = new TextField(2);
                   Panel agePanel = new Panel();
                   agePanel.setLayout(new BorderLayout(2,2));
                   agePanel.add( new Label("Input your age"), BorderLayout.WEST );
                   agePanel.add(age, BorderLayout.CENTER);
                   child = new TextField(2);
                   Panel childPanel = new Panel();
                   childPanel.setLayout(new BorderLayout(2,2));
                   childPanel.add( new Label("Number of children"), BorderLayout.WEST );
                   childPanel.add(child, BorderLayout.CENTER);
                   parent = new TextField(1);
                   Panel parentPanel = new Panel();
                   parentPanel.setLayout(new BorderLayout(2,2));
                   parentPanel.add( new Label("Number of parent that live with you"), BorderLayout.WEST );
                   parentPanel.add(parent, BorderLayout.CENTER);
                   course = new TextField(5);
                   Panel coursePanel = new Panel();
                   coursePanel.setLayout(new BorderLayout(2,2));
                   coursePanel.add( new Label("Course fee"), BorderLayout.WEST );
                   coursePanel.add(course, BorderLayout.CENTER);
                   maid = new TextField(5);
                   Panel maidPanel = new Panel();
                   maidPanel.setLayout(new BorderLayout(2,2));
                   maidPanel.add( new Label("Maid levy paid"), BorderLayout.WEST );
                   maidPanel.add(maid, BorderLayout.CENTER);
                   pay = new TextField(10);
                   pay.setEditable(false);
                   Panel payPanel = new Panel();
                   payPanel.setLayout(new BorderLayout(2,2));
                   payPanel.add( new Label("Please pay"), BorderLayout.WEST );
                   payPanel.add(pay, BorderLayout.CENTER);
                   Panel buttonPanel = new Panel();
                   buttonPanel.setLayout(new GridLayout(1,3));
                   Button b2 = new Button("Reset");
                   b2.addActionListener(this);     // register listener
                   buttonPanel.add(b2);
                   Button b3 = new Button("Calculate");
                   b3.addActionListener(this);     // register listener
                   buttonPanel.add(b3);
                   /* Set up the layout for the applet, using a GridLayout,
              and add all the components that have been created. */
              setLayout(new GridLayout(8,2));
                   add(incomePanel);
                   add(agePanel);
                   add(childPanel);
                   add(parentPanel);
              add(coursePanel);
              add(maidPanel);
              add(payPanel);
              add(buttonPanel);
              /* Try to give the input focus to xInput, which is
              the natural place for the user to start. */
              income.requestFocus();
              } // end init()
         public Insets getInsets() {
    // Leave some space around the borders of the applet.
         return new Insets(2,2,2,2);
         // event handler for ActionEvent
         public void actionPerformed (ActionEvent e) {
              if (e.getSource() == b3) {
                   double x = 0;
                   double relief = 0;
                   String incomeString = income.getText();
                   double income = Double.parseDouble(incomeString);
                   String ageString = age.getText();
                   int age = Integer.parseInt(ageString);
                   String childString = child.getText();
                   int child = Integer.parseInt(childString);
                   String parentString = parent.getText();
                   int parent = Integer.parseInt(parentString);
                   String courseString = course.getText();
                   double course = Double.parseDouble(courseString);
                   String maidString = maid.getText();
                   double maid = Double.parseDouble(maidString);
                             //determine age relief
                             if(age<55) {
                             relief += 3000;
                             else if(age>=55 && age<= 59) {
                             relief += 8000;
                             else {
                             relief += 10000;
                             //determine children relief
                             if(child<=3) {
                             relief += (child*2000);
                             else if(child>3 && child<6) {
                             relief += ((child-3)*500 + 6000);
                             else {
                             relief += 0;
                             //determine parent relief
                             if(parent == 1) {
                             relief += 3000;
                             else if(parent ==2) {
                             relief += 6000;
                             else {
                             relief += 0;
                             //determine course subsidy
                             if(course != 0 ) {
                                  if(course <= 2500) {
                                  relief += course;
                                  else {
                                  relief += 2500;
                             //determine maid levy
                             if(maid != 0) {
                                  if(maid <= 4000) {
                                  relief += 2 * maid;
                                  else {
                                  relief += 0;
                             income =- relief;
                             if (income <= 7500) {
                             x = income * .02;
                             else if (income > 7500 && income <= 20000)
                             x = 150 + ((income - 7500) * .05);
                             else if (income > 20000 && income <= 35000)
                             x = ((income - 20000) * .08) + 775;
                             else if (income > 35000 && income <= 50000)
                             x = ((income - 35000) * .12) + 1975;
                             else if (income > 50000 && income <= 75000)
                             x = ((income - 50000) * .16) + 3775;
                             else if (income > 75000 && income <= 100000)
                             x = ((income - 75000) * .2) + 7775;
                             else if (income > 100000 && income <= 150000)
                             x = ((income - 100000) * .22) + 12775;
                             else if (income > 150000 && income <= 200000)
                             x = ((income - 150000) * .23) + 23775;
                             else if (income > 200000 && income <= 400000)
                             x = ((income - 200000) * .26) + 35275;
                             else if (income > 400000)
                             x = ((income - 400000) * .28) + 87275;
                   pay.setText("$" + x);
              else
                   income.setText("");
                   age.setText("");
                   child.setText("");
                   parent.setText("");
                   course.setText("");
                   maid.setText("");
                   pay.setText("");
    }     // end actionPerformed()
    }      // end class TaxCal

    The problem that you're having is actually one of scope. At the top of your class, you declare the two buttons:
    private Button b2, b3;These Button objects have class scope.
    Within the init() method, the lines:
    Button b2 = new Button("Reset");
    Button b3 = new Button("Calculate");declare another pair of Button objects that have method scope. These are the objects that are added to the panel and that receive the mouse click.
    In the actionPerformed() method, the statement:
    if (e.getSource() == b3) {cannot refer to the two Button object that are encapsulated in the init() method, but it can and does refer to the Button object with class scope. This is not the object that was added to the panel, so it hasn't received any events and won't be the source of the event that triggered execution of the actionPerformed() method. Since you don't check for any other events, the processing associated with the "Reset" button (b2) will always be executed.
    If you change the two lines in the init() method to:
    b2 = new Button("Reset");
    b3 = new Button("Calculate");
    your code will work as originally written (but there are a couple of errors in the computation logic).

Maybe you are looking for