Results 1 to 4 of 4
- 09-06-2010, 12:14 AM #1
Member
- Join Date
- Mar 2010
- Posts
- 49
- Rep Power
- 0
Please explain to me this basics in java !! array delaration
Java Code:public class Driver { int[] a; int lastItem; public static void main(String []args){ a[0] = 4; // THIS DOES NOT WORK ?? WHY ?? PLEASE EXPLAIN:confused:.... for(int s = 0 ; s < a.length; s++){ System.out.println(" "+a[s] );} } }Last edited by Eranga; 09-06-2010 at 05:33 AM. Reason: code tags added
-
Your problems are several-fold. For one, the variable a is declared:
but never initializedJava Code:int[] a;
For another, a has been declared as a non-static class field, but you're trying to access it from within a static method, and it simply doesn't exist by itself within a static method. It only exists in association with the context of a Driver object.Java Code:a = new int[5];
- 09-06-2010, 05:33 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
@OP, please use code tags when you are posting again.
- 09-06-2010, 05:39 AM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Go through the comments I've added in the following code.
If you are confusing with my comments let me know.Java Code:public class Driver { int[] a; // A variable is declared. [] stands for the declaration of an array. But not initialize. That means in an array you've to define how many items you want to store in advance, before use. int lastItem; public static void main(String []args){ a[0] = 4; // THIS DOES NOT WORK ?? WHY ?? PLEASE EXPLAIN:confused:.... // In above line you found an error because the first element, a[0] is the first element of an array(items are zero based indexing), could not found by your compiler. Because compiler dosen't know how many items there have actually, in simple word. for(int s = 0 ; s < a.length; s++){ System.out.println(" "+a[s] );} } }
Similar Threads
-
What loop? Java Networking Basics
By JonnySnip3r in forum NetworkingReplies: 0Last Post: 01-28-2010, 08:37 PM -
Explain how to troubleshoot simple java pg
By senthil in forum Advanced JavaReplies: 2Last Post: 09-01-2009, 01:28 PM -
Please explain Java
By MarkWilson in forum New To JavaReplies: 7Last Post: 07-02-2008, 08:38 AM -
Iam new in Java Please explain to me
By vinaytvijayan in forum AWT / SwingReplies: 1Last Post: 12-30-2007, 11:35 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks