0% found this document useful (0 votes)
5 views

java 2

The document explains various Java programming concepts including parameterized constructors, natural number summation, method overloading, multidimensional arrays, multilevel inheritance, and exception handling. It provides example programs for each concept, demonstrating their functionality and use cases. Additionally, it includes a brief overview of variable declaration in JavaScript and a program for adding two numbers using a form and button click event.

Uploaded by

Sohel Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

java 2

The document explains various Java programming concepts including parameterized constructors, natural number summation, method overloading, multidimensional arrays, multilevel inheritance, and exception handling. It provides example programs for each concept, demonstrating their functionality and use cases. Additionally, it includes a brief overview of variable declaration in JavaScript and a program for adding two numbers using a form and button click event.

Uploaded by

Sohel Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Q 1 Explain parametenzed constructor with java program.

Parameterized Constructor in JavaA constructor is a special type of method in Java that is used to
initialize objects. A parameterized constructor is a constructor that takes arguments (parameters)
to initialize an object with specific values.Key Points about Parameterized Constructor:

1. It has the same name as the class.

2. It takes parameters to initialize object attributes.

3. It is used to provide different values to different objects.

Java Program Example

// Class definition

class Student {String name;

int age; // Parameterized Constructor-- Student(String n, int a) { name = n; age = a; }

// Method to display student details void display() { System.out.println("Name: " + name + ",
Age: " + age); } public static void main(String[] args) { // Creating objects and passing values to
the constructor

Student s1 = new Student("Alice", 20); Student s2 = new Student("Bob", 22);

// Displaying object values s1.display() s2.display();

Output:

Name: Alice, Age: 20

Name: Bob, Age: 22

Explanation:

1. The Student class has a parameterized constructor Student(String n, int a), which initializes
the name and age attributes.

2. In the main() method, two objects (s1 and s2) are created using the parameterized
constructor, and different values are passed to them.

3. The display() method prints the values of each object.

This approach helps in creating objects with different initial values dynamically.
Q 2---Write a program in Java to diplay terms of naturel number and their sum

Java Program to Display Natural Numbers and Their Sum

This program will:

1. Take an input n from the user.

2. Display the first n natural numbers.

3. Calculate and display their sum.

Java Program

import java.util.Scanner;

public class NaturalNumberSum { public static void main(String[] args) { Scanner sc = new
Scanner(System.in);

// Taking user input for number of terms System.out.print("Enter the number of natural
numbers: "); int n = sc.nextInt();

int sum = 0;

// Displaying natural numbers and calculating sum

System.out.print("Natural numbers: ");

for (int i = 1; i <= n; i++) {

System.out.print(i + " ");

sum += i;

}// Displaying the sum of natural numbers

System.out.println("\nSum of natural numbers: " + sum);

sc.close();}}

Example Output

Enter the number of natural numbers: 5

Natural numbers: 1 2 3 4 5

Sum of natural numbers: 15

Explanation

• The program takes an integer n from the user.

• It prints natural numbers from 1 to n.

• The sum is calculated using a loop and displayed at the end.

This is a simple and effective way to work with natural numbers in Java.
Q 3 Explain method overloading using java program.

Method Overloading in Java

Method Overloading is a feature in Java that allows multiple methods in the same class to have the
same name but different parameters (different type, number, or sequence of parameters). It helps
in improving code readability and reusability. Key Rules for Method Overloading:

1. Methods must have the same name.

2. Methods must have different number of parameters OR different types of parameters.

3. The return type does not affect method overloading.

4. Method overloading happens at compile-time (also called Compile-time Polymorphism).

Example Java Program for Method Overloading

class OverloadExample { // Method with one parameter

void display(int num) { System.out.println("Integer: " + num);

} // Method with two parameters void display(int num1, int num2) {

System.out.println("Two Integers: " + num1 + " and " + num2); }

// Method with a different parameter type (double)

void display(double num) {System.out.println("Double: " + num); }

public static void main(String[] args) {OverloadExample obj = new OverloadExample();

// Calling different overloaded methods

obj.display(10); // Calls method with int parameter

obj.display(20, 30); // Calls method with two int parameters

obj.display(15.5); // Calls method with double parameter }}

Output

Integer: 10

Two Integers: 20 and 30

Double: 15.5

Explanation

1. The display method is overloaded with:

o display(int num): Accepts a single integer.

o display(int num1, int num2): Accepts two integers.

o display(double num): Accepts a double value.

2. The compiler determines which method to call based on the arguments passed.

3. Overloading allows the same method name to handle different types of inputs efficiently.
Q—4 What is a Multidimensional array? Wite a java program for addition of two dimensional array

import java.util.Scannerpublic class MatrixAddition { public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Taking input for matrix dimensions

System.out.print("Enter the number of rows: ");

int rows = sc.nextInt();

System.out.print("Enter the number of columns: ");

int cols = sc.nextInt(); int[][] matrix1 = new int[rows][cols] int[][] matrix2 = new
int[rows][cols]; int[][] sumMatrix = new int[rows][cols];

// Input for First Matrix System.out.println("Enter elements of first matrix:");

for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) {matrix1[i][j] = sc.nextInt(); }}// Input for
Second Matrix

System.out.println("Enter elements of second matrix:");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

matrix2[i][j] = sc.nextInt();

// Adding both matrices

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];

} } // Displaying the Result

System.out.println("Sum of the two matrices:");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

System.out.print(sumMatrix[i][j] + " ");

} System.out.println();

} sc.close();

}
Q 5----Explain concept of multilevel inhertiance using a simple java program

Multilevel Inheritance in Java

Multilevel Inheritance is a type of inheritance where a class is derived from another derived class.
In other words, there is a chain of inheritance.

Key Points of Multilevel Inheritance----A class (Child) inherits from another class (Parent), and then
another class (Grandchild) inherits from the Child class.----The derived class gets all the features of
the base class and can also have its own additional features.---This forms a hierarchy of classes.

Example of Multilevel Inheritance in Java Let's consider a real-world example: Animal → Mammal
→ Dog Animal class represents general properties of all animals.Mammal class inherits from
Animal and adds features specific to mammals.Dog class inherits from Mammal and adds
properties of a dog. Java Code for Multilevel Inheritance// Base Class (Parent)class Animal {

void eat() { System.out.println("This animal eats food.");}}

// Derived Class (Child of Animal)class Mammal extends Animal { void walk() {


System.out.println("This mammal walks on legs."); }}

// Another Derived Class (Child of Mammal)class Dog extends Mammal {

void bark() { System.out.println("Dog barks: Woof Woof!");}}

// Main Class public class MultilevelInheritance {public static void main(String[] args) {

Dog myDog = new Dog(); // Creating an object of Dog // Calling methods from all levels of
inheritance myDog.eat(); // From Animal class

myDog.walk(); // From Mammal class

myDog.bark(); // From Dog class }}

Explanation

1. Animal class (Base class)Contains a method eat().

2. Mammal class (Derived from Animal)Inherits eat() method from Animal.Defines its own
method walk().

3. Dog class (Derived from Mammal)Inherits eat() from Animal and walk() from
Mammal.Defines its own method bark().

4. Main Method (MultilevelInheritance class)We create an object of Dog.The object can


access methods from all the ancestor classes.

5. Output This animal eats food.This mammal walks on legs.

Dog barks: Woof Woof!

Advantages of Multilevel Inheritance✔ Promotes code reusability.


✔ Helps in hierarchical classification of objects.
✔ Allows method overriding for specialized behavior.
Q 6 What is exceptions handling and state benefits of exception handling in java? Explain Java
Exception Handling Keywords.

Exception Handling in Java

Exception handling manages runtime errors to prevent program crashes and maintain smooth
execution.

Benefits:

1. Prevents program crashes. 2.Improves code readability.

3.Helps in debugging.4.Ensures smooth execution.

5.Encourages modular code.

Java Exception Handling Keywords:

1. try – Contains code that may cause an exception.

2. catch – Handles exceptions from the try block.

3. finally – Always executes, used for cleanup.

4. throw – Manually throws an exception.

5. throws – Declares exceptions a method might throw.

Example:

public class ExceptionExample {

public static void main(String[] args) {

try {

int a = 10, b = 0;

int result = a / b; // Error

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero!");

} finally {

System.out.println("Always executes.");

Output:

Error: Cannot divide by zero!

Always executes.

Exception handling makes Java programs more robust and reliable.


Q 8 How to declare variables in Java Script? Write a Java script Program to add two numbers by
using on click event, form and text box.

Declaring Variables in JavaScript

In JavaScript, variables can be declared using var, let, or const:

• var: Used in older code, has function scope.

• let: Block-scoped and recommended for most cases.

• const: Block-scoped and used for constants (unchangeable values).

Example:

var x = 10; // Function-scoped

let y = 20; // Block-scoped

const z = 30; // Block-scoped and cannot be reassigned

JavaScript Program to Add Two Numbers Using Form, Text Box & Button Click Event

This program takes two numbers from user input, adds them, and displays the result when a
button is clicked.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Add Two Numbers</title>

<script>

function addNumbers() {

// Get values from text boxes

let num1 = parseFloat(document.getElementById("num1").value);

let num2 = parseFloat(document.getElementById("num2").value);

// Check if input is valid

if (isNaN(num1) || isNaN(num2)) {

alert("Please enter valid numbers!");

return;

}
// Perform addition

let sum = num1 + num2;

// Display result

document.getElementById("result").innerHTML = "Sum: " + sum;

</script>

</head>

<body>

<h2>Add Two Numbers</h2>

<form>

<label for="num1">Enter first number:</label>

<input type="text" id="num1">

<br><br>

<label for="num2">Enter second number:</label>

<input type="text" id="num2">

<br><br>

<button type="button" onclick="addNumbers()">Add</button>

</form>

<h3 id="result"></h3>

</body>

</html>

Explanation:

1. The user enters two numbers in the text fields.

2. When the button is clicked, the addNumbers() function runs.

3. The function retrieves the values, converts them to numbers, adds them, and displays the
result in an <h3> tag.

You might also like