Ads

Monday, December 28, 2020

Java Programming: Creating a Student Class with Name and Roll Number

Here's the program to solve the problem as described:

Learn how to create a Student Object in Java.

Source Code:


public class Student {

    String name;

    int roll_no;

   

    public static void main(String[] args) {

        Student student = new Student();

        student.name = "Ahmed";

        student.roll_no = 101;

       

        System.out.println("Name: " + student.name);

        System.out.println("Roll No: " + student.roll_no);

    }

}

 

In this program, we define a class named Student with two instance variables, name of type String and roll_no of type int

 

public class Student {

    String name;

    int roll_no;

   

    // methods will be defined here...

}

 

We then define the main method, which is the entry point of our program.

Inside the main method, we create an instance of the Student class named student.

Student student = new Student();                         

 

We then assign the values "Ahmed" and 101 to the name and roll_no instance variables of the student object, respectively.

student.name = "Ahmed";

student.roll_no = 101;

Finally, we print the values of name and roll_no to the console using System.out.println.

System.out.println("Name: " + student.name);

System.out.println("Roll No: " + student.roll_no);

 

When we run this program, it will print the following output:

 

Name: Ahmed

Roll No: 101

 

So, the program creates an object of the Student class, sets its name and roll_no instance variables, and then prints their values to the console

 

Some additional information

In this program, we are creating an instance of the Student class and assigning values to its name and roll_no instance variables. This is an example of object-oriented programming (OOP) in Java.


OOP is a programming paradigm that focuses on creating objects that have properties and methods. An object is an instance of a class, and a class is a blueprint that defines the properties and methods of an object.

 

In this program, the Student class is the blueprint, and the student object is an instance of that class. We can create multiple instances of the Student class with different values for the name and roll_no instance variables.

 

By using OOP concepts, we can write more organized and modular code, making it easier to maintain and reuse.


No comments:

Post a Comment