Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am a newbie in Java programming and was just wondering if you can do this: I have a object class Person:

public class Person {

    public String name;
    public String[] friends;
}

If yes how to initialse it, i.e.

newPerson.name = "Max"; 
newPerson.friends = {"Tom", "Mike"};

I tried to do it like that, but it does not work.

share|improve this question
2  
You need to create an instance first. Person p = new Person(); – NeplatnyUdaj Jan 8 '14 at 20:42
2  
If you are a newbie, then start by studying Java tutorials. You can't expect to learn Java by asking 500 questions on SO. – Marko Topolnik Jan 8 '14 at 20:43
up vote 5 down vote accepted

try this

new Person("Max", new String[]{"Tom", "Mike"});

You would also need a constructor to initialize the variables.

public Person(String name, String[] friends){
    this.name = name;
    this.friends = friends;
}

As a good practice, you should also limit the access level of variables in your class to be private. (unless there is a very good reason to make them public.)

share|improve this answer
    
+1 for suggesting a constructor. You may want to mention that making fields public is not a good practice. – dasblinkenlight Jan 8 '14 at 20:46
    
why is not good practice? – maximilliano Jan 8 '14 at 21:01
    
have a look stackoverflow.com/questions/7622730/… – Ashish Jan 8 '14 at 21:06

try

newPerson.friends = new String[]{"Tom", "Mike"}

share|improve this answer

You can do it like this

public static class Person {
    public String name;      
    public String[] friends;
}
public static void main(String[] args) {
    Person newPerson = new Person();
    newPerson.name = "Max";
    newPerson.friends = new String[] {"Tom", "Mike"};
}
share|improve this answer

Thats actually pretty simple

U can initialize in creation (thats the easiest method):

public class Person {

      public String name = "Max";
      public String[] friends = {"Adam","Eve"};
 }

U could initialize variables in your constructor

public class Person {
      public String name;
      public String[] friends;
      public Person(){
          name =  "Max";
          friends = new String[] {"Adam", "Eve"};
      }
 }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.