
Design a class with the following specifications: Class name: Student Member variables: name - name of student age - age of student mks - marks obtained stream - stream allocated (Declare the variables using appropriate data types) Member methods: void accept() - Accept name, age and marks using methods of Scanner class. void allocation() - Allocate the stream as per the following criteria: mks stream >= 300 Science and Computer >= 200 and < 300 Commerce and Computer >= 75 and < 200 Arts and Animation < 75 Try Again void print() - Display Student name, age, mks and stream allocated. Call all the above methods in main method using an object.
Topic: Class definition with grade allocation
Answer
import java.util.Scanner;
class Student { String name, stream; int age, mks;
void accept() { Scanner sc = new Scanner(System.in); System.out.print("Enter name of the student : "); name = sc.nextLine(); System.out.print("Enter age of the student : "); age = sc.nextInt(); System.out.print("Enter marks obtained : "); mks = sc.nextInt(); }
void allocation() { if(mks >= 300) stream = "Science and Computer"; else if(mks >= 200) stream = "Commerce and Computer"; else if(mks >= 75) stream = "Arts and Animation"; else stream = "Try Again"; }
void print() { System.out.println("Name : " + name); System.out.println("Age : " + age); System.out.println("Marks : " + mks); System.out.println("Stream : " + stream); }
public static void main(String args[]) { Student ob = new Student(); ob.accept(); ob.allocation(); ob.print(); } }
A range-checking class question. The key skill is ordering the conditions so that no range is tested twice.
Work from the HIGHEST range downwards. Because else-if stops at the first true test, reaching the second branch already guarantees that mks is below 300, so you can simply write mks >= 200 rather than (mks >= 200 && mks < 300). Writing the full double condition is not wrong, but it is longer and easier to get wrong.
"Appropriate data types" is part of the marks: name and stream are text, so String; age and mks are whole numbers, so int. Declaring mks as a double would be poor choice here.
Note the structure the question dictates — accept(), allocation() and print() are separate methods, each doing one job, all invoked in turn from main() through a single object. Doing everything inside main() loses marks even if the output is right.
Check with 250 marks: it fails the first test, passes mks >= 200, and is allocated Commerce and Computer.
name String - name of the student age int - age of the student mks int - marks obtained by the student stream String - stream allocated according to the marks sc Scanner - object used to read input ob Student - object of the class used in main()