Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

  • Re: Common Java Problems

    Problem description: Code outside of a method
    Problem category: Compile-time Problems

    Diagnosis Difficulty: Medium
    Difficulty to Fix: Easy-medium


    The two most common incarnations of this problem are not putting your code inside of the main method, or not putting initializing code inside of a static initializer block or constructor.

    Missing main method:
    public class Test
    {
        int a = 5;
        for(int i = 0; i < a; ++i)
        {
            System.out.println(i);
        }
    }

    Attempting to perform multi-statement initialization outside of a static initializer block/constructor.
    public class Test
    {
        public static int[] myArray;
        myArray = new int[5];
        for(int i = 0; i < myArray.length; ++i)
        {
            myArray[i] = i * i;
        }
    }

    Error Messages

    Unfortunately, this type of problem doesn't really have any indicative error message. You will probably get tens if not hundreds of error messages of other problems the Java compiler is finding because of this problem.

    Suggested fixes

    Missing main method: Add a main method
    public class Test
    {
        public static void main(String[] args)
        {
            int a = 5;
            for(int i = 0; i < a; ++i)
            {
                System.out.println(i);
            }
        }
    }

    Attempting to perform multi-statement initialization outside of a static initializer block/constructor: add a static initializer block (or a constructor, depending on if you want to initialize static or instance variables).
    public class Test
    {
        public static int[] myArray;
        static
        {
            myArray = new int[5];
            for(int i = 0; i < myArray.length; ++i)
            {
                myArray[i] = i * i;
            }
        }
    }
    This article was originally published in forum thread: Common Java Mistakes started by helloworld922 View original post