Bird
0
0

You want to create a class Student that stores a student's name and age, and has a method to print these details. Which code snippet correctly implements this?

hard📝 Application Q8 of 15
Java - Object-Oriented Programming Concepts
You want to create a class Student that stores a student's name and age, and has a method to print these details. Which code snippet correctly implements this?
Aclass Student { String name; int age; void printDetails() { System.out.println(name + ", " + age); } }
Bclass Student { String name, age; void printDetails() { System.out.println(name + ", " + age); } }
Cclass Student { String name; int age; void printDetails() { System.out.println(name + age); } }
Dclass Student { String name; int age; void printDetails() { System.out.println(name + " " + age + " years"); } }
Step-by-Step Solution
Solution:
  1. Step 1: Check field types

    Name should be a String, age an int. Options A, C, and D have correct types; B incorrectly declares age as String.
  2. Step 2: Check printDetails method

    class Student { String name; int age; void printDetails() { System.out.println(name + " " + age + " years"); } } prints name and age with spaces and "years" for clarity, which is a good practice.
  3. Final Answer:

    Option D correctly stores and prints student details -> Option D
  4. Quick Check:

    Correct fields and clear print format = class Student { String name; int age; void printDetails() { System.out.println(name + " " + age + " years"); } } [OK]
Quick Trick: Use correct types and clear print formatting [OK]
Common Mistakes:
  • Using wrong data types
  • Concatenating without spaces or labels

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes