w3resource

Java: Create and print Person objects

Java OOP: Exercise-1 with Solution

Write a Java program to create a class called "Person" with a name and age attribute. Create two instances of the "Person" class, set their attributes using the constructor, and print their name and age.

Sample Solution:

Java Code:

// Person.java
public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

The above class has two private attributes: name and age, and a constructor that initializes these attributes with the values passed as arguments. It also has a getter method to access the attributes.

// Main.java
public class Main {
  public static void main(String[] args) {
    Person person1 = new Person("Ean Craig", 11);
    Person person2 = new Person("Evan Ross", 12);
    System.out.println(person1.getName() + " is " + person1.getAge() + " years old.");
    System.out.println(person2.getName() + " is " + person2.getAge() + " years old.\n");
  }
}

In the above example, we create two instances of the "Person" class, set their attributes with the constructor, and print their name and age using the getter methods. We also modify the attributes using the setter methods and print the updated values.

Sample Output:

Ean Craig is 11 years old.
Evan Ross is 12 years old.

Set new age and name:
Ean Craig is now 14 years old.
Lewis Jordan is now 12 years old.

Flowchart:

Flowchart: Java  OOP Exercises: Create and print Person objects.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java OOP Previous: Java Object Oriented Programming Exercises Home.
Java OOP Next: Create and Modify Dog Objects.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.