Alan
Alan

Reputation: 589

No output when checking an element in an ArrayList in Java

I have declared a string ArrayList in Java, now when I fill the entire list and I check if one element is inside with the ArrayList.contains(value) method and I want to print if it exists or not I get no output. I am wondering why as the list.contains("Red") method should return TRUE.

Code snippet:

import java.util.ArrayList;

public MyClass{
    public static void main(){

    ArrayList<String> list = new ArrayList<String>(10);

    list.add("Green");
    list.add("Orange");
    list.add("Red");
    list.add("Black");
    list.add("White");

    boolean test = list.contains("Red");

    if(test)
        System.out.println("True");

    else
        System.out.println("False");
    }
}

Upvotes: 1

Views: 91

Answers (2)

Anisuzzaman Babla
Anisuzzaman Babla

Reputation: 7480

Everything is OK in your code. But argument is missing. As JVM starts executing the java program it searches for the main method having this signature(i.e String array).

So your Main Method should be like

public static void main(String[] args)

And class modifier also missing in your class.

Use public class MyClass instead of public MyClass

Upvotes: 3

VelNaga
VelNaga

Reputation: 3953

Use the below code, It works in my local, There are a couple of things missing in your code, Class modifier is missing and there is not "String[] args".Also, I did a bit of refactoring of your code. Hope this helps for you

package com.sample.service;

import java.util.ArrayList;
import java.util.List;

public class MyClass {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("Green");
        list.add("Orange");
        list.add("Red");
        list.add("Black");
        list.add("White");

        boolean test = list.contains("Red");
        System.out.println(test);

    }
}

Upvotes: 1

Related Questions