0% found this document useful (0 votes)
40 views8 pages

Java Constructors and Class Examples

Uploaded by

nkumbhare566
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views8 pages

Java Constructors and Class Examples

Uploaded by

nkumbhare566
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1. A) Define Constructor and it's types with examples of each.

(7
Marks)
Answer:
A constructor in Java is a special method that is used to initialize objects. It is called
automatically when an object of a class is created. The constructor has the same name as its
class and does not have a return type, not even void. Its primary job is to set initial values for
the object's instance variables.
Types of Constructors:
There are three main types of constructors in Java:
1. Default Constructor: If a class does not have any constructor defined by the programmer,
the Java compiler provides a default constructor on its behalf. This constructor has no
parameters and an empty body. It initializes instance variables with their default values (e.g., 0
for numbers, null for objects, false for booleans).
Example:
// In this class, the compiler will add a default constructor: public
MyClass() {}​
class MyClass {​
int number;​
String text;​

void display() {​
[Link]("Number: " + number); // Will print 0​
[Link]("Text: " + text); // Will print null​
}​
}​

public class DefaultConstructorDemo {​
public static void main(String[] args) {​
MyClass obj = new MyClass(); // Default constructor is called
here​
[Link]();​
}​
}​

2. No-Argument Constructor: This is a constructor that is explicitly defined by the programmer


but does not accept any parameters. It allows you to write custom initialization logic that should
run for every object, without needing any specific input.
Example:
class Car {​
String model;​

// No-Argument Constructor​
Car() {​
model = "Unknown"; // Custom initialization​
[Link]("A new car object is created!");​
}​
}​

public class NoArgConstructorDemo {​
public static void main(String[] args) {​
Car myCar = new Car(); // Our no-argument constructor is
called​
[Link]("Model: " + [Link]);​
}​
}​

3. Parameterized Constructor: This constructor accepts one or more parameters. It is used to


initialize each object with different, specific data provided as arguments during object creation.
This is the most common type of constructor.
Example:
class Book {​
String title;​
String author;​
int year;​

// Parameterized Constructor​
Book(String t, String a, int y) {​
title = t;​
author = a;​
year = y;​
}​

void displayInfo() {​
[Link]("Title: " + title + ", Author: " + author +
", Year: " + year);​
}​
}​

public class ParameterizedConstructorDemo {​
public static void main(String[] args) {​
// Passing specific values to the constructor​
Book book1 = new Book("The Hobbit", "J.R.R. Tolkien", 1937);​
Book book2 = new Book("1984", "George Orwell", 1949);​

[Link]();​
[Link]();​
}​
}​
Q1. B) Create a class Student with data members name, age, and
marks. Create objects of this class and display their details using a
method. (3 Marks)
Answer:
Here is the complete, runnable Java program for the Student class.
// Save as [Link]​
class Student {​
// Data members​
String name;​
int age;​
double marks;​

// Method to set the details of the student​
public void setDetails(String name, int age, double marks) {​
[Link] = name;​
[Link] = age;​
[Link] = marks;​
}​

// Method to display student details​
public void displayDetails() {​
[Link]("--- Student Details ---");​
[Link]("Name: " + name);​
[Link]("Age: " + age);​
[Link]("Marks: " + marks);​
[Link]("-----------------------");​
}​
}​

public class StudentDemo {​
public static void main(String[] args) {​
// Create the first Student object​
Student student1 = new Student();​
[Link]("Alice", 20, 85.5);​

// Create the second Student object​
Student student2 = new Student();​
[Link]("Bob", 21, 91.0);​

// Display details for both students​
[Link]("Details of the first student:");​
[Link]();​

[Link]("\nDetails of the second student:");​
[Link]();​
}​
}​

OR

Q1. C) Build a class Employee that has private fields id, name, and
salary. Use getter and setter methods to access and modify them. (3
Marks)
Answer:
This program demonstrates encapsulation by making the class fields private and providing
public getter and setter methods to access them.
// Save as [Link]​
class Employee {​
// Private data members to enforce encapsulation​
private int id;​
private String name;​
private double salary;​

// Public setter method for id​
public void setId(int id) {​
[Link] = id;​
}​

// Public getter method for id​
public int getId() {​
return id;​
}​

// Public setter method for name​
public void setName(String name) {​
[Link] = name;​
}​

// Public getter method for name​
public String getName() {​
return name;​
}​

// Public setter method for salary​
public void setSalary(double salary) {​
// We can add validation logic here​
if (salary > 0) {​
[Link] = salary;​
} else {​
[Link]("Invalid salary amount. Salary not
updated.");​
}​
}​

// Public getter method for salary​
public double getSalary() {​
return salary;​
}​
}​

public class EmployeeDemo {​
public static void main(String[] args) {​
Employee emp = new Employee();​

// Use setter methods to modify private data​
[Link](101);​
[Link]("John Doe");​
[Link](75000.00);​

// Use getter methods to access private data​
[Link]("--- Employee Details ---");​
[Link]("Employee ID: " + [Link]());​
[Link]("Employee Name: " + [Link]());​
[Link]("Employee Salary: $" + [Link]());​
[Link]("------------------------");​
}​
}​

Q2. A) Define the definitions of classes and objects and differentiate


between Object oriented programming and procedure oriented
programming. (7 Marks)
Answer:
Class: A class is a blueprint or a template for creating objects. It is a user-defined data type that
bundles data (variables) and methods (functions) that operate on that data into a single unit. A
class does not occupy any memory space itself until an object (instance) of it is created.
Object: An object is an instance of a class. When a class is defined, no memory is allocated,
but when an object is created, memory is allocated. An object has a state (defined by its
variables) and behavior (defined by its methods). It is a real-world entity. For example, if "Car" is
a class, then a specific Toyota Camry is an object of that class.
Difference between Object-Oriented and Procedure-Oriented Programming:
Feature Object-Oriented Programming Procedure-Oriented
(OOP) Programming (POP)
Approach Bottom-up approach. Focuses Top-down approach. Focuses
on building objects first. on breaking down a task into
functions.
Core Unit The core unit is an object, The core unit is a function or
Feature Object-Oriented Programming Procedure-Oriented
(OOP) Programming (POP)
which bundles data and procedure.
methods.
Data Focus Data is the critical element. Focus is on procedures and
Data and its operations are tied algorithms. Data and functions
together. are separate.
Data Hiding Provides strong data hiding Data is generally exposed and
through access modifiers can be accessed by any
(private, public). function.
Inheritance Supports inheritance, allowing Does not support inheritance.
a new class to inherit properties
from an existing class.
Overloading Supports function and operator Does not support overloading.
overloading.
Real World Better suited for modeling Less suitable for modeling
complex, real-world problems. complex real-world scenarios.
Example Java, C++, Python, C# C, Pascal, FORTRAN
Q2. B) Write a program that accepts a string from user and check if it
is palindrome or not. (3 Marks)
Answer:
A palindrome is a word or phrase that reads the same forwards and backward (e.g., "madam",
"level", "racecar"). This program takes user input and checks if it's a palindrome.
// Save as [Link]​
import [Link];​

public class PalindromeChecker {​
public static void main(String[] args) {​
Scanner scanner = new Scanner([Link]);​

[Link]("Enter a string to check if it's a
palindrome: ");​
String originalString = [Link]();​

// A simple and efficient way to reverse a string​
String reversedString = new
StringBuilder(originalString).reverse().toString();​

// Compare the original and reversed strings, ignoring case
for a robust check​
if ([Link](reversedString)) {​
[Link]("The string \"" + originalString + "\"
is a palindrome.");​
} else {​
[Link]("The string \"" + originalString + "\"
is not a palindrome.");​
}​

[Link]();​
}​
}​

OR

Q2. C) Write a program that finds the largest and smallest element
from an array. (3 Marks)
Answer:
This program initializes an array of integers and then iterates through it to find the minimum and
maximum values.
// Save as [Link]​
public class ArrayMinMax {​
public static void main(String[] args) {​
// Initialize an integer array​
int[] numbers = {45, 23, 89, 12, 99, 4, 67, 55};​

// Handle case for an empty array​
if (numbers == null || [Link] == 0) {​
[Link]("The array is empty. Cannot find min
and max.");​
return;​
}​

// Assume the first element is both the smallest and largest
initially​
int smallest = numbers[0];​
int largest = numbers[0];​

// Iterate through the array starting from the second element​
for (int i = 1; i < [Link]; i++) {​
// Check if the current element is larger than the current
largest​
if (numbers[i] > largest) {​
largest = numbers[i];​
}​
// Check if the current element is smaller than the
current smallest​
else if (numbers[i] < smallest) {​
smallest = numbers[i];​
}​
}​

[Link]("Array elements: ");​
for (int num : numbers) {​
[Link](num + " ");​
}​

[Link]("\n----------------------------------");​
[Link]("The smallest element in the array is: " +
smallest);​
[Link]("The largest element in the array is: " +
largest);​
}​
}​

You might also like