Java
Java
Java
12. Assess the error in the following array declaration and rectify them.
int a[]=new [10]int;
float []b=new int[10.5];
Correction 1: int a[] = new int[10];
Correction 2: float[] b = new float[10];
13. Write a program to find the Largest of three numbers using Ternary Operator
public class LargestOfThree {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
// Find the largest of three numbers using the ternary operator
int largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
14. Write a program to display total marks of 5 students with the following attributes: Regno(int),
Name(string), Marks in subjects(Integer Array), Total(int) using student class.
public class Student {
int regno;
String name;
int[] marks;
int total;
// Constructor
public Student(int regno, String name, int[] marks) {
this.regno = regno;
this.name = name;
this.marks = marks;
this.total = calculateTotal();
}
15. What is a package? Give an example program to import and use packages.
In Java, a package is a namespace that arranges classes and interfaces into a hierarchical structure, aiding in
the organization of code. It helps avoid name conflicts by grouping related classes together, controls access by
restricting visibility, and enhances code reusability by allowing classes to be shared across different packages.
Create Package:
package MyPackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in MyPackage!");
}
}
Use the Package:
import MyPackage.MyClass;
public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
O/P: Hello from MyClass in MyPackage!
17. Create a Java class named Math Operations with overloaded methods to perform addition. Implement
three versions of the add() method:
One that adds two integers.
One that adds three integers.
public class MathOperations {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MathOperations mathOps = new MathOperations();
// Relational Operators
System.out.println("\nRelational Operators:");
System.out.println("a == b: " + (a == b)); // Equal to
System.out.println("a != b: " + (a != b)); // Not equal to
System.out.println("a > b: " + (a > b)); // Greater than
System.out.println("a < b: " + (a < b)); // Less than
// Logical Operators
boolean x = true, y = false;
System.out.println("\nLogical Operators:");
System.out.println("x && y: " + (x && y)); // Logical AND
System.out.println("x || y: " + (x || y)); // Logical OR
System.out.println("!x: " + !x); // Logical NOT
// Unary Operators
int d = 5;
System.out.println("\nUnary Operators:");
System.out.println("++d: " + (++d)); // Pre-increment
System.out.println("d++: " + (d++)); // Post-increment
System.out.println("d after increment: " + d);
System.out.println("--d: " + (--d)); // Pre-decrement
System.out.println("d--: " + (d--)); // Post-decrement
System.out.println("d after decrement: " + d);
// Ternary Operator
int max = (a > b) ? a : b;
System.out.println("\nTernary Operator:");
System.out.println("Maximum of a and b: " + max);
}
}
21. Answer the following
i) Write a program with class name "first" as the parent class. Create class name "second" as one child class
and class name "third" as another child class. (6)
class First {
public void display() {
System.out.println("This is the First class.");
}
}
class Second extends First {
public void show() {
System.out.println("This is the Second class.");
}
}
class Third extends First {
public void print() {
System.out.println("This is the Third class.");
}
}
secondObj.display();
secondObj.show();
thirdObj.display();
thirdObj.print();
}
}
O/P
This is the First class.
This is the Second class.
This is the First class.
This is the Third class.
ii) What is the type of inheritance involved in (i) and justify your answer. (4)
Type of Inheritance Involved: Hierarchical Inheritance
Justification:
In the provided code, the Second and Third classes both inherit from the same parent class, First. This means
that multiple subclasses (Second and Third) are derived from a single parent class (First). This type of
inheritance, where one parent class has multiple child classes inheriting from it, is known as Hierarchical
Inheritance.
Hierarchical Inheritance occurs when a single base class (First) is extended by multiple subclasses (Second
and Third). Each subclass inherits the properties and methods of the base class, as seen in the code where
both Second and Third can access the display() method from First while also having their own specific
methods (show() in Second and print() in Third).
22. Write a Java program that reads a list of integers from the user and sorts them using the
Bubble Sort algorithm.
import java.util.Scanner;
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero.");
scanner.close();
return;
}
break;
default:
System.out.println("Error: Invalid operator.");
scanner.close();
return;
}
System.out.println("Result: " + result);
scanner.close();
}
}
O/P
Enter first number: 12
Enter second number: 8
Enter an operator (+, -, *, /): +
Result: 20.0
25. Define Inheritance? With diagrammatic illustration and java Programs illustrate the different types of
inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) where a new class, known as
the subclass or derived class, inherits properties and behaviors (methods) from an existing class, known as
the superclass or base class. This mechanism promotes code reusability and establishes a natural hierarchy
between classes.
Types of Inheritance
1. Single Inheritance:
A class inherits from one parent class.
class Parent {
void display() { System.out.println("Parent"); }
}
class Child extends Parent {
void show() { System.out.println("Child"); }
}
public class SingleLevelInheritanceDemo {
public static void main(String[] args) {
Child c = new Child();
c.display(); // Parent
c.show(); // Child
}
}
O/P
Parent
Child
2. Multilevel Inheritance:
A class inherits from another class, which itself is derived from another class
class Grandparent {
void show() { System.out.println("Grandparent"); }
}
3. Hierarchical Inheritance:
Multiple classes inherit from a single parent class.
class Parent {
void show() { System.out.println("Parent"); }
}
class Child1 extends Parent {
void display1() { System.out.println("Child1"); }
}
class Child2 extends Parent {
void display2() { System.out.println("Child2"); }
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Child1 c1 = new Child1();
Child2 c2 = new Child2();
c1.show(); // Parent
c1.display1(); // Child1
c2.show(); // Parent
c2.display2(); // Child2
}
}
O/P
Parent
Child1
Parent
Child2
4. Multiple Inheritance:
Java does not support multiple inheritance directly through classes but allows it through interfaces.
5. Hybrid inheritance
Combination of multiple inheritance types (e.g., single, multilevel, and hierarchical) in one hierarchy, achieved
using a mix of classes and interfaces.
class Base {
void show() { System.out.println("Base"); }
}
class Intermediate extends Base {
void display() { System.out.println("Intermediate"); }
}
class Derived extends Intermediate {
void message() { System.out.println("Derived"); }
}
26. Create a package com.example.math containing two classes: Adder and Multiplier.
The Adder class should have a method add(int a, int b) and the Multiplier class should have a method
multiply(int a, int b).
In another package com.example.main, create a class Main that imports the Adder and Multiplier classes
and demonstrates their usage.
Ensure proper access protection and import statements. Also, explain the use of the CLASSPATH for
importing these packages.
Create Package com.example.math
Adder.java:
package com.example.math;
public class Adder {
public int add(int a, int b) {
return a + b;
}
}
Multiplier.java:
package com.example.math;
public class Multiplier {
public int multiply(int a, int b) {
return a * b;
}
}
2. Create Package com.example.main
Main.java:
package com.example.main;
import com.example.math.Adder;
import com.example.math.Multiplier;
public class Main {
public static void main(String[] args) {
Adder adder = new Adder();
Multiplier multiplier = new Multiplier();
System.out.println("Addition: " + adder.add(5, 3)); // Output: 8
System.out.println("Multiplication: " + multiplier.multiply(5, 3)); // Output: 15
}
}
The CLASSPATH is an environment variable in Java that tells the Java Virtual Machine (JVM) and Java compiler
where to find class files. To use packages, you need to set the CLASSPATH to include the directory where your
packages are located.
Output:
Addition: 8
Multiplication: 15