shubham4522
shubham4522

Reputation: 1

new to java : getting unexpected output

i have created 2 java files.
1. helloWorld.java 2. inside the folder p/node.java

helloWorld.java folder contains the main function

import p.node;  
import java.util.ArrayList;  
import java.util.List;  
public class helloWorld {
    public static void main(String[] args) {
        List<node> list = new ArrayList<node>(); //created list of object node
        list.add(new node('a'));
        list.add(new node('b'));
        list.add(new node('c'));
        list.add(new node('g'));
        list.add(new node('k'));
        list.add(new node('o'));

        System.out.println(list.get(2).val);
    }
}

2.node.java

package p;
public class node {
    public static char val;

    public boolean busy = true;


    public  node(char val)
   {
       this.val=val;
   }
}

Expected Output c
Actual output o
please help me , i'm new to java ... Thanks in advance!!

Upvotes: 0

Views: 60

Answers (2)

Andree Kr&#246;ger
Andree Kr&#246;ger

Reputation: 104

remove the word static in line 3 in the class node, then should it work.

Best regards Andree

Upvotes: 0

Chirag
Chirag

Reputation: 565

you have declared val as static and static members are created only once

remove static declaration from node class

package p;
public class node {
    public char val;
    public boolean busy = true;

    public  node(char val) {
       this.val=val;
   }
}

Upvotes: 3

Related Questions