Class variable declaration

Hello.
Just looking through some code and I see a class variable declared as so...
static final MessageDigest digestFunction;
static { // The digest method is reused between instances to provide higher entropy.
        MessageDigest tmp;
        try {
            tmp = java.security.MessageDigest.getInstance(hashName);
        } catch (NoSuchAlgorithmException e) {
            tmp = null;
        digestFunction = tmp;
    }I have never come accoss a variable being declared in this way and it looks strange. The use of static before the opening brace is strange to me, and just the fact that this is not inside the constructor. Would this code be run after or before code inside the class constuctor?
Thanks for any help, just a little confused!

Sir_Dori wrote:
Ah yes, of course it could not be within the constructor as it is static, sorry.
So when would the class be loaded? Could this be the first time the ClassName.staticBlockVar is accessed, Most likely, yes. The first time something else uses the class. Classloading in Java is lazy.
Also, is the code not reevaluated every time it is referenced ?No. Only when the class is loaded (actually, when it's initialized, but usually it boils down to the same thing)
You can write some simple tests for this, by writing a constructor and a static initializer, then instantiating it twice, for example. Don't be afraid to just play around with code to test assumptions. I find JUnit very handy for experimenting with assumptions.

Similar Messages

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • How to declare class variable with generic parameters?

    I've got a class that declares a type parameter T. I know how to declare a static method, but this doesn't work for a static variable:
    public class Test< T >
        * Map of String to instances of T.
        * error: '(' expected (pointing to =)
        * <identifier> expected (pointing to () )
       private final static < T > Map< String, T > MAP = new HashMap< String, T >();
        * Get instance of type T associated with the given key.
       public final static < T > T getType( String key )
          return MAP.get( key );
    }Edited by: 845859 on Mar 20, 2011 11:46 AM

    jveritas wrote:
    I'm trying to create a generic polymorphic Factory class that contains boilerplate code.
    I don't want to have to rewrite the registration code every time I have a different return type and parameter.I haven't seen a case yet where that is reasonable.
    If you have hundreds of factories then something is wrong with your code, design and architecture.
    If you have a factory which requires large number of a varying input types (producing different types) then something is probably wrong with your code and design.
    A reasonable factory usage is one where you have say 20 classes to be created and you need to add a new class every 3 months. Along with additional functionality represented by the class itself and perhaps variances in usage. Thus adding about 3 lines of code to one class is trivial. Conversely if you have hundreds of classes to be created by the factory and you are adding them daily then it is likely that
    1. Something is wrong with the architecture which requires a new class every day.
    2. You should be using a dynamic mechanism for creation rather than static because you can't roll out a static update that often.
    More than that the idiom that leads to factory creation is different for each factory. A factory that creates a database connection is substantially different than the one used in dynamic rules logic processing. A generic version will not be suitable for both.
    Actualy the only case I know of where such a factory might be seem to be a 'good' idea is where someone has gotten it into their head that every class should be represented by an interface and every class created by a factory (its own factory.) And of course that is flawed.

  • Assign a value to class variable

    I want to define a class variable in class. And I want all subclasses of that class ot have a different value for that class variable. How can I do that?
    public class BaseClass {
      public static String tableName = "";
    }Now if I have a ClassA and I want to assign a value like this :
    public class ClassA extends BaseClass {
      tableName = "location";
    } I got an error message.
    I can move it in a static initializer block but then it will only work when the class is loaded. In my case its possible i want to get this value without loading the class.
    Ditto if i move it to constructor.
    Any input? Thanks

    Are you saying that if i have 2 classes ClassA and
    ClassB inherited from BaseClass, then both are
    sharing the same copy of 'tableName' staticvariable?
    If yes then I should go with an instance variable.No, I am saying that you can easily declare a
    tablName in A and another tableName in B.
    A.tableName will be shared between all the instances
    s of A. B.tableName will be shared between all the
    instances of B. And BaseClass.tableName is
    irelevant. I think you try to use
    BaseClass.tableName as some kind of template for
    sub-classes, but this does not happen: you need to
    declare tableName again and again in each subclass.
    IThanks for clarifying. Each class needs to have a variable "tableName" and it needs to have one copy of this variable for all of that class's objects. 2 classes will not have the same value of this tableName variable.
    Thats why I was defining it as static variable. And I define it in BaseClass so that I dont have to define it again in each subclass.
    Is there any better way? Thanks

  • Why can't I move a variable declaration from inside a Sub to the Declarations area?

    I'm writing an app and so far, so good. But I need wider access to an array defined in my "Form_Load" sub.
    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Assign checkboxes to an array.
    Dim Checkboxes() As CheckBox = {chkThumb01, chkThumb02, chkThumb03, chkThumb04, _
    chkThumb05, chkThumb06, chkThumb07, chkThumb08, chkThumb09, chkThumb10}
    Moving the declaration ("Dim Checkboxes()...") from "Sub frmMain_Load" up into the Declarations space just above it breaks my program. :(
    I tried putting it in a Module and that fails too. The ONLY place it work's is in Form_Load (it's not related to being an array because at least one standard integer variable declaration has this problem too.)
    I have other variables in the Declarations area that work fine (eg: "Dim bolChanges as Boolean"), but for some reason, I can't move others out into what
    should be a more global namespace.
    Anyone know what's going on? Thx.

    No, because this makes no difference.
    Background #1: If you do not write your own constructor (=Sub New), the VB compiler adds a default constructor. It contains a call to Sub InitializeComponent. In this Sub, the controls are created and assigned to chkThumb01 etc. You see it if you type "Sub
    New[Enter]":
    Sub New()
    InitializeComponent()
    End Sub
    Background #2: If you write
    Public Class Test
    Private values As Integer() = {1, 2, 3}
    End Class
    it is identical to
    Public Class Test
    Private values As Integer()
    Sub New()
    values = New Integer() {1, 2, 3}
    End Sub
    End Class
    As you can see, the assignments that you do to fields of the class in the declaration line are actually executed in the constructor (sub new).
    Now put both backgrounds together. Consequently, this code
    Public Class Form1
    Private buttons As Button() = {Button1, Button2, Button3}
    End Class
    is identical to this one:
    Public Class Form1
    Private buttons As Button()
    Sub New()
    buttons = New Button() {Button1, Button2, Button3}
    InitializeComponent()
    End Sub
    End Class
    Obviously, the assignment to variable "buttons" is done before the call to Sub InitializeComponent. At this point, variables Button1, Button2 and  Button3 are still empty (Nothing) because they will be set in Sub InitializeComponent. Consequently,
    the array buttons contains just {Nothing, Nothing, Nothing}
    In opposite, if the array buttons is set in the Load event, Button1, Button2 and Button3 have already been set before, Consequently, the array buttons correctly contains references to the three buttons.
    Armin

  • URGENT: problem with variable-declaration while precompiling

              Hi,
              i got a problem while precompiling my webapplication.
              i got some jsp-pages, each containing following code
              <%@ include file="/header.jsp" %>
              <% button = true; %>
              [...some code...]
              <%@ include file="/footer.jsp" %>
              The variable 'button' is defined in header.jsp and
              evaluated in footer.jsp. When i run through my application without precompiling
              it, there appear NO errors, but when i try to precompile my pages, the jsp-compiler
              reports an error in footer.jsp, because in footer.jsp is the 'button'-Variable
              used, but not defined and not included (because all other pages include footer.jsp)
              How can I tell the jsp-Compiler not to check for variable declarations, or what
              else can i do to work around this problem ?
              thanks,
              Dirk Bade
              

    Thanks for the sample. Changed it to look this way. Still getting the error message from above. Any clue?
    [ BTW: you can see the auto-fixits that Netbeans used to resolve the exception thrown errors from earlier.  Ugly ... I used Netbeans for the ease of interface generation, but I am spending a lot time chasing down little stuff like this. ]
    public class DesktopApplication1View extends FrameView {
        public DesktopApplication1View(SingleFrameApplication app) throws PortInUseException, UnsupportedCommOperationException, IOException, NoSuchPortException {
            super(app);
          initComponents();  //interface code follows this until the variables below ...
            String      defaultPort = "/dev/ttyS0";
            String      portName;
            ByteBuffer  asciiBytes = null;
            CommPort    commPort = null;
            byte[] h = new byte[asciiBytes.capacity()];
            asciiBytes.get(h, 0, h.length);
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(defaultPort);
                System.out.println("Default port" + defaultPort + "found.");
            if ( portIdentifier.isCurrentlyOwned() )
                System.out.println("Error: Port is currently in use");
            try {
                 commPort = portIdentifier.open(this.getClass().getName(), 200);
            } catch (NoSuchPortException e) {
            System.out.println("Whoops! Cannot identify the port.");
            }

  • HOW-TO initialize class variable

    How can an annotation initialize a class variable? For example, JEE5 has an annotation called @EJB that initializes a class variable with a remote or local interface:
    @Stateless class Foo
    @EJB bar;
    bar.scoobyDoobyDoo(); // I can use bar seemingly before it was initialized!
    In general terms, how can annotation be used to initialize class variables?

    It can't.
    What it can do is tell something else that this needs to be done, and that something else can do it.
    That something else might be an annotation processor running at build / compile time, which might generate some code to do it, or might generate some configuration file that causes it to be done later.
    That something else might alternatively be a runtime artifact, that can look at the annotation and carry out the requested operation. For example a container could do it.
    So an annotation cannot do anything, including initailizing a class variable, but it can declare that the class variable needs to be initialized in some way.
    Bruce

  • Variable declaration.

    Hello there!!  As all you know, we declare on a variable name by using the keyword 'var' followed by the variable name.  My question is simply is there any way to define the variable name based on an input from the user.  Hope someone here has an appropriate answer.  Thanks in advance!!  Atar.

    Hi there kglad!!
    Again, thanks you very much about your kindness to answer to my issue.
    Because I want to make sure that I've understand you correctly, I've been attached the following code and will be very happy if you will quickly review it:
    //Declare on readers class:
    Public class Readers{
    //declare on properties:
    Public var firstName:String;
    Public var lastName:String;
    Public var readerAge:uint;
    //declare on the class's constructor:
    Public function Readers(fName:String, lName:String, rAge:uint):void{
    firstName = fName;
    lastName = lName;
    readerAge = rAge;
    //add some readers:
    reader1[firstNameinputTextBox.text] = new Readers("Tim","Wozniak",45);
    reader2[firstNameinputTextBox.text] = new Readers("John","smith",23);
    reader3[firstNameinputTextBox.text] = new Readers("Bob","Blackstone",20);
    //now, assuming that the user enter the following names: Tim, John and Bob for those three instances of the Readers class, are the variables names that those instances are stored inside them will be the names that the user entered in the first name input text box? For example,can I refer to those instances' properties by the following syntax:
    trace(Tim.firstName); //Tim.
    trace(John.lastName);//smith.
    trace(Bob.readerAge);//20.
    |||||||||||||||||||~
    I'll be very glad if you'll review my code and tell me if it will work.
    Wait for your response ASAP!
    Many thanks in advance!!
    Atar.
    ב-9 באוג 2011, בשעה 08:19, kglad <[email protected]> כתב/ה:
    that logic is probably not what you want.  if you have a reader class there's no reason to have an addNewReader() method unless the reader class will be a repository of all reader instances.  if that's the situation, it would be better to name it something like Readers class or ReaderGroup class and also have a Reader class that contain the properties and methods of each Reader instance.
    if you don't need a ReaderGroup class, there's no reason to have an addNewReader() method.  each Reader instance will be instantiated in the constructor.  and you can use a string to assign that variable but again, you can't type the variable:
    somedynamicclassinstance[readerstring]=new Reader();
    or, if you need a ReaderGroup class, you could use:
    var rg:ReaderGroup=new ReaderGroup();  // this class should be a singleton class.
    rg.addNewReader("atar11",this);  // assuming "this" is a dynamic class instance, eg a movieclip
    // and in ReaderGroup:
    static public function addNewReader(nameS:String,dynamicclassinstance:*):void{
    dynamicclassinstance[nameS]=new Reader();
    classA.push(dynamicclassinstance[nameS]);  // where classA is a static array.
    // but this doesn't really make any sense.  you should just assign a property to your Reader instance, eg:
    var r:Reader=new Reader();
    r.nameS = nameS;
    >

  • How to access an element using its name or id if it is not a class variable?

    I am trying to retrieve the element I added to my UI in a different  function. I am using actionscript 3. I know I can put the variable into a  class variable, so it can be access anywhere in the class, but I have  too many elements. Is there anyway I could access them without putting  them into class variable?
    Thanks.
    public class Test extends SkinnableContainer{
    // private var image:Image; <-- I try not to do this, too messy
    private function func1() {
        var image:Image = new Image();
        addElement(image);
    private function func2() {
        var image:Image = /* how to get the element from my UI without putting into class variable */

    Here is what works for me:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx"
                   creationComplete="init()"
                   minWidth="955" minHeight="600">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import spark.components.Image;
                private var  image:Image;
                private function init():void
                    image = new Image();
                    addElement(image);
                    trace(this["image"]);
            ]]>
        </fx:Script>   
    </s:Application>

  • Template declaration error when variable assigned is the same as variable declared

    Hi Fedor,
    In comm-central repository, when compiling mozilla/mfbt/Compression.cpp using -std=c++11, it results in an error as follows:
    "../dist/include/mozilla/CheckedInt.h", line 400: Error: Unexpected type name "T" encountered.
    "../dist/include/mozilla/CheckedInt.h", line 400: Error: value is not defined.
    "../dist/include/mozilla/CheckedInt.h", line 400: Error: No direct declarator preceding ">".
    "../dist/include/mozilla/CheckedInt.h", line 400: Error: A declaration does not specify a tag or an identifier.
    "../dist/include/mozilla/CheckedInt.h", line 400: Error: Default template argument cannot be specified on the definition of a class template member that appears outside of its class.
    "../dist/include/mozilla/CheckedInt.h", line 400: Error: Templates can only declare classes or functions.
    "../dist/include/mozilla/CheckedInt.h", line 413: Error: No primary specialization for partial specialization NegateImpl<T, 0>.
    "../dist/include/mozilla/CheckedInt.h", line 416: Error: Too many arguments for template mozilla::detail::NegateImpl<T>.
    8 Error(s) detected.
    After a check on the file CheckedInt.h, it was narrowed down to the following code that resulted in the failure (the variable assigned, isSigned is the same as variable being declared) :
    template<typename T, bool IsSigned = IsSigned<T>::value>
    struct NegateImpl;
    This code, however compiles without problems in gcc-4.8.
    A workaround was to use a different variable declared in the template (e.g. bool IsTSigned = IsSigned<T>). But I just wanted to be sure whether is this a bug in 12.4 Beta or whether coding rules in templates do allow this kind of declaration? Kindly advise. Thanks.
    Regards,
    Brian

    Hi Steve,
    The declaration made below is not valid when -std=c++11 is not used (it causes the same compile-time errors when using July Refresh):
    template<typename U> class IsSigned;
    template<typename T, bool IsSigned = IsSigned<T>::value>
    struct NegateImpl;
    So far, the workaround was to use a different variable declared in the template (e.g. bool IsTSigned = IsSigned<T>).
    Regards,
    Brian

  • Reassign class variable to a blank instance of its class

    When I declare a class variable
    private var myVar:MyClass = new MyClass();
    It creates a new instance of that class that will trace as [Object MyClass].
    However, as soon as I assign it to something
    myVar = thisOtherVar;
    It will now trace as [Object thisOtherVar].
    I need to get it back to where it's just an "empty" blank class instance, if that makes any sense at all.
    How do I go about doing that? Thanks!

    I'm brand new to OOP - I've been watching iTunes U videos and reading books but it's still all pretty abstract in my mind and it's difficult for me to pin point how all that stuff translates to actually writing good code.
    Basically, it's an open ended kid's dictionary. You drag the lettes to drop boxes, touch the check to see if it's a word, and then a picture representing the word pops up on the screen.
    All of it works except if you try to remove a letter that's already been placed. Originally, I wanted the check button to do a sweep of the dropped letters and see if they had formed a word - but I couldn't figure out a way to do that. So then I started tracking movements of letters in real time, and that's when it got really confusing. I think I just need to start over and try to make the code a bit cleaner. Right now this is what I've got:
    if (currentUsedBlank is BlankSquare) {  //if they have removed a letter that has already been dropped
                    if (currentUsedBlank != currentBlank) { //and it's been placed back on a different square
                        currentUsedBlank.letter = null;
                else {
                    currentUsedBlank.letter = null;
                if (this.dropTarget.parent is BlankSquare && currentBlank.letter == null) {
                    SpellingGlobals.lettersInBlanks[SpellingGlobals.lettersInBlanks.length] = this;
                    this.x = this.dropTarget.parent.x + 10;
                    this.y = this.dropTarget.parent.y - 10;
                    var myClass:Class = getDefinitionByName(getQualifiedClassName(MovieClip(this))) as Class;
                    var newLetter:MovieClip = new myClass();
                    newLetter.x = currentLetter.startPoint.x;   
                    newLetter.y = currentLetter.startPoint.y;
                    newLetter.letter = currentLetter.letter;
                    newLetter.reference = currentLetter.reference;
                    newLetter.startPoint.x = currentLetter.startPoint.x;
                    newLetter.startPoint.y = currentLetter.startPoint.y;
                    newLetter.isVowel = currentLetter.isVowel;
                    currentBlank.letter = currentLetter.letter;
                    if (SpellingGlobals.isCaps == true) {
                        newLetter.txt.text.toUpperCase();
                        if (SpellingGlobals.isColor == true) {
                            if (newLetter.isVowel) {
                                newLetter.txt.textColor = SpellingGlobals.colorVowel;
                            else {
                                newLetter.txt.textColor = SpellingGlobals.colorCon;
                    MovieClip(root).addChild(newLetter);
                    SpellingGlobals.copiedLetters[SpellingGlobals.copiedLetters.length] = newLetter;
                    currentBlank.alpha = 0;
                else {
                    this.x = MovieClip(this).startPoint.x;
                    this.y = MovieClip(this).startPoint.y;
                this.stopDrag();

  • Netbean variable declaration help

    I've been trying to crank out yet another mortgage program. The problem I have is with the declaration of the following
    double loan = Double.parseDouble(loanField.getText());
    double rate = Double.parseDouble(rateField.getText());
    double years_due = Double.parseDouble(years_dueField.getText());
    I'm not quite certain if it's the declaration itself, or if I didn't set up the GUI properly. I've been tinkering with this for 3 days so I figured I'd ask for help. I can't seem to find a post that suitably answers my question. Any help would be appreciated. Here is the code. I'm using Netbean IDE 6.0.1 if that is of any use to you.
    * week2_herbieGUI.java
    * Created on August 1, 2008, 6:45 PM
    * @author  archon
    public class week2_herbieGUI extends javax.swing.JFrame {
        /** Creates new form week2_herbieGUI */
        public week2_herbieGUI() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            loanfield = new javax.swing.JTextField();
            ratefield = new javax.swing.JTextField();
            years_duefield = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            PaymentLabel = new javax.swing.JLabel();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("PaymentCalculatorGUI");
            loanfield.setName("loanField"); // NOI18N
            ratefield.setText("jTextField2");
            ratefield.setName("rateField"); // NOI18N
            years_duefield.setName("years_dueField"); // NOI18N
            jLabel1.setText("Principle Loan");
            jLabel1.setName("Principle Loan"); // NOI18N
            jLabel2.setText("Interest Rate");
            jLabel2.setName("Interest Rate"); // NOI18N
            jLabel3.setText("Years of Mortgage");
            jLabel3.setName("Years of Mortgage"); // NOI18N
            jButton1.setText("Calculate");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            PaymentLabel.setText("Monthly Payment");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(31, 31, 31)
                            .addComponent(PaymentLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3))
                            .addGap(25, 25, 25)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(ratefield, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                                .addComponent(loanfield)
                                .addComponent(years_duefield, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap(180, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(loanfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(ratefield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(years_duefield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(PaymentLabel))
                    .addContainerGap(25, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
          //gather necessary variables from user
            double loan = Double.parseDouble(loanField.getText());
            double rate = Double.parseDouble(rateField.getText());
            double years_due = Double.parseDouble(years_dueField.getText());
          //Variables derived from user input
            double rate_total = rate/100; //Converts interest rate to decimal form
            double rate_monthly = rate_total/12; //converts to monthly interest rate
            double payment_year = years_due * 12; //Number of payments during course of mortgage.
            double payment = (loan * rate_monthly) / (1 - Math.pow(1 + rate_monthly, - payment_year)); //Calculates monthly payment
            PaymentLabel.setText("Your monthly payment is $" +payment);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new week2_herbieGUI().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JLabel PaymentLabel;
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextField loanfield;
        private javax.swing.JTextField ratefield;
        private javax.swing.JTextField years_duefield;
        // End of variables declaration
    }

    ThousandSon wrote:
    Here is what the computer says:
    Cannot find symbol
    symbol: variable loanField
    location: class week2_herbieGUI
    Cannot find Symbol
    Symbol: method getText()
    location: class loanField
    And it says the same thing for rateField and years_dueFieldThank you for finally posting the error message--it didn't hurt a bit did it. Had you posted it in the first place you would have had your answer 6 posts ago and probably a lot more planely.
    Please take special note of how this autocode has been generated and especially close attention to naming conventions:
        // Variables declaration - do not modify
        private javax.swing.JLabel PaymentLabel;
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextField loanfield;
        private javax.swing.JTextField ratefield;
        private javax.swing.JTextField years_duefield;
        // End of variables declarationThere in lay your problems, please look this block of code over very carefully and compare it to the errors you are getting and the code you have cut based on this autocode.
    Look very very closely. The same error exists in every one of your problems. If that doesn't do it for you, then you can look in the initComponents method and how each of these variables are referenced there. Do you see the difference? (Hint: it is the error.)
    BTW: does it show that I really despise when someone chooses to use autogenerated code and then asks how to correct errors from using it--and especially when they don't want to give the exact errors so we don't have to fish through all of the autocode to find out what is happening?

  • Initial values to instance & class variable

    I read in the book that instance & class variable definitions are given an initial value depending on the type of information they hold:
    Numeric variable - 0
    Characters - '\0'
    Boolean - false
    Objects - null
    But when I try to compile a class without giving explict value to the variable I get error.
    So why do I need this initial value - if it can't be used any way?

    Sorry� I'll try to make my question clearer.
    As I wrote in my previous message, I read in the book that instance & class variable definitions are given an initial value depending on the type of information they hold:
    Numeric variable - 0
    Characters - '\0'
    Boolean - false
    Objects - null
    From the above I understand that whenever I declare a variable without assigning it a value, it automatically has an initial value.
    For example:
    Class Myclass(){
    Int x;
    Static int z;
    Void fooMyClass(){
    Int y;
    I understand from what I read in the book, both x, y & z - get default values of zero. Is that correct?
    if it is correct, why can't I use these values that were assign as default?

  • Variable declaration in BEx - Business scenario's

    Hi,
        I need some documents about all kind of variable declaration with some example business scenarios in MM, FI-CO modules.
    will assign you a reasonable points
    Regards,
    Pooja.S

    Hi Pooja,
    The processing type of a variable may be varies from business requirement.
    In general we will use the processing type:
    Replacement Path : If you specify a variable as a characteristic value, you do not have to specify a text for the characteristic value right away. Instead, you can fill the text field dynamically and specifically for the characteristic that you use for the variable when you execute the query. To do this, define a text variable with automatic replacement.
    [http://help.sap.com/saphelp_nw70/helpdata/EN/bd/589b3c494d8e15e10000000a114084/content.htm]
    Authorisations: If the user belongs to Asia PAciffic region and he must see only details of his region then we can create a variable Region vt Processing type Authorisations so that he vl able to see only that region's data.
    [http://help.sap.com/saphelp_nw70/helpdata/EN/44/599b3c494d8e15e10000000a114084/content.htm]
    SAP EXIT: If you want to define a query that only ever displays the data from the current month, drag the delivered variable “current month” (technical name 0CMONTH) for the characteristic “calendar year/month” (technical name 0CMONTH) into the query filter.
    [http://help.sap.com/saphelp_nw70/helpdata/EN/f1/0a5702e09411d2acb90000e829fbfe/content.htm]
    Customer Exit: You want to use one characteristic value to calculate a second characteristic value. The InfoProvider only contains the calendar day. However, you now also want to display the cumulated value for the relevant period (beginning with the first day of a quarter) in a query.
    For the first day of the quarter, use a variable with customer exit processing. If you now enter the current calendar day (for example, 06/19/2000), a start date of 06/01/2000 appears in the customer exit, and the cumulated value of this period can be displayed.
    [http://help.sap.com/saphelp_nw70/helpdata/EN/f1/0a56f5e09411d2acb90000e829fbfe/content.htm]
    I hope this helps you.

  • Unbound Class Variable Error

    Hi All,
    I am doing a webdynpro application. while deploying, it gives me an error
    "Unbound class Variable:'KMC_LIBS/bc.srf.framework_api.jar'.
    What is this error?
    Regards,
    Divya

    Hi,
    A Classpath Variable is just a variable which points to a directory in your file system.
    Useful when 1st developer has external jars on path1 and 2nd developer has external jars on path2 (the two paths are different) and the developers want to prevent classpath issues.
    In NWDS go to:
    Window -> Preferences -> Java -> Classpath Variables and check if 'KMC_LIBS' points to a directory.
    Also, you can delete this entry from your project's classpath and add the file 'bc.srf.framework_api.jar'' manually (without classpath variable).
    Regards,
    Omri

Maybe you are looking for

  • IMac (late 2009) CPU runs very slow (about half speed)

    After having had troubles with performance I 've recently discovered, that Geekbench as well as Xbench return results way too low for my machine. In fact it appears results are exactly half the speed one would expect. In Xbench CPU power is about a s

  • Scheduling Agreement Output NEU

    Hello Friends, We have used the standard SAP output type NEU for SA( Scheduling Agreement ) output. And we are sending the output via email to vendor in PDF format. Now the issue is as per standard SAP whenever SA is generated SAP is sending the enti

  • How to restrict the creation of un wanted threads ?

    Hello Techies, I am using SunApplication Server 8.1. when I submit a request using Internet Explorer it is creating two threads for the same reaquest, due to this each task is executed twice by these threads. The strange thing is , Using Mozilla Fire

  • RecordNow version 7.32.1 build 08e update problem - Intrnal Error 03f2.8007007b

    Hello All!  Machine is T30 with WinXP Professional SP2 (RecordNow ver 4.10 preinstalled) There is RecordNow 7.32.1 update accessible from ThinkVantage System Update (listed as optional). When I try to install it I get Internal Error 03f2.8007007b fro

  • How do i change Maps on Mac desktop from km to miles

    is there a way to change the setting in the Maps application for my imac. directions are displayed in km. on my IOS evices it displays correctly but i cant find option to change it in maps. r/