Final attributes and local variables - performance ??

Hi all,
I and a colleague have done some performance testing regarding the use of final attributes and final local variables, e.g.
with final:
public class MyClass {
  private final int i;
  public final void myMethod() {
    final int j = 5;
    // do something with i and j
}vs. non-final:
public class MyClass {
  private int i;
  public final void myMethod() {
    int j = 5;
    // do something with i and j
}I couldn't find any speed differences in a small test program, but my colleague did so in his application. Who is right ??
Still, I will have do some formal testing next week and I will post the results.
I'd prefer the version using final anyway because I find it better readable, but the issue I am having is whether I'll spend 2-3 days going through the program making everything final or not.

I made some tests with final arguments to a method: I could not find any difference between final and non-final arguments. code is posted below
import java.io.*;
import java.net.*;
import java.rmi.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import junit.framework.*;
import junit.extensions.*;
public final class FinalVariablesTest extends TestCase /* from junit */ {
     * Constructors
    public FinalVariablesTest(String name) {
        super(name);
     * helper methods/classes
    protected void setUp() throws Exception {
        super.setUp();
    protected void tearDown() throws Exception {
        super.tearDown();
     * Test Suite
    public static void main(String[] args) {
     junit.textui.TestRunner.run(suite());
    public static Test suite() {
        return new TestSuite(FinalVariablesTest.class);
     * Test Cases
    /** tests the effect of passing an (final or non-final) int parameter
     to a method which uses the variable in a for loop.
     <p>
     Linux System:
     cat /proc/cpuinfo
     processor       : 0
     vendor_id       : GenuineIntel
     cpu family      : 6
     model           : 8
     model name      : Pentium III (Coppermine)
     stepping        : 1
     cpu MHz         : 501.146
     cache size      : 256 KB
     fdiv_bug        : no
     hlt_bug         : no
     sep_bug         : no
     f00f_bug        : no
     coma_bug        : no
     fpu             : yes
     fpu_exception   : yes
     cpuid level     : 2
     wp              : yes
     flags           : fpu vme de pse tsc msr pae mce cx8 sep mtrr pge mca cmov pat pse36 mmx fxsr xmm
     bogomips        : 999.42
     </pre>
     <p>
     Results:
     <pre>
     java version "1.4.0"
     Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
     Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
     final     non-final
     498     500
     491     494
     491     493
     491     494
     534     494
     492     494
     491     494
     492     493
     491     494
     495     494
     4966     4944 (Totals)
     </pre>
    public final void testIntParametersToForLoop() {
     final int RUNS = 10;
     final int INNER = 1000000;
     final int OUTER = 10;
     System.out.println("-----------------------");
     System.out.println("testIntParametersToForLoop");
     for(int i=0; i<RUNS; i++) {
         outerFinalIntParametersToForLoop(INNER, OUTER);
         outerNonFinalIntParametersToForLoop(INNER, OUTER);
    private final void outerFinalIntParametersToForLoop(final int INNER,
                                   final int OUTER) {
     // with final var in for loop
     long start0 = System.currentTimeMillis();
     for(int i=0; i<OUTER; i++) {
         innerFinalIntParametersToForLoop(INNER * i);
     long end0 = System.currentTimeMillis();
     System.out.println("      final:       " +
                  ( end0 - start0 ) + " milliseconds");
    private final void outerNonFinalIntParametersToForLoop(final int INNER,
                                      final int OUTER) {
     // with non-final var in for loop
     long start1 = System.currentTimeMillis();
     for(int i=0; i<OUTER; i++) {
         innerNonFinalIntParametersToForLoop(INNER * i);
     long end1 = System.currentTimeMillis();
     System.out.println("  non final: " +
                  ( end1 - start1 ) + "       milliseconds");
    private final void innerFinalIntParametersToForLoop(final int INNER) {
     for(int i=0; i<INNER; i++) {
         int testVar = i * INNER;
    private final void innerNonFinalIntParametersToForLoop(int loops) {
     for(int i=0; i<loops; i++) {
         int testVar = i * loops;

Similar Messages

  • How to change value of instance variable and local variable at run time?

    As we can change value at run time using debug mode of Eclipse. I want to do this by using a standalone prgram from where I can change the value of a variable at runtime.
    Suppose I have a class, say employee like -
    class employee {
    public String name;
    employee(String name){
    this.name = name;
    public int showSalary(){
    int salary = 10000;
    return salary;
    public String showName()
    return name;
    i want to change the value of instance variable "name" and local variable "salary" from a stand alone program?
    My standalone program will not use employee class; i mean not creating any instance or extending it. This is being used by any other calss in project.
    Can someone tell me how to change these value?
    Please help
    Regards,
    Sujeet Sharma

    This is the tutorial You should interest in. According to 'name' field of the class, it's value can be change with reflection. I'm not sure if local variable ('salary') can be changed - rather not.

  • Global and Local Variable

    Hi Gurus, I was unable to see where I can define local and global variables? I see that help.sap.com documentation but where do I create. All variables that I create, are global because, they are visible to all and they all can use it? Any help would be greatly appreciated.

    As far as I know, Variables are re-usable objects that are not dependent upon InfoProvider. When I look at this link
    http://help.sap.com/saphelp_nw04/helpdata/en/5c/8db07d555411d189660000e829fbbd/frameset.htm
    it talks about Global and Local variable? Is this different than what we use in Query Designer?

  • Default initialisation of member variables and local variables

    I don't understand why member variables are initialized with default values by Java.
    Objects are initialized with "null" and primitives with "0", except boolean, which is initialized with "false".
    If these variables are used locally they are not initialized. The compiler requires them to be initialized by the programer, for example "String s = null".
    Why? What is the use of that difference?
    And why are arrays always initialized with default values, no matter if they are member variables or local variables? For example String[] s = new String[10]; s[0] to s[9] are initialized with "null", no matter if "s" is a local or member variable.
    Can someone please explain that strange difference, why it is used? To me it has no sense.

    Most of the time I have to initialize a local variable
    with "String s = null" in order to use it because
    otherwise the compile would complain. This is a cheap
    little trick, but I think everyone uses it.
    I wouldn't agree with "most of the time". The only cases where it is almost necessary to do that is when the variable should be initialized in a loop or a try-catch statement, and that doesn't happen too often.
    If local variables were initiliazed automatically without a warning it would be a Bad Thing: the compiler could tell when there is a possibility that a variable hasn't been assigned to and prevent manymanymany NullPointerExceptions on run time.
    And you didn't answer me why this principle is not
    used with arrays if it is so useful as you think.
    Possibly it is much more difficult to analyse the situation in the case of arrays; what if values are assigned to the elements in an order that depends on run time properties such as values returned from a random number generator.
    The more special rules one has to remember, the more
    likely one makes errors.I agree, but what is the rule to remember in this case?

  • Debugging and Local Variable

    Hi All
    In MS visual studio i can select a local variable (Promise I will go and wash my mouth out now) and add it to a watch therefore i can see what the value of the variable as I go through the code line for line
    how can I view local variable in xcode ?
    Regards
    Tony

    To do something similar in Xcode, select the variable and either choose Run > Variables View > View Variables as Expression or choose Run > Variables View > View Variable in Window. Both options place the local variable in a separate window for you to view.
    There's not much difference between the two options if you're viewing one variable, but there is a difference if you're viewing multiple variables. If you view the variable as an expression, Xcode places all the variables you want to view in one Expressions window. If you view the variable in a window, Xcode creates a new window when you choose Run > Variables View > View Variable in Window.

  • Reading digital line and local variable

    I am using digital lines in my program to start and stop "Flat Sequence Structures"
    like time measurement ( 4 sequence, start and stop time with "Tick Count" )
    Is it good behaviour if i use once "Read from Digital Line.vi" and other starts and stops etc. with Local variables?
    Or can i just use "Read from Digital Line.vi" many times in my VI? (same line)

    Most experienced LV programmers try to avoid both sequence structures and local (and global) variables. The state machine architecture is often preferred. Look at the examples with LV and search for "State machine" on this site.
    I would probably use one read line or read port VI in a loop and pass the data to other, independent loops for processing (the timing) via queues.
    Lynn

  • Scope of globle and locale variable of a Package

    I have query about scope of variable declared in spec and body of a package. like
    create or replace package pk_test as
    v_var varchar2(50);
    procedure pk_p_test;
    end ;
    create or replace package body pk_test as
    v_var varchar2(50) := 'aaa';
    procedure pk_p_test
    is
    --v_var varchar2(50) := 'bbbb' ;
    begin
    null;
    --dbms_output.put_line(pk_p_test.v_var);
    dbms_output.put_line(pk_test.v_var);
    dbms_output.put_line(*v_var*);
    end;
    end;
    declare
    begin
    pk_test.v_var := 'qqqqq';
    --dbms_output.put_line(pk_test.v_var);
    pk_test.pk_p_test() ;
    end ;
    package is allowing to declare variable having same name in spec and body.
    But its not allowing to access. is it bug or .. can we access that variable using some methods

    Ah, I think I can see what you are saying.
    Yes, it can be declared in either place, or even declared in both places, but it shouldn't be declared in both.
    One is a "public" state variable and the other is a "private" state variable, so when it creates the package state, they are both marked differently within the state and therefore unique, hence it compiles.
    The public one can be accessed from outside the package, because it's clear to Oracle which is being referred to...
    SQL> create or replace package pk_test as
      2  v_var varchar2(50);
      3  procedure pk_p_test;
      4  end ;
      5  /
    Package created.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace package body pk_test as
      2    v_var varchar2(50) := 'aaa';
      3    procedure pk_p_test is
      4    begin
      5      null;
      6    end;
      7* end;
    SQL> /
    Package body created.
    SQL> exec pk_test.v_var := 'aaa';
    PL/SQL procedure successfully completed.
    SQL> set serverout on
    SQL> exec dbms_output.put_line(pk_test.v_var);
    aaa
    PL/SQL procedure successfully completed.However if you try and access the variable from inside the package, the body is able to reference both the public and private variables, so it doesn't know which one to use. Hence the compilation error previously seen.
    It's not a bug, because the packages are being flexible to allow for public and private variables, but what you are experiencing just indicates poor package design and lack of understanding of package state variables.

  • Marketing Attributes and Segment Builder performance

    Hello!
    Could you pls let me know
    1. Maximum number of Marketing attributes one can create at  - 
        CRMD_PROF_CHAR - Maintain Attributes
    2. What is the maximum number of BP's  that can be taken into segment builder
        for Target Group creation without Segment Builder performance suffering
    Thanks & Regards,
    Raju

    The solution for the problem is as follows,
    When you upgrade to JRE 1.6 version 19 patch 4, in the graphical modeler, the filter drag and drop doesnot work. In this case,    add the following line in you JAVA POLICY file.
        permission java.awt.AWTPermission "accessClipboard","read,write";
        you can find the POLICY file in the path:
           C:\Program Files\Java\<JAVA VERSION>\lib\security
    Please note that I found this in note 1359890

  • What's the difference between global variables and instance variables?

    hi im just a biginner,
    but what is the difference between these two?
    both i declare them above the constructor right.
    and both can access by any method in the class but my teacher said
    global variables are not permitted in java....
    but i don't know what that means....and i got started to confuse these two types,,
    im confusing.......
    and why my teacher said declaring global variables is not permitted,,,,,,
    why.....

    instance variables are kindof like Global variables. I'm not surprised you are confused.
    The difference is not in how they are declared, but rather in how they are used.
    There are two different "styles" of programming
    - procedural programming.
    - object oriented programming.
    Global variables are a term from Procedural programming.
    In this style of programming, you have only one class, and one "main" procedure. You only create one instance of the class, and then "run" it.
    There is one thread of control, which goes through various methods/procedures to accomplish your task.
    In this style of programming instance variables ARE "global" variables. They are accessible to all methods. There is only one instance of the class, and thus only one instance of the variables.
    Global variables are "bad" BECAUSE you can change them in any method you like. Even from places that shouldn't have to. Also if you use the same name as a global variable and a local variable, you can cause great trouble. This can lead to very subtle bugs, as the procedures interact in ways you don't expect.
    The preferred method in procedural programming is to pass the values as parameters to the methods, and only refer to the parameters, and local variables. This means that you can track exactly what your method is doing, and what it affects. It makes it simpler to understand. If you use global variables in your methods, it becomes harder to understand.
    So when are instance variables not global variables?
    When you are actually using the class as an Object, rather than just a program to run. If you are creating multiple instances of an object, all with different values for their instance variables, then they are not global variables. For instance you declare a Person object with an attribute "firstname". Your "main" program then creates many instances of the Person object, each with their own "firstname"
    I guess at the end of all this, it comes down to definitions.
    Certainly you can write procedural code in java. You can treat your instance variables, for all intents and purposes like global variables.
    I can only think to show a sort of example
    public class Test1
       User[] users;
       public void printUsers(){
         // loop through and print all the users
         // uses a global variable
          for(int i=0; i<users.length; i++){
            users.printUser();
    public void printUsers(User[] users){
    // preferred method - pass it the info it needs to do the job
    for(int i=0; i<users.length; i++){
    users[i].printUser();
    public Test1(){
    User u1 = new User("Tom", 20);
    User u2 = new User("Dick", 42);
    User u3 = new User("Harry", 69);
    users = new User[3];
    users[0] = u1;
    users[1] = u2;
    users[2] = u3;
    printUsers();
    printUsers(users);
    public static void main(String[] args)
    new Test1();
    class User{
    String firstName;
    int age;
    public User(String name, int age){
    this.firstName = name;
    this.age = age;
    public void printUser(){
    // here they are used as instance variables and not global variables
    System.out.println(firstName + " Age: " + age);
    Shit thats a lot of typing, and I'm not even sure I've explained it any good.
    Hope you can make some sense out of this drivel.
    Cheers,
    evnafets

  • Local variable's VariableElement not accessible through treepath

    Hi,
    I'm extending TreePathScanner visitor to localize and handle certain annotations associated with variables of any kind (field, parameters and local variables).
    To do so I overrode the visitVariable method that, as far I understand, should be able to obtain the corresponding javax.lang.model's VariableElement for any variable (whatever its kind) based on the current three path, see code bellow.
    It does work well with fields and parameter, however with local variables Trees.getElement simply returns a null. All the information is in fact in the code tree VariableTree node and I could retrieve what I needed from it but rather refrain from using com.sun. ... API if not really necessary and of course implement the processing twice.
    Perhaps the javax.lang.model.... object tree is not built for elements within a method body? or is this a bug? com.sun.source.util.Trees#getElement javadoc only says that a null is returned if the element is not "available".
    Thanks in advance.
    import javax.lang.model.element.VariableElement;
    import com.sun.source.util.TreePathScanner;
    import com.sun.source.util.Trees;
    import com.sun.source.tree.VariableTree;
    import com.sun.source.util.TreePath;
    public class MyVisitor extends TreePathScanner<Object,Trees> {
         @Override
         public Object visitVariable(VariableTree node, Trees trees) {
              TreePath path = getCurrentPath();
              VariableElement ve = (VariableElement) trees.getElement(path);
              if (ve != null) {
                            // The case for parameters and fields.
                            process(ve);
              else {  // Funnily getElement return null for local variables
                            process(node);
              return super.visitVariable(node, trees);
    }

    I had a similar problem where trees.getElement(TreePath) was returning null. In my case it had to do with the fact that symbol resolution wasn't done yet. I was trying to invoke my TreePathScanner after calling javacTask.parse() but I had to switch to after calling javacTask.analyze() otherwise trees.getElement(TreePath) always returned null. My issues was with a TreePath for a method though.

  • Performance with globle variable and local var.

    hi anyone
    i just have one performance question about the globle var and local. is having a globle var that is initialized with 'new' at one place better than having local var that is initialzed with 'new' in several places? for example, i have a access var that is initialzed with DB connection. should i have it as a globle var? or put it in the functions where it is needed, and initialize it with DB connection? in both cases, i need to use new operator.
    thanks in advance.

    First , don't use the term "global variable". It is misleading and not an official part of the Java nomenclature. I think the term used should be ( and correct me if I'm wrong ) instance variable. In C and C++ globale variables really are global - they can be accessed by any and all classes which include the header file.
    OK, having got that out of my system, back to the question. The value is gotten from a database, right? Whether you make it an instance variable or not depends on you design and whether the value in the database is likely to change during the lifetime of the instance.
    For example, if this class is a superclass of another, and the cild needs to know the value of the variable, it is often convenient to make it an instance variable so the subclass can access it directly.
    But if the value is likely to change, then you may want to have a getter method which returns the current value in the database.
    The latter will clearly have more overhead associated with it since you would need to get the value each time, but it is probably safer than having an instance variable.

  • No difference between using a local variable and a notifier in timed parallel loops?

    The example code "Pass Data With Notifiers.vi" that came with LV 7.1 illustrates using notifiers with parallel loops.  Just looking at two of the loops, the one that generates the sine wave and the one for "User 1", you can change the timing of the two loops and you can change the condition of the "Ignore Previous" status on the "Wait on Notification".  I have a special case of this to consider, where I'm wondering if there's any reason not to use a local variable instead of the notifier:
    Set the delay on the generator portion (which contains the Send Notification) to something very short, say 5 ms.  Set the delay on the User 1 (which contains the Wait on Notification) to something relatively longer, say 200 ms.  Set the Wait on Notification to False.  Now you have a situation where the User 1 loop action is contingent only upon the loop delay time, since each time the loop timer runs the loop there will always be a value in the notifier.  In this case it seems to behave just like the case where you update a local variable in the fast loop and read it in the slow one.
    Is my understanding correct?  Would there be a performance difference between the two methods?  What do you prefer in this situation and why?
    Thanks,
    Hosehead

    Hi H.,
    I think your idea is to write to a Global Variable in the data-producer VI, and read it in the data-consumer VI(?)
    One reason this might be less efficient than using Notifiers is if you want to graph every new value in the "consumer" - or make sure the value read in the consumer has changed at least once since the last loop.
    > since each time the [consumer] loop timer runs the loop there will always be a value in the notifier...
    > Would there be a performance difference between the two methods? 
    If you don't use the Notification "event" to synchronize the producer and consumer, then to be sure the consumer gets a new vaue, you've made the producer loop faster - every 5 ms - a waste of cpu-cycles.  More often the situation is reversed, that is, there's a consumer that needs to see every single new value, and (without events) the consumer must loop faster than the producer (to catch every new value) - this is called polling and it wastes cpu-cycles.
    Just about anytime one's tempted to make a loop execute "fast" to check on some value (or to make sure there's a fresh value,) there's an opportunity to improve performance through synchronization with events (including notifiers, queues, occurrances, semaphores, and rendezvous')
    tbd
    Message Edited by tbd on 07-09-2006 03:51 AM
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • How many ways to read and write a local variable in a called VI?

    Ciao!
    I'm producing my first TestStand sequence. It is called "FirstAttempt" and it is made by a single step which calls a VI. One of the first dilemmas i encountered realizing this sequence is how to read and write a local variable (created going in Variables -> Locals ('FirstAttempt') -> <right click to insert local>) in the called VI.
    The first way (the only one i tried) is to create a control and an indicator on the VI front panel, connect them to their respective terminals in the connector pane and then specify (going in Step Settings -> Module) that these connectors (shown in the Parameter Name column) are linked to the local variable (selected in the Value column).
    The second way (not tried) consists in using TestStand API: create a Sequence Context reference on the VI front panel, link it to a property node in the block diagram, select the property "Locals" and extract from this the local variable name and value which, i think, can be readable and writable.
    So...
    Are the shown ways correct?
    Are there other ways?
    Knowing that a "local" variable can be considered "global" within the whole sequence, is there the possibility to simply create a reference to the local variable and use the reference in the called VI block diagram in order to save space in the connector pane (if using method 1) or in the block diagram (if using method 2)?
    Thanks!
    Message Edited by aRCo on 09-17-2009 05:09 AM

    Hi,
    Before TestStand 3 you would use the second way you quoted as its the only way.
    But now you would use the first way you quoted. You may still what to pass the SequenceContext if you were going to use the TestStand API. For TestStand 3.x and above you would use this way as the first chose. (Personnelly, I would not pass the SequenceContext into a VI if I know it was never going to be used in that VI.)
    Not sure I understand your final comment, maybe you are liking it to passing the reference of a control to a subVI so that the control can be updated from within the subVI.
    If this is the case and you had a situation where you had a step that was running in parallel with the rest of the steps in the sequence either as a separate thread or execution and were dependent on the contents of the  local variable changing from that parallel running step, then you would have to use the API SetVal method to change the local.
    Hope this is clear.
    Regards
    Ray Farmer
    Regards
    Ray Farmer

  • Local variable needs to be declared final

    This is the error code I am getting:
    C:\javacode\Notepad>javac FinalProgram.java
    FinalProgram.java:60: local variable textfield1 is accessed from within inner class; needs to be declared final
    System.out.println("It is detected " + pressed +
    textfield1);
    ^
    1 error
    Here is my code:
    comments relevant to this topic are //ALL IN CAPS
    import java.awt.*; //declare packages needed
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.JMenuBar;
    public class FinalProgram extends JFrame
        implements ActionListener {
    static JFrame frame;
      public void actionPerformed (ActionEvent e) {
          String answer = (e.getActionCommand());
             if (answer == "Get Data") {
              JInternalFrame iFrame = new JInternalFrame("Get Data . ", false, true, false, false);
              iFrame.setLayout(new GridLayout(8,2));
              JLabel label1 = new JLabel("First Name");
              JLabel label2 = new JLabel("Last Name");
              JLabel label3 = new JLabel("Street");
              JLabel label4 = new JLabel("City");
              JLabel label5 = new JLabel("State");
              JLabel label6 = new JLabel("Zip");
              JLabel label7 = new JLabel("Phone");
              JLabel label8 = new JLabel("Click Button to Submit Form -->");
              JTextField textfield1 = new JTextField(10);
              JTextField textfield2 = new JTextField(10);
              JTextField textfield3 = new JTextField(10);
              JTextField textfield4 = new JTextField(10);
              JTextField textfield5 = new JTextField(10);
              JTextField textfield6 = new JTextField(10);
              JTextField textfield7 = new JTextField(10);
              JButton button1 = new JButton("Submit Data");
              //textfield1.addActionListener(this);
              textfield1.addActionListener(this);
              textfield2.addActionListener(this);
              textfield3.addActionListener(this);
              textfield4.addActionListener(this);
              textfield5.addActionListener(this);
              textfield6.addActionListener(this);
              textfield7.addActionListener(this);
              button1.addActionListener(new ActionListener() { //start button1.addActionListener
              public void actionPerformed(ActionEvent a) { //start button1 actionPerformed
                        String pressed = ((JButton) a.getSource()).getText();
                        System.out.println("button press is detected " + pressed + textfield1);  //THIS SYSTEM OUT PRINT IS A TEST, IT WORKS WHEN I DON'T HAVE THE "+ textfield1" PART, IT GIVES ME THE ERROR MESSAGE POSTED ABOVE ABOUT DECLARING IT FINAL.
    I'M A BEGINNER, MY GOAL HERE, IN EASY ENGLISH, IS TO GRAB THE DATA FROM EACH TEXTFIELD AND STORE THEM IN VARIABLES, OR MORE IDEALLY IN AN ARRAY SO THAT THE REST OF MY CODE BELOW CAN WRITE THEM TO FILE, I'VE BEEN TRYING THE PAST FEW DAYS ON THIS EXPERIMENTING AND ANY SUGGESTIONS WOULD BE APPRECIATED
              try {
                   String directoryName = "c:\\javacode\\Notepad";
                   String fileName = "program.txt";
                   File output = new File(directoryName,fileName);
                   output.createNewFile();
              if (! output.isFile()) {
                   System.out.println("File creation of" + output.getPath() + "failed");
            return;
              BufferedWriter out = new BufferedWriter(new FileWriter(output.getPath(), true));
              String[] text = {"This is the text that will be written. \r", //we pass an array, which holds the text to append to the file
                    "The text will be written to the file \r",
                    "in append mode. If the file does not \r",
                    "exist it will be created.\r"};  //WHAT YOU SEE HERE IS JUST A TEST, IN PLACE, I WOULD LIKE TO HAVE THE INFORMATION FOR MY TEXTFIELDS SO THAT I CAN PASS THEM THROUGH A FOR LOOP AS BELOW AND WRITE DATA FOR EACH OF THE TEXTFIELDS TO MY EXTERNAL TEXT FILE
                    for(int i = 0; i < text.length; i++) { //using the length of the text message we use out.Write() to write out the data.  Notice that all of the code is placed into a try-catch block so we can check for any IOExceptions that occur
           out.write(text[i] + "\n");
              //Here I create the code to grab the actions(grab the text) from the textFields and store them into variables OR into an array
              //after I have created my container to hold the information for my various textFields, then I want to create a for loop to go through each textField and write that information to a text file, separating each textField on its own line
         out.close();
         catch(IOException d) {
         System.out.println("Error writing to file " + d);
                   }  //end button1.addActionListener
              }  //end button1 actionPerformed
              );     //end actionListener statement     
              //textfield1.setSize(10, 10);
              iFrame.add(label1);
              iFrame.add(textfield1);
              iFrame.add(label2);
              iFrame.add(textfield2);
              iFrame.add(label3);
              iFrame.add(textfield3);
              iFrame.add(label4);
              iFrame.add(textfield4);
              iFrame.add(label5);
              iFrame.add(textfield5);
              iFrame.add(label6);
              iFrame.add(textfield6);
              iFrame.add(label7);
              iFrame.add(textfield7);
              iFrame.add(label8);
              iFrame.add(button1);
              iFrame.setSize(200, 500);
              iFrame.setVisible(true);
              add(iFrame);
              if (answer == "Display Data") {
              JInternalFrame iFrame = new JInternalFrame("Display Data . ", false, true, false, false);
              JTextArea text = new JTextArea();
              JScrollPane scroller = new JScrollPane();
              scroller.getViewport().add(text);
              iFrame.getContentPane().add(scroller);
              iFrame.setSize(200, 150);
              iFrame.setVisible(true);
              add(iFrame);
      public FinalProgram() {
        super ("Menu Example");
        JMenuBar jmb = new JMenuBar();
        JMenu file = new JMenu("Functions");
        JMenuItem item;
        file.add(item = new JMenuItem("Get Data"));
        item.addActionListener (this);
        file.add(item = new JMenuItem("Display Data"));
        item.addActionListener (this);
        jmb.add(file);
        addWindowListener(new ExitListener());    
         setJMenuBar (jmb);
        public static void main(String[] args) {
            FinalProgram window = new FinalProgram();
            window.setTitle("Final Program");
            window.setSize(600, 600);
            window.setVisible(true);
    }

    hi,
    Updated Code,
    import java.awt.*; //declare packages needed
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.JMenuBar;
    public class FinalProgram extends JFrame
        implements ActionListener {
    static JFrame frame;
              JLabel label1 = new JLabel("First Name");
              JLabel label2 = new JLabel("Last Name");
              JLabel label3 = new JLabel("Street");
              JLabel label4 = new JLabel("City");
              JLabel label5 = new JLabel("State");
              JLabel label6 = new JLabel("Zip");
              JLabel label7 = new JLabel("Phone");
              JLabel label8 = new JLabel("Click Button to Submit Form -->");
              JTextField textfield1 = new JTextField(10);
              JTextField textfield2 = new JTextField(10);
              JTextField textfield3 = new JTextField(10);
              JTextField textfield4 = new JTextField(10);
              JTextField textfield5 = new JTextField(10);
              JTextField textfield6 = new JTextField(10);
              JTextField textfield7 = new JTextField(10);
              JButton button1 = new JButton("Submit Data");
      public void actionPerformed (ActionEvent e) {
          String answer = (e.getActionCommand());
             if (answer == "Get Data") {
              JInternalFrame iFrame = new JInternalFrame("Get Data . ", false, true, false, false);
              iFrame.setLayout(new GridLayout(8,2));
              //textfield1.addActionListener(this);
              textfield1.addActionListener(this);
              textfield2.addActionListener(this);
              textfield3.addActionListener(this);
              textfield4.addActionListener(this);
              textfield5.addActionListener(this);
              textfield6.addActionListener(this);
              textfield7.addActionListener(this);
              button1.addActionListener(new ActionListener() { //start button1.addActionListener
              public void actionPerformed(ActionEvent a) { //start button1 actionPerformed
                        String pressed = ((JButton) a.getSource()).getText();
                        System.out.println("button press is detected " + pressed + textfield1.getText()); 
              try {
                   String directoryName = "c:\\javacode\\Notepad";
                   String fileName = "program.txt";
                   File output = new File(directoryName,fileName);
                   output.createNewFile();
              if (! output.isFile()) {
                   System.out.println("File creation of" + output.getPath() + "failed");
            return;
              BufferedWriter out = new BufferedWriter(new FileWriter(output.getPath(), true));
              String[] text = {"This is the text that will be written. \r", //we pass an array, which holds the text to append to the file
                    "The text will be written to the file \r",
                    "in append mode. If the file does not \r",
                    "exist it will be created.\r"};  //WHAT YOU SEE HERE IS JUST A TEST, IN PLACE, I WOULD LIKE TO HAVE THE INFORMATION FOR MY TEXTFIELDS SO THAT I CAN PASS THEM THROUGH A FOR LOOP AS BELOW AND WRITE DATA FOR EACH OF THE TEXTFIELDS TO MY EXTERNAL TEXT FILE
                    for(int i = 0; i < text.length; i++) { //using the length of the text message we use out.Write() to write out the data.  Notice that all of the code is placed into a try-catch block so we can check for any IOExceptions that occur
           out.write(text[i] + "\n");
              //Here I create the code to grab the actions(grab the text) from the textFields and store them into variables OR into an array
              //after I have created my container to hold the information for my various textFields, then I want to create a for loop to go through each textField and write that information to a text file, separating each textField on its own line
         out.close();
         catch(IOException d) {
         System.out.println("Error writing to file " + d);
                   }  //end button1.addActionListener
              }  //end button1 actionPerformed
              );     //end actionListener statement     
              //textfield1.setSize(10, 10);
              iFrame.add(label1);
              iFrame.add(textfield1);
              iFrame.add(label2);
              iFrame.add(textfield2);
              iFrame.add(label3);
              iFrame.add(textfield3);
              iFrame.add(label4);
              iFrame.add(textfield4);
              iFrame.add(label5);
              iFrame.add(textfield5);
              iFrame.add(label6);
              iFrame.add(textfield6);
              iFrame.add(label7);
              iFrame.add(textfield7);
              iFrame.add(label8);
              iFrame.add(button1);
              iFrame.setSize(200, 500);
              iFrame.setVisible(true);
              add(iFrame);
              if (answer == "Display Data") {
              JInternalFrame iFrame = new JInternalFrame("Display Data . ", false, true, false, false);
              JTextArea text = new JTextArea();
              JScrollPane scroller = new JScrollPane();
              scroller.getViewport().add(text);
              iFrame.getContentPane().add(scroller);
              iFrame.setSize(200, 150);
              iFrame.setVisible(true);
              add(iFrame);
      public FinalProgram() {
        super ("Menu Example");
        JMenuBar jmb = new JMenuBar();
        JMenu file = new JMenu("Functions");
        JMenuItem item;
        file.add(item = new JMenuItem("Get Data"));
        item.addActionListener (this);
        file.add(item = new JMenuItem("Display Data"));
        item.addActionListener (this);
        jmb.add(file);
        addWindowListener(new ExitListener());    
         setJMenuBar (jmb);
        public static void main(String[] args) {
            FinalProgram window = new FinalProgram();
            window.setTitle("Final Program");
            window.setSize(600, 600);
            window.setVisible(true);
    class ExitListener extends WindowAdapter {
      public void windowClosing(WindowEvent event) {
        System.exit(0);
    }

  • Custom class loader and local class accessing local variable

    I have written my own class loader to solve a specific problem. It
    seemed to work very well, but then I started noticing strange errors in
    the log output. Here is an example. Some of the names are in Norwegian,
    but they are not important to this discussion. JavaNotis.Oppstart is the
    name of my class loader class.
    java.lang.ClassFormatError: JavaNotis/SendMeldingDialog$1 (Illegal
    variable name " val$indeks")
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at JavaNotis.Oppstart.findClass(Oppstart.java:193)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
    at JavaNotis.SendMeldingDialog.init(SendMeldingDialog.java:78)
    at JavaNotis.SendMeldingDialog.<init>(SendMeldingDialog.java:54)
    at JavaNotis.Notistavle.sendMelding(Notistavle.java:542)
    at JavaNotis.Notistavle.access$900(Notistavle.java:59)
    at JavaNotis.Notistavle$27.actionPerformed(Notistavle.java:427)
    JavaNotis/SendMeldingDialog$1 is a local class in the method
    JavaNotis.SendMeldingDialog.init, and it's accessing a final local
    variable named indeks. The compiler automatically turns this into a
    variable in the inner class called val$indeks. But look at the error
    message, there is an extra space in front of the variable name.
    This error doesn't occur when I don't use my custom class loader and
    instead load the classes through the default class loader in the JVM.
    Here is my class loading code. Is there something wrong with it?
    Again some Norwegian words, but it should still be understandable I hope.
         protected Class findClass(String name) throws ClassNotFoundException
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         private byte[] loadClassData(String name) throws ClassNotFoundException
             ByteArrayOutputStream ut = null;
             InputStream inn = null;
             try
                 JarEntry klasse = arkiv.getJarEntry(name.replace('.', '/')
    + ".class");
                 if (klasse == null)
                    throw new ClassNotFoundException("Finner ikke klassen "
    + NOTISKLASSE);
                 inn = arkiv.getInputStream(klasse);
                 ut = new ByteArrayOutputStream(inn.available());
                 byte[] kode = new byte[4096];
                 int antall = inn.read(kode);
                 while (antall > 0)
                     ut.write(kode, 0, antall);
                     antall = inn.read(kode);
                 return ut.toByteArray();
             catch (IOException ioe)
                 throw new RuntimeException(ioe.getMessage());
             finally
                 try
                    if (inn != null)
                       inn.close();
                    if (ut != null)
                       ut.close();
                 catch (IOException ioe)
         }I hope somebody can help. :-)
    Regards,
    Knut St�re

    I'm not quite sure how Java handles local classes defined within a method, but from this example it seems as if the local class isn't loaded until it is actually needed, that is when the method is called, which seems like a good thing to me.
    The parent class is already loaded as you can see. It is the loading of the inner class that fails.
    But maybe there is something I've forgotten in my loading code? I know in the "early days" you had to do a lot more to load a class, but I think all that is taken care of by the superclass of my classloader now. All I have to do is provide the raw data of the class. Isn't it so?

Maybe you are looking for

  • How can I attach individual e-mail address lists to an e-mail and then send the lists to another person?

    I want someone else to be able to send group e-mails, using mail lists that I have created. What is the easiest way of e-mailing my mail lists to someone else? I do not see how individual mail lists can be made as an attachment to an e-mail.

  • FR Reports Migration issue

    Hi All, There is an issue while migrating some of the FR reports.I am migrating the reports from Dev environment to Test environment using normal export import option but to my surpsrise when I try to import some of the files it loses its database co

  • Exchange rate wronly taking

    Hi, i have maintained the eur rate from 01.01.2009. but while posting system is picking the rate which was maintained on 01.11.2008. Why system is not taking the current rate? can any one guide me on this. govind.

  • Letters on Keyboard wearing off

    I have an iBook G4 with a british keyboard. i've only had this machine for a matter of months and already the letters on a few of the keys are starting to wear off!! is there anywhere were i could cheaply order a few keys? in particular i need an "a"

  • Supervisor Approval Hierarchy in HRSSA

    Hi, I am using 'change Supervisor Process' using Manager Self Service in 11.5.10.2. The work flow is HRSSA. The default approval is for 5 levels. I need to have only one single level of approval hierarchy. Please advise how can i achieve the same. Th