[Go to site: main page, start]

0% found this document useful (0 votes)
9 views10 pages

Java Assignment

The document provides a comprehensive overview of Java programming concepts, including key features, object-oriented principles, and practical coding examples. It covers topics such as classes, objects, method overloading, constructors, access modifiers, polymorphism, and dynamic method dispatch. Each section includes definitions, explanations, and code snippets to illustrate the concepts effectively.

Uploaded by

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

Java Assignment

The document provides a comprehensive overview of Java programming concepts, including key features, object-oriented principles, and practical coding examples. It covers topics such as classes, objects, method overloading, constructors, access modifiers, polymorphism, and dynamic method dispatch. Each section includes definitions, explanations, and code snippets to illustrate the concepts effectively.

Uploaded by

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

Java Programming – Assignment Answers (6 Marks Each)

Java Programming – Assignment


6-Mark Answers | CO1/PO2 & CO1/PO3

Q1. Key Features of Java (Eight Features)


Java is a platform-independent, object-oriented programming language with numerous distinctive
features:
1. Platform Independence (Write Once, Run Anywhere)
Java code is compiled into bytecode by the Java compiler. This bytecode runs on the Java Virtual
Machine (JVM), making Java programs platform-independent. The same .class file runs on Windows,
Linux, or macOS.
2. Object-Oriented
Java follows OOP principles — Encapsulation, Inheritance, Polymorphism, and Abstraction. Everything
in Java is treated as an object, making code modular, reusable, and easy to maintain.
3. Simple
Java eliminates complex features like pointers (direct memory manipulation) and multiple inheritance
from C++. It has a clean syntax that is easy to learn and write.
4. Secure
Java has no explicit pointers, a bytecode verifier, a security manager, and class loaders — all working
together to prevent unauthorized access, viruses, and data manipulation.
5. Robust
Java provides strong exception handling, automatic garbage collection, and type checking at both
compile-time and runtime, making programs less prone to crashes.
6. Multithreaded
Java supports multithreading, enabling the simultaneous execution of two or more threads. This allows
efficient use of CPU and enables tasks like animations, network operations, and I/O to run concurrently.
7. Distributed
Java is designed for distributed environments. Technologies like RMI (Remote Method Invocation) and
EJB allow Java programs to run across networks, making it ideal for internet-based applications.
8. High Performance
Java uses Just-In-Time (JIT) compilation, which converts bytecode into native machine code at
runtime, significantly improving execution speed compared to purely interpreted languages.

Q2. Java Program – Month Name Using Switch Case


Program to read month number (1–12) and display corresponding month name using switch case:
import [Link];
public class MonthName {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter month number (1-12): ");
int month = [Link]();

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 1


Java Programming – Assignment Answers (6 Marks Each)
String name;
switch (month) {
case 1: name = "January"; break;
case 2: name = "February"; break;
case 3: name = "March"; break;
case 4: name = "April"; break;
case 5: name = "May"; break;
case 6: name = "June"; break;
case 7: name = "July"; break;
case 8: name = "August"; break;
case 9: name = "September"; break;
case 10: name = "October"; break;
case 11: name = "November"; break;
case 12: name = "December"; break;
default: name = "Invalid month number.";
}
[Link]("Month: " + name);
}
}
Output (for input 3): Month: March
Output (for input 15): Invalid month number.

Q3. Class and Object in Java


Class:
A class is a blueprint or template for creating objects. It defines the properties (attributes/fields) and
behaviors (methods) that its objects will have. A class does not occupy memory until an object is
created.
Object:
An object is an instance of a class. When a class is instantiated using the 'new' keyword, an object is
created in heap memory. Each object has its own copy of instance variables.
How Objects are Created:
Syntax: ClassName objectName = new ClassName();
The 'new' keyword allocates memory, and the constructor initializes the object.
Example:
class Car {
String brand;
int speed;

void display() {
[Link]("Brand: " + brand + ", Speed: " + speed);
}
}

public class Main {


public static void main(String[] args) {
Car c1 = new Car(); // Object creation
[Link] = "Toyota";
[Link] = 120;

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 2


Java Programming – Assignment Answers (6 Marks Each)
[Link](); // Output: Brand: Toyota, Speed: 120
}
}

Q4. Java Program – Student Class with Input and Display


import [Link];
class Student {
String name;
int rollNo;
float marks;

void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Roll No: ");
rollNo = [Link]();
[Link]("Enter Marks: ");
marks = [Link]();
}

void display() {
[Link]("--- Student Details ---");
[Link]("Name : " + name);
[Link]("Roll No : " + rollNo);
[Link]("Marks : " + marks);
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student();
[Link]();
[Link]();
}
}
The Student class encapsulates three attributes. The input() method uses Scanner to take user input,
and display() prints the details.

Q5. Method Overloading in Java


Definition:
Method overloading is a feature in Java where multiple methods in the same class share the same
name but differ in their parameter list (number, type, or order of parameters). It is an example of
compile-time polymorphism. The return type alone cannot distinguish overloaded methods.
Example:
class Calculator {
// Method 1: two integers
int add(int a, int b) {

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 3


Java Programming – Assignment Answers (6 Marks Each)
return a + b;
}
// Method 2: three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method 3: two doubles
double add(double a, double b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](5, 3)); // Output: 8
[Link]([Link](5, 3, 2)); // Output: 10
[Link]([Link](2.5, 1.5)); // Output: 4.0
}
}
The compiler resolves which method to call based on the arguments provided at compile time.

Q6. Constructor in Java – Student Class with Parameterized Constructor


Definition:
A constructor is a special method in Java that is automatically called when an object is created. It has
the same name as the class and no return type. It is used to initialize objects.
A parameterized constructor accepts arguments, allowing objects to be initialized with specific values at
the time of creation.
Student Class with Parameterized Constructor (int parameter):
class Student {
int rollNo;

// Parameterized constructor with int parameter


Student(int r) {
rollNo = r;
[Link]("Student created with Roll No: " + rollNo);
}

void display() {
[Link]("Roll No: " + rollNo);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student(101);
Student s2 = new Student(102);
[Link](); // Output: Roll No: 101
[Link](); // Output: Roll No: 102
}

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 4


Java Programming – Assignment Answers (6 Marks Each)
}

Q7. Constructor Overloading in Java


Definition:
Constructor overloading is the process of defining multiple constructors in the same class with different
parameter lists. Java differentiates them by the number and types of arguments. It allows objects to be
initialized in different ways.
Example:
class Box {
double length, width, height;

// Default constructor
Box() {
length = width = height = 1.0;
}

// One-parameter constructor (cube)


Box(double side) {
length = width = height = side;
}

// Three-parameter constructor
Box(double l, double w, double h) {
length = l; width = w; height = h;
}

void volume() {
[Link]("Volume = " + (length * width * height));
}
}

public class Main {


public static void main(String[] args) {
Box b1 = new Box(); // Default
Box b2 = new Box(5); // Cube
Box b3 = new Box(2, 3, 4); // Custom
[Link](); // Volume = 1.0
[Link](); // Volume = 125.0
[Link](); // Volume = 24.0
}
}

Q8. Access Modifiers in Java


Access modifiers in Java control the visibility and accessibility of classes, methods, and variables.
There are four types:
1. public
Accessible from anywhere — same class, same package, subclass, and other packages.
Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 5
Java Programming – Assignment Answers (6 Marks Each)
public int x = 10; // Accessible everywhere

2. private
Accessible only within the same class. Best used for data hiding (encapsulation).
private int salary; // Only within the same class

3. protected
Accessible within the same package and by subclasses (even in different packages).
protected String name; // Package + subclasses

4. default (no modifier)


If no modifier is specified, it is package-private. Accessible only within the same package.
int age = 20; // Only within the same package

Summary Table:
Modifier | Same Class | Same Package | Subclass | Other Package
public | Yes | Yes | Yes | Yes
protected | Yes | Yes | Yes | No
default | Yes | Yes | No | No
private | Yes | No | No | No

Q9. Polymorphism in Java – Types with Examples


Definition:
Polymorphism means 'many forms'. In Java, it allows one interface to be used for different underlying
data types or methods. There are two types:
1. Compile-Time Polymorphism (Static Binding)
Achieved through method overloading. The method call is resolved at compile time.
class MathOps {
int square(int x) { return x * x; }
double square(double x) { return x * x; }
}

2. Runtime Polymorphism (Dynamic Binding)


Achieved through method overriding. The method call is resolved at runtime based on the actual object
type.
class Animal {
void sound() { [Link]("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Dog barks"); }
}
class Cat extends Animal {
void sound() { [Link]("Cat meows"); }
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog(); [Link](); // Dog barks
a = new Cat(); [Link](); // Cat meows

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 6


Java Programming – Assignment Answers (6 Marks Each)
}
}

Q10. Dynamic Method Dispatch in Java


Definition:
Dynamic Method Dispatch is the mechanism by which a call to an overridden method is resolved at
runtime rather than compile time. It is the foundation of runtime polymorphism in Java. A superclass
reference variable can refer to a subclass object, and the overridden method in the subclass is invoked.
Example:
class Shape {
void draw() {
[Link]("Drawing a Shape");
}
}
class Circle extends Shape {
void draw() {
[Link]("Drawing a Circle");
}
}
class Rectangle extends Shape {
void draw() {
[Link]("Drawing a Rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape s; // Superclass reference
s = new Circle(); // Refers to Circle object
[Link](); // Output: Drawing a Circle
s = new Rectangle(); // Refers to Rectangle object
[Link](); // Output: Drawing a Rectangle
}
}
The JVM determines which draw() method to call based on the actual object at runtime — this is
dynamic dispatch.

Q11. Java Concepts Explained


a) Encapsulation
Encapsulation is the process of wrapping data (fields) and methods into a single unit (class) and
restricting direct access using private modifiers. Access is provided via getter and setter methods.
Example: A BankAccount class keeps balance private and provides deposit()/withdraw() methods.
b) Static Binding
Static binding (early binding) means the method call is resolved at compile time. It applies to static,
private, and final methods, as well as overloaded methods. Example: int add(int a, int b) is resolved at
compile time based on argument types.
c) Dynamic Binding

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 7


Java Programming – Assignment Answers (6 Marks Each)
Dynamic binding (late binding) means the method call is resolved at runtime. It occurs with overridden
methods through superclass references. The JVM checks the actual type of object to decide which
method to execute.
d) Abstraction
Abstraction hides internal implementation details and shows only essential features. In Java, it is
achieved using abstract classes and interfaces. Example: A Car's start() button hides the engine
mechanics — you just use it.
abstract class Vehicle {
abstract void start(); // no implementation
}
class Bike extends Vehicle {
void start() { [Link]("Bike starts with kick"); }
}

e) Inheritance
Inheritance allows a child class to inherit properties and methods from a parent class using the
'extends' keyword. It promotes code reuse. Java supports single, multilevel, and hierarchical
inheritance.
class Animal { void eat() { [Link]("Eating"); } }
class Dog extends Animal { void bark() { [Link]("Barking"); } }
// Dog inherits eat() from Animal

Q12. this() vs super() Constructors and Keywords


this() Constructor:
Used to call another constructor within the same class. It must be the first statement in the constructor.
class Student {
String name; int rollNo;
Student() { this("Unknown", 0); } // Calls parameterized constructor
Student(String n, int r) { name = n; rollNo = r; }
}

super() Constructor:
Used to call the parent class constructor from a child class. Must also be the first statement.
class Person { Person(String n) { [Link]("Person: " + n); } }
class Student extends Person {
Student(String n) { super(n); [Link]("Student: " + n); }
}

this keyword:
Refers to the current object. Used to differentiate between instance variables and parameters with the
same name.
[Link] = name; // instance variable = parameter

super keyword:
Refers to the parent class. Used to access parent class methods or variables that are hidden by the
child class.
[Link](); // calls parent's display()

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 8


Java Programming – Assignment Answers (6 Marks Each)

Q13. Difference Between Constructor and Method


Constructor:
• Same name as the class; no return type (not even void).
• Called automatically when an object is created using 'new'.
• Used to initialize object state.
• Cannot be called explicitly like a normal method.

Method:
• Can have any name; must have a return type (or void).
• Called explicitly by the programmer.
• Used to define behavior/operations on objects.
• Can be called multiple times on the same object.
Example:
class Demo {
int x;
Demo(int val) { // Constructor
x = val;
[Link]("Constructor called, x = " + x);
}
void show() { // Method
[Link]("Method called, x = " + x);
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo(10); // Constructor auto-called
[Link](); // Method explicitly called
}
}

Q14. Compile-Time vs Runtime Polymorphism


Compile-Time Polymorphism (Method Overloading):
Resolved at compile time. Achieved through method overloading. Also called static polymorphism or
early binding.
class Print {
void show(int x) { [Link]("Integer: " + x); }
void show(String s) { [Link]("String: " + s); }
}
// Compiler picks the correct method based on arguments.

Runtime Polymorphism (Method Overriding):


Resolved at runtime. Achieved through method overriding. Also called dynamic polymorphism or late
binding.
class Bank {
float interestRate() { return 0; }
}
class SBI extends Bank {
float interestRate() { return 7.5f; }

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 9


Java Programming – Assignment Answers (6 Marks Each)
}
class ICICI extends Bank {
float interestRate() { return 8.0f; }
}
public class Main {
public static void main(String[] args) {
Bank b = new SBI();
[Link]([Link]()); // 7.5 – resolved at runtime
b = new ICICI();
[Link]([Link]()); // 8.0 – resolved at runtime
}
}
Key Difference: Compile-time polymorphism uses overloading; runtime polymorphism uses overriding.

Q15. Java Program – Find Largest Number in an Array


import [Link];
public class LargestInArray {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter " + n + " elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

int largest = arr[0]; // Assume first element is largest


for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
[Link]("Largest number is: " + largest);
}
}
Sample Output:
Enter number of elements: 5
Enter 5 elements: 12 45 7 89 33
Largest number is: 89
Logic: Initialize largest with arr[0], then traverse the array. If any element is greater than current largest,
update it. After loop completes, largest holds the maximum value.

Date of Issue: 18-03-2026 | Date of Submission: 31-03-2026 | Page 10

You might also like