4 Replies Latest reply: May 2, 2011 2:43 AM by 802316 RSS

    Assign a value to a final variable

    848755
      http://en.wikipedia.org/wiki/Final_(Java)

      According to the above link, I can assign a value to a final variable in the constructor once. The value in my program comes from a text file. The compiler gave me an error saying

      "variable processTime might not have been initialized"

      The code is the following and the text file has 5 in it. My goal is to assign the prosseingTime to be 5. If you need to try it, just put 5 in a file and use the file name as command-line argument. I do not want to use 5 in the code because it will be changed in the file.
      import java.io.*;
      import java.util.*;
      
      public class Test
      {
           public String fName;
           public final int processTime;
          public Test(String f)
          {
           int l = 0;
           try
              {
                   File myFile= new File(f);
                   FileInputStream fileStream = new FileInputStream(myFile);
                   DataInputStream in = new DataInputStream(fileStream);
                   BufferedReader br = new BufferedReader(new InputStreamReader(in));
                   String strLine;
                   strLine = br.readLine();
                   System.out.println(strLine);
                   System.out.println();
                   strLine = br.readLine();
                   Scanner scanner = new Scanner(strLine);
                   l = scanner.nextInt();
                   processTime = l;
              }
              catch (Exception e)
              {
                 System.err.println("Error: " + e.getMessage());
              }
          }
        public static void main(String[] args)
        {
             String sFile= args[0];
             Test test = new Test(sFile);
        }
      }
      Is there a way to fix it?

      Thank you very much.

      Edited by: EJP on 2/05/2011 14:13: fixed your code tags. They have changed since the forum migration, please check.
        • 1. Re: Assign a value to a final variable
          EJP
          http://en.wikipedia.org/wiki/Final_(Java)

          According to the above link
          The above link has no status in this discussion. You should be referring to, and learning from, the Java Language Specification.
          I can assign a value to a final variable in the constructor once.
          The language specification says here that a value must be definitely assigned by the end of each constructor. And that's a good example of why you shouldn't rely on statements from third parties. For another reason have another look at the page: it no longer says what you cited. [I fixed it.]
          The compiler gave me an error saying

          "variable processTime might not have been initialized"
          Because if the exception occurs the variable isn't initialized.
          • 2. Re: Assign a value to a final variable
            Darryl Burke
            Cross posted
            http://www.java-forums.org/new-java/43365-assign-value-final-variable.html

            db
            • 3. Re: Assign a value to a final variable
              YoungWinston
              user5434016 wrote:
              Is there a way to fix it?
              Yes. Add an assignment in your 'catch' block (-1?). Alternatively, it might be better to use a local variable, and then assign that to your class field immediately before exiting the constructor.

              BTW - 'l' is a really bad name for a variable. Far to easy to mistake it with either '1' or capital 'I'.

              Winston
              • 4. Re: Assign a value to a final variable
                802316
                My suggestions are

                - only catch an exception unless you are going to add some value by handling it. For example, catching an exception and leaving yourself with an incomplete/corrupt object is not adding value.

                - only read/write a file as either binary (like DataInputStream) OR text (like BufferedReader)

                - always try to close files/sockets after you have finished with them

                - try not to place complex code in constructors, in this case it would be better to use a factory method/builder class (but I fear I have confused you enough already.
                public class Test {
                    public final int processTime;
                
                    public Test(String f) throws IOException {
                        BufferedReader br = null;
                        try {
                            br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(f))));
                            System.out.println(br.readLine());
                            System.out.println();
                            Scanner scanner = new Scanner(br.readLine());
                            processTime = scanner.nextInt();
                        } finally {
                            close(br);
                        }
                    }
                    
                    public static void close(Closeable closeable) {
                        if (closeable != null)
                            try {
                                closeable.close();
                            } catch (IOException ignored) {
                            }
                    }
                
                    public static void main(String... args) throws IOException {
                        String sFile = args[0];
                        Test test = new Test(sFile);
                    }
                }