0

I am new to java and trying to learn array in java, so when i executed this

class Example
{
    int [] i= new int[2];
    i[0]=5;    //error in this line. Trying to assign 5 to 1st position of array i.

    void m1()
    {
        System.out.println("i[0]:"+i);
    }

    public static void main(String args[])
    {
        Example a=new Example();
        a.m1();
    }
}

it gives error as ']' expected on line number 4 here.

I know within function it will work only want to know why not like this and is there any solution and if not what is the reason?

Sorry, didn't copy but wrote the program incorrectly...Now its the correct one.

2 Answers 2

3
int[0] = 5;

Is wrong. You should use

i[0] = 5;

But you can't make assignment like this in the class body. You have to move that declaration inside a method, or do something like this in the array declaration:

int[] i= {5};//same as int[] i = new int[1]; i[0] = 5;
Sign up to request clarification or add additional context in comments.

5 Comments

Also he's later trying to access i[1] which will be out of bounds and will cause the program to crash.
@Kon No, he isn't. He is printing "i[1]", he is not accessing it
@PrathameshDeshmukh My answer is still valid. You can't make assignments in the class body
Why not? If integer variables can be assigned in similar ways why not array?
@PrathameshDeshmukh Integer cannot be assigned in the body class. You can assign a value to a variable only if you do it while you declare it. int a = 5 will be permitted, int a; a = 5; will not. Also, int[]a = {5}; will be permitted, int[]a = new int[1]; a[0] = 5; won't.
2

This line is incorrect:

int[0] = 5;

You meant this (notice the block, and the correct name of the array):

{
    i[0] = 5;
}

Or you could declare an initialize the array in a single line:

int[] i = {5};

Also notice that as a convention, the [] part is usually written after the type of the array, not after the name of the array (that's a C convention, not a Java convention).

2 Comments

Can't do i[0]=5; in class body.
@SotiriosDelimanolis Indeed, you can't put code at the class level unless it's in a block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.