Showing posts with label Programming errors. Show all posts
Showing posts with label Programming errors. Show all posts

Wednesday, January 5, 2011

Java : Error Patterns in Programming - The Top errors List-1

1. Accessing non-static member variables from static methods (such as main)
This is a quite often committed mistake especially who are newly introduced to java.Your first few days with java can be a real mess with this error.
Take for example the following application, which will generate a compiler error message.

public class StaticDemo
{
        public String str1 = "teststr";
        public static void main (String args[])
        {
// Access a non-static member from static method
                System.out.println ("This generates a compiler error" + str1 );
        }
}
If you want to access its member variables from a non-static method (like main), you must create an instance of the object.
Here's a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.

public class Non-StaticDemo
{
        public String str1 = "tststr";


        public static void main (String args[])
        {
                NonStaticDemo nsd = new NonStaticDemo();


// Access member variable of demo
                System.out.println ("No error here" + nsd.my_member_variable );
        }
}

---------------------Please click on "more" below for the enitre list -------------------------

subversion video