Java Program to read information about a student from the user and display the same with the use of classes and objects
This program demonstrates the capturing of Student information like Name. USN and age from the user and display these on console.
Program
import java.util.*;
class Student {
private String name;
private int usn;
private int age;
public void getInfo() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter student details");
System.out.print("Name:\t");
name = sc.next();
System.out.print("USN:\t");
usn = sc.nextInt();
System.out.print("Age:\t");
age = sc.nextInt();
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("USN: " + usn);
System.out.println("Age: " + age);
}
}
public class StudentInfo {
public static void main(String[] args) {
Student std = new Student();
std.getInfo();
System.out.println("The details of entered student are:");
std.displayInfo();
}
}
Let us understand the program by breaking into simple parts:
In this example we have two class Student
and StudentInfo
. Student class has Name, USN and Age. Here Name is of type String, USN and Age is of primitive int. The variables has the access specifiers private which means name, usn and age can be accessed only within the class Student
. There are two methods getInfo() and displayInfo() inside the Student class, according to terminology used we would call these methods as member functions.
getInfo() method uses Scanner class and accepts the user inputs for Name, USN and Age and stored in variables name, usn and age respectively. displayInfo() method displays the value stored in variables name, usn and age.
In the main method we create the instance of Student class using Student std = new Student();
, using the object std we will invoke the member functions of Student class using std.getInfo();
and std.displayInfo();
.
Output
Enter student details
Name: Ram
USN: 1234
Age: 19
The details of entered student are:
Name: Ram
USN: 1234
Age: 19