Write a java program to create a class Student with data name, city and age along with method addData and printData to input and display the data. Create the two objects s1, s2 to declare and access the values.
CODE:
import java.util.Scanner;
class Student {
private String name;
private String city;
private int age;
// Method to input data
public void addData(String name, String city, int age) {
this.name = name;
this.city = city;
this.age = age;
}
// Method to display data
public void printData() {
System.out.println("Name: " + name);
System.out.println("City: " + city);
System.out.println("Age: " + age);
}
}
public class StudentTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Creating objects of Student class
Student s1 = new Student();
Student s2 = new Student();
// Input data for student 1
System.out.println("Enter details for student 1:");
System.out.print("Name: ");
String name1 = scanner.nextLine();
System.out.print("City: ");
String city1 = scanner.nextLine();
System.out.print("Age: ");
int age1 = scanner.nextInt();
scanner.nextLine(); // Consume newline character
// Input data for student 2
System.out.println("\nEnter details for student 2:");
System.out.print("Name: ");
String name2 = scanner.nextLine();
System.out.print("City: ");
String city2 = scanner.nextLine();
System.out.print("Age: ");
int age2 = scanner.nextInt();
scanner.nextLine(); // Consume newline character
// Adding data to objects
s1.addData(name1, city1, age1);
s2.addData(name2, city2, age2);
// Printing data of both students
System.out.println("\nDetails of student 1:");
s1.printData();
System.out.println("\nDetails of student 2:");
s2.printData();
scanner.close();
}
}
- Define a class
Studentwith private instance variablesname,city, andage. - Define a method
addData()in theStudentclass that takesname,city, andageas arguments and sets the instance variables accordingly. - Define a method
printData()in theStudentclass that prints thename,city, andageof the student. - Define a class
StudentTest. - Inside the
StudentTestclass:- Create a
Scannerobject to read input from the user. - Create two objects
s1ands2of theStudentclass. - Prompt the user to enter details for the first student (
name,city, andage). - Read the details entered by the user for the first student and set the data using the
addDatamethod ofs1. - Prompt the user to enter details for the second student (
name,city, andage). - Read the details entered by the user for the second student and set the data using the
addDatamethod ofs2. - Print the details of both students using the
printDatamethod.
- Create a
- Close the
Scannerobject. - End of the program.




