0% found this document useful (0 votes)
14 views22 pages

Java Assignment

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
14 views22 pages

Java Assignment

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

JAVA PROGRAMMING

Assignment - 2
Program: BTECH (CSE Data Science and Artificial Intelligence (IBM))
5th Semester
Course Code: CSE504-22
Session: 2024-25
CT University, Ludhiana

Submitted in partial fulfilment of the requirement for the award of the Degree of
Bachelors of Data Science and Artificial Intelligence in Computer Science Engineering
along with IBM

SUBMITTED BY: SUBMITTED TO:


NAME : N.Rishi Ram Er. Shreya Gandhi

REGISTRATION NO.: 72212437


1. Difference between method overloading and method over
riding?
A. The differences between Method Overloading and
Method Overriding in Java are as follows:
Method Overloading Method Overriding

Method overloading is a compile- Method overriding is a run-time


time polymorphism. polymorphism.

Method overriding is used to grant the


Method overloading helps to
specific implementation of the method
increase the readability of the
which is already provided by its parent
program.
class or superclass.

It is performed in two classes with


It occurs within the class.
inheritance relationships.

Method overloading may or may Method overriding always needs


not require inheritance. inheritance.

In method overloading, methods


In method overriding, methods must
must have the same name and
have the same name and same signature.
different signatures.

In method overloading, the return


type can or cannot be the same, In method overriding, the return type
but we just have to change the must be the same or co-variant.
parameter.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

Private and final methods can be Private and final methods can’t be
Method Overloading Method Overriding

overloaded. overridden.

The argument list should be


The argument list should be the same in
different while doing method
method overriding.
overloading.

2. Explain Interface, Final, Package in java with syntax and example.


A. Interface in Java
An interface in Java is a reference type, similar to a class, that
can contain only constants, method signatures, default
methods, static methods, and nested types. It cannot contain
instance fields or constructors. Interfaces are used to
represent a contract that other classes must adhere to.
Syntax:
java
Copy code
interface Interface Name {
// Constants (implicitly public, static, and final)
int CONSTANT = 100;

// Abstract method (implicitly public and abstract)


void abstract Method();
// Default method (optional implementation)
default void default Method () {
System.out.println("This is a default method.");
}

// Static method
static void staticMethod () {
System.out.println("This is a static method in interface.");
}
}

class ImplementingClass implements InterfaceName {


// Providing implementation for abstract method
public void abstractMethod() {
System.out.println("Abstract method implemented.");
}
}
Example:
java
Copy code
interface Animal {
void sound(); // abstract method
// Default method
default void breathe() {
System.out.println("This animal breathes.");
}
}

class Dog implements Animal {


public void sound() {
System.out.println("Dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks.
dog.breathe(); // Output: This animal breathes.
}
}
2. Final in Java
The final keyword is used to define constants, prevent method
overriding, and prevent class inheritance. It can be applied to
variables, methods, and classes.
Syntax:
 Final Variable:
java
Copy code
final int MAX_VALUE = 100;
 Final Method:
java
Copy code
class Parent {
final void display() {
System.out.println("Final method cannot be
overridden.");
}
}

class Child extends Parent {


// This will result in a compile-time error
// void display() {
// System.out.println("Cannot override final method.");
// }
}
 Final Class:
java
Copy code
final class MyClass {
// class body
}

// This will result in a compile-time error


// class AnotherClass extends MyClass { }
Example:
java
Copy code
class Car {
final int MAX_SPEED = 200; // A constant value

final void showSpeed() { // Method cannot be overridden


System.out.println("The maximum speed is " +
MAX_SPEED);
}
}
class SportsCar extends Car {
// This will give a compile-time error because 'showSpeed'
is final
// void showSpeed() {
// System.out.println("Sports car speed.");
// }
}

public class Main {


public static void main(String[] args) {
Car car = new Car();
car.showSpeed(); // Output: The maximum speed is 200
}
}
3. Package in Java
A package is a way of grouping related classes, interfaces, and
sub-packages. It helps organize the code, prevents naming
conflicts, and controls access. Java has two types of packages:
 Built-in packages (e.g., java.util, java.io).
 User-defined packages (created by developers).
Syntax:
 Defining a package:
java
Copy code
package com.example.myapp;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in package
com.example.myapp");
}
}
 Using a package (importing a class from a package):
java
Copy code
import com.example.myapp.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display(); // Output: Hello from MyClass in package
com.example.myapp
}
}
Example:
java
Copy code
// File: com/example/animals/Dog.java
package com.example.animals;

public class Dog {


public void bark() {
System.out.println("Woof! Woof!");
}
}

// File: com/example/test/Main.java
package com.example.test;

import com.example.animals.Dog; // Import the Dog class


from the animals package
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // Output: Woof! Woof!
}
}
3. Explain types of error in java.
In Java, errors can be broadly categorized into three main
types:
1. Compile-time Errors
These errors are detected by the compiler when the program
is being compiled. They must be corrected before the
program can be successfully compiled and run. Common
compile-time errors include:
 Syntax Errors: Mistakes in the use of the Java language. For
example, missing semicolons, misused keywords, or
mismatched parentheses.
java
// Example of a syntax error (missing semicolon)
public class Main {
public static void main(String[] args) {
System.out.println("Hello World") // <- Missing semicolon
here
}
}
 Semantic Errors: Errors that occur when the statements are
not meaningful. For instance, trying to assign a string value
to an integer variable.
java
// Example of a semantic error
int number = "ten"; // <- Cannot assign a string to an integer
2. Runtime Errors
These errors occur during the execution of the program, after
it has successfully compiled. They can cause the program to
terminate unexpectedly. Common runtime errors include:
 NullPointerException: Trying to use an object reference
that has not been initialized.
java
// Example of NullPointerException
public class Main {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // <- Throws
NullPointerException
}
}
 ArrayIndexOutOfBoundsException: Attempting to access
an array element outside its bounds.
java
// Example of ArrayIndexOutOfBoundsException
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // <-
ArrayIndexOutOfBoundsException
}
}
3. Logical Errors
These errors occur when the program compiles and runs, but
the output is not as expected. The error lies in the logic used
in the program. They are often the hardest to debug because
the program runs without crashing.
 Incorrect Logic: Writing a loop that never terminates, or
using incorrect conditions in decision-making statements.
java
// Example of a logical error
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum = sum - i; // <- Incorrect logic, should be sum =
sum + i;
}
System.out.println("Sum: " + sum); // <- Incorrect output
}
}
Summary Table
Error When
Examples
Type Detected
Compile-
During
time Syntax Errors, Semantic Errors
compilation
Errors
Runtime During NullPointerException,
Errors execution ArrayIndexOutOfBoundsException
Logical During Incorrect Logic in calculations or
Errors execution conditions
Preventing Errors
 Compile-time Errors: Ensure correct syntax and proper use
of Java language features.
 Runtime Errors: Handle exceptions and validate inputs
properly.
 Logical Errors: Test thoroughly and use debugging
techniques to verify program logic.

4. Explain exception handling using try catch final block.


Exception handling in Java is a powerful mechanism to handle
runtime errors, ensuring the program can run smoothly even
when something unexpected happens. It involves using try,
catch, and finally blocks to manage exceptions. Here's how
they work:
try Block
 The try block contains the code that might throw an
exception.
 If an exception occurs within the try block, it stops
executing, and the control is transferred to the catch block.
catch Block
 The catch block catches the exception thrown by the try
block.
 You can have multiple catch blocks to handle different types
of exceptions.
finally Block
 The finally block contains code that will always execute,
regardless of whether an exception was thrown or not.
 It's typically used for cleanup activities like closing files or
releasing resources.
Example
Here's a simple example to illustrate how these blocks work
together:
java
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Code that may throw an exception
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // This will throw an
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
// Handling the exception
System.out.println("Exception caught: " + e);
} finally {
// Code that will always execute
System.out.println("This will always be executed.");
}
}
}
Explanation
1. try Block: The code inside the try block attempts to access
an array element at an invalid index.
2. catch Block: When the ArrayIndexOutOfBoundsException is
thrown, the control is transferred to the catch block, which
prints an appropriate message.
3. finally Block: Regardless of whether the exception was
caught or not, the finally block executes, ensuring that
certain cleanup tasks are always performed.
Key Points
 Multiple catch Blocks: You can have multiple catch blocks
for different exception types. The first matching catch block
will handle the exception.
java
try {
// Some code that might throw an exception
} catch (IOException e) {
// Handle IOException
} catch (NumberFormatException e) {
// Handle NumberFormatException
} finally {
// This block will always execute
}
 Nested try Blocks: You can also nest try blocks, though it’s
generally good practice to keep exception handling as clear
and straightforward as possible.
java
try {
try {
// Some code that might throw an exception
} catch (Exception e) {
// Handle inner exception
}
} catch (Exception e) {
// Handle outer exception
} finally {
// This block will always execute
}
Using try, catch, and finally blocks effectively can help make
your code more robust and easier to debug

5.Define thread and explain the need of Multi-threading in Java.


A. A thread is a lightweight sub-process, the smallest unit of
processing in a program. In Java, threads allow a program to
perform multiple operations concurrently. Each thread runs in
parallel with other threads, sharing the same resources, but
independently executing its own task.
Creating a Thread in Java
There are two primary ways to create a thread in Java:
1. Extending the Thread class:
java
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}

public static void main(String[] args) {


MyThread t1 = new MyThread();
t1.start(); // Start the thread
}
}
2. Implementing the Runnable interface:
java
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running.");
}

public static void main(String[] args) {


MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
t1.start(); // Start the thread
}
}
Need for Multi-threading in Java
Multi-threading is essential in Java for several reasons:
1. Improved Performance:
o By dividing tasks into multiple threads, a program can
execute more efficiently, utilizing CPU resources better.
o Particularly useful for CPU-intensive tasks where
different parts of a job can be processed
simultaneously.
2. Concurrency:
o Allows a program to perform multiple operations at the
same time, enhancing responsiveness and interactivity.
o For example, a web server can handle multiple client
requests simultaneously.
3. Better Resource Utilization:
o Multithreading helps in optimal utilization of resources
such as CPU, which might otherwise remain idle.
o In a single-threaded program, CPU cycles may be
wasted while waiting for I/O operations to complete.
4. Simplifies Complex Applications:
o Makes it easier to design complex applications by
dividing the workload into smaller, more manageable
threads.
o Enhances the modularity and readability of the code.
5. Responsive User Interfaces:
o Keeps the user interface responsive. For instance, in a
graphical user interface (GUI) application, the main
thread can handle user inputs while a separate thread
performs a background task.
Example: Multi-threading for Resource Utilization
Here's an example that demonstrates the use of multithreading
to print even and odd numbers simultaneously:
java
class EvenThread extends Thread {
public void run() {
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even: " + i);
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();

evenThread.start(); // Start the even thread


oddThread.start(); // Start the odd thread
}
}
This example showcases how two threads (one for even
numbers and one for odd numbers) can run concurrently,
efficiently utilizing CPU resources and speeding up the overall
execution time.

You might also like