0

I have a code

 class testArrayList
{
   ArrayList<String> auto = new ArrayList<String>();

   auto.add("MITSUBISHI");
   auto.add("Hyundae");
   auto.add("Ford");
   auto.add("Ferrari");
   auto.add("Mazda");
   auto.add("Mustang");
   auto.add("Lamborghini");

   for(String cars : auto)
   {
      System.out.println(cars);
   }
}

but when I compiled it, theres an error saying enter image description here

Im confused why it has an error saying IDENTIFIER EXPECTED or ILLEGAL START OF TYPE tho I already imported import java.util.ArrayList;

3 Answers 3

1

You have to change your code as below. You need to add array list inside to the main method.

public class testArrayList {

public static void main(String[] args) {

    ArrayList<String> auto = new ArrayList<String>();

    auto.add("MITSUBISHI");
    auto.add("Hyundae");
    auto.add("Ford");
    auto.add("Ferrari");
    auto.add("Mazda");
    auto.add("Mustang");
    auto.add("Lamborghini");

    for(String cars : auto)
    {
        System.out.println(cars);
    }
}

}
Sign up to request clarification or add additional context in comments.

2 Comments

why is that I need to put it in the main method sir?
Answer is with this question. please read. stackoverflow.com/questions/27553538/…
1

You can put logic ONLY inside methods. The main-method is the method that will be executed when u run the program. You can only put declarations and methods inside a class, thats why you get the runtime errors. I won't do a duplicate, just take Anuradha's solution.

Comments

0

auto is not a keyword and it’s fine in java. Change theSyntax of arrayList it to something

List<String> auto= new ArrayList<>();

6 Comments

Did you change that everywhere ?
but when I put it in main class the error gone why is that?
Try this List<String> autoList = new ArrayList<>() , This should work normally in main or any where .
why is that sir when I put it in main the error is gone? but if it is in another class there is an error?
Can you confirm the above syntax by putting in normal place where you tried?
|

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.