Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

C.V.

RAMAN GLOBAL UNIVERSITY


BHUBANESWAR, ODISHA-752054
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OBJECT ORIENTED PROGRAMMING USING JAVA

NAME : ISHANT ABHILASH NAYAK

REGD. NO. : 20010146

SEMESTER :

BRANCH : CSE

1
ASSIGNMENT 1
1. Why is java platform independent? difference between JDK, JVM &JRE.

Java is considered platform independent due to its ability to run the same compiled
bytecode on different operating systems. The key components enabling this are:

1. Java Source Code Compilation: Java source code is compiled into bytecode
by the Java Compiler.
2. Bytecode: This intermediate representation is platform-independent.
3. Java Virtual Machine (JVM): The JVM on each platform interprets or
compiles this bytecode into machine code suitable for that specific platform.
This means the same bytecode can run on any device that has a JVM.

Difference between JDK, JVM & JRE

Java Development Kit (JDK):

 The JDK is a full-featured software development kit required to develop Java


applications.
 It includes the JRE, an interpreter/loader (Java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), and other tools needed for Java
development.
 It is primarily used by Java developers.

Java Virtual Machine (JVM):

 The JVM is an abstract machine that provides a runtime environment to


execute Java bytecode.
 It is platform-dependent; different JVMs are available for different operating
systems.
 The JVM performs three main tasks:
1. Loads bytecode.
2. Verifies bytecode.
3. Executes bytecode (using an interpreter or a Just-In-Time (JIT)
compiler).
 The JVM is part of the JRE.

Java Runtime Environment (JRE):

2
 The JRE provides the libraries, Java Virtual Machine (JVM), and other
components to run applications written in Java.
 It does not include development tools like compilers or debuggers (these are
part of the JDK).
 The JRE is used by end-users to run Java applications.

In summary:

 JDK = JRE + Development tools (compiler, debugger, etc.)


 JRE = JVM + Libraries required to run Java applications
 JVM = Engine that runs Java bytecode and makes the Java platform-
independent by translating bytecode to machine-specific instructions.

2. Differentiate between for loop and for each loop with suitable example?

The for loop and for-each loop (also known as the enhanced for loop)
are both used for iteration in Java.

 Syntax:

 for loop: for (initialization; condition; update) { // code }


 for-each loop: for (elementType element: collection) { // code }

 Use Cases:

 for loop: Suitable for situations where you need to control the loop index or
iterate in a specific way (e.g., skipping elements, iterating in reverse).
 for-each loop: Best for iterating over elements in a collection or array
where the order is not important and there is no need to manipulate the index.

 Flexibility:

 for loop: More flexible, allowing for complex iteration logic, including
multiple conditions, updates, or nested loops.
 for-each loop: Simpler and more concise, but less flexible since it is only
suitable for forward iteration over collections and arrays.

 Readability:

3
 for loop: Can become complex and harder to read with more logic in the
initialization, condition, and update sections.
 for-each loop: More readable and less prone to errors, as it removes the
boilerplate code associated with managing the loop counter.

3. What do you mean by variable length array or jagged array or array of


array? Give examples while declaring 2D and 3D array?

Variable Length Array (Jagged Array): A variable length array, often referred
to as a jagged array or array of arrays, is an array whose elements are arrays
themselves. These inner arrays can have different lengths, making the outer
array "jagged.

Example of a 2D Jagged Array:

// Declaring a 2D jagged array


int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2]; // First row has 2 columns
jaggedArray[1] = new int[3]; // Second row has 3 columns
jaggedArray[2] = new int[1]; // Third row has 1 column

// Initializing the jagged array


jaggedArray[0][0] = 1;
jaggedArray[0][1] = 2;
jaggedArray[1][0] = 3;
jaggedArray[1][1] = 4;
jaggedArray[1][2] = 5;
jaggedArray[2][0] = 6;

Example of a 3D Jagged Array:

// Declaring a 3D jagged array


int[][][] jaggedArray3D = new int[2][][];

jaggedArray3D[0] = new int[2][]; // First element is a 2D array


jaggedArray3D[0][0] = new int[3]; // First row of the first 2D array has 3 columns
4
jaggedArray3D[0][1] = new int[2]; // Second row of the first 2D array has 2 columns

jaggedArray3D[1] = new int[1][]; // Second element is a 2D array


jaggedArray3D[1][0] = new int[4]; // Only row of the second 2D array has 4 columns

4. What is a constructor? Differentiate between parameterized and default


constructor and explain the concept of constructor overloading with
examples.

Constructor: A constructor in Java is a special method used to initialize


objects. It is called when an instance of a class is created. Constructors have
the same name as the class and do not have a return type.

Default Constructor: A default constructor is one that takes no arguments. It


is provided by the compiler if no constructor is defined in the class.

class Example {
int value;
// Default constructor
Example () {
value = 0;
}
}

Parameterized Constructor: A parameterized constructor is one that takes


one or more arguments to initialize the object with specific values .

class Example {
int value;
// Parameterized constructor
Example (int val) {
value = val;
}
}
Constructor Overloading: Constructor overloading is the concept of having
more than one constructor with different parameter lists in the same class.
5
Example:

class Example {
int value;
String name;
// Default constructor
Example () {
value = 0;
name = "Default";
}
// Parameterized constructor
Example (int val) {
value = val;
name = "Default";
}
// Another parameterized constructor
Example (int val, String name) {
value = val;
this.name = name;
}
}

5. Discuss the basic principle of any object-oriented programming language.


a. Encapsulation: Bundling data (attributes) and methods (functions) that
operate on the data into a single unit or class, and restricting access to
some of the object's components.
b. Abstraction: Hiding the complex implementation details and showing
only the essential features of the object.
c. Inheritance: A mechanism where one class acquires the properties and
behaviors of a parent class.

6
d. Polymorphism: The ability of a single function or method to operate in
different ways on different data types or instances.

6. With suitable examples differentiate between pass by value and pass by


reference way of parameter passing techniques in writing a method.

Pass by Value: In Java, all primitive types (int, char, etc.) are passed by value.
This means a copy of the value is passed to the method, and changes to the
parameter do not affect the original value.
Example:
public class Test {
public static void modify(int x) {
x = 10;
}
public static void main(String[] args) {
int a = 5;
modify(a);
System.out.println(a); // Outputs: 5
}
}
Pass by Reference: In Java, object references are passed by value. This means
a copy of the reference to the object is passed, allowing the method to modify
the actual object
Example:
class MyObject {
int value;
}
public class Test {
public static void modify(MyObject obj) {
obj.value = 10;
}
public static void main(String[] args) {
MyObject obj = new MyObject();
7
obj.value = 5;
modify(obj);
System.out.println(obj.value); // Outputs: 10
}
}

7. Explain different ways the static, final and this keyword are applied to
variables, methods or classes in Java programming with relevant examples.
Static: The static keyword in Java is used for memory management. It can
be applied to variables, methods, blocks, and nested classes.
Example:
class Example {
static int count = 0;
static void displayCount() {
System.out.println("Count: " + count);
}
}

Final: The final keyword is used to declare constants. It can be applied to


variables, methods, and classes.

Example:

class Example {

final int MAX_VALUE = 100;

final void display() {

System.out.println("This is a final method.");

8
final class FinalClass {

// This class cannot be extended

8. Discuss memory allocation and deallocation in detail. When an object is


eligible for memory deallocation and collected by the Garbage collector.

Memory Allocation in Java:

 Stack: Used for static memory allocation. It stores primitive variables and
references to objects in the heap.
 Heap: Used for dynamic memory allocation. It stores objects and their instance
variables.

Memory Deallocation and Garbage Collection:

 An object becomes eligible for garbage collection when it is no longer


reachable from any live threads or static references.
 The Garbage Collector (GC) reclaims memory by collecting and disposing of
objects that are no longer in use

Example:
public class GarbageCollection {
public static void main(String[] args) {
GarbageCollection obj = new GarbageCollection();
obj = null; // The object is now eligible for garbage collection
System.gc(); // Requesting JVM to run Garbage Collector
}
@Override
protected void finalize() throws Throwable {
System.out.println("Garbage collector called");
}
}
9
9. State object slicing. Explain the need for it.

Object Slicing: Object slicing occurs when a derived class object is assigned
to a base class object. The derived class part of the object is "sliced off," and
only the base class part is copied.

Example: In Java, object slicing does not occur directly since Java uses
references. However, if we cast a derived class object to a base class reference, we
lose access to the derived class methods and attributes

10.Outline the importance of JIT compiler.


The Just-In-Time (JIT) compiler is an integral part of the Java Virtual Machine
(JVM) that enhances the performance of Java applications by translating bytecode
into native machine code at runtime. Here's an outline of its importance:
1.Performance Optimization

 Faster Execution: By converting bytecode to native machine code at runtime,


the JIT compiler allows the program to run directly on the host machine's CPU,
resulting in significantly faster execution compared to interpreting bytecode.

2.Adaptive Optimization

 Dynamic Profiling: The JIT compiler collects runtime statistics and uses this
data to optimize code based on the actual execution patterns, allowing it to
make informed decisions about which optimizations will be most beneficial.

3.Platform Independence

 Abstract Bytecode: Java bytecode is platform-independent. The JIT compiler


translates this bytecode into platform-specific machine code, allowing the same
Java program to run efficiently on any platform with a JVM.

4. Reduced Startup Time

10
 Selective Compilation: The JIT compiler does not compile the entire program
at once. Instead, it compiles methods on-demand (as they are called), which
helps reduce the initial startup time compared to ahead-of-time (AOT)
compilation.

5.Memory Efficiency

 Inline Caching: The JIT compiler uses inline caching to optimize method
dispatches, reducing the overhead of method calls and improving memory
efficiency.

11
ASSIGNMENT 2

public class Calculator {


// Static method to calculate power for integers
public static int powerInt(int num1, int num2) {
return (int) Math.pow(num1, num2);
}
// Static method to calculate power for a double and an integer
public static double powerDouble(double num1, int num2) {
return Math.pow(num1, num2);
}
// Main method to test the functionalities
public static void main(String[] args) {
// Test the powerInt method
int resultInt = Calculator.powerInt(2, 3); // 2^3 = 8
System.out.println("2 to the power of 3 is: " + resultInt);
// Test the powerDouble method
double resultDouble = Calculator.powerDouble(2.5, 3); // 2.5^3 = 15.625
System.out.println("2.5 to the power of 3 is: " + resultDouble);
}
}
12
public class Box {
// Encapsulation: Private instance variables
private double width;
private double height;
private double depth;
// Constructor (Encapsulation and Abstraction): Initializes the box dimensions
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
// Method (Abstraction): Calculates and returns the volume of the box
public double getVolume() {
return width * height * depth;
}
// Main method to test the functionality
public static void main(String[] args) {
// Creating an object of the Box class (Encapsulation and Abstraction)
Box myBox = new Box(10, 20, 15);
// Calling the method to calculate the volume (Abstraction)
double volume = myBox.getVolume();
13
// Printing the volume
System.out.println("The volume of the box is: " + volume);
}
}

public class Author {


// Member variables
private String name;
private String email;
private char gender;
// Parameterized constructor to initialize the variables
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
// Getters and setters for the member variables

14
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}

public void setEmail(String email) {


this.email = email;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender +
"]";
}
}
15
public class Book {
// Member variables
private String name;
private Author author; // Author is a reference to an Author object
private double price;
private int qtyInStock;

// Parameterized constructor to initialize the variables


public Book(String name, Author author, double price, int qtyInStock) {
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}

// Getters and setters for the member variables


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Author getAuthor() {
return author;
16
}
public void setAuthor(Author author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQtyInStock() {
return qtyInStock;
}
public void setQtyInStock(int qtyInStock) {
this.qtyInStock = qtyInStock;
}
@Override
public String toString() {
return "Book [name=" + name + ", author=" + author + ", price=" + price + ",
qtyInStock=" + qtyInStock + "]";
}
}

public class Main {


public static void main(String[] args) {
17
// Create an Author object
Author author = new Author("J.K. Rowling", "jkrowling@example.com", 'F');

// Create a Book object


Book book = new Book("Harry Potter", author, 29.99, 100);

// Print the details of the book (including author details)


System.out.println(book);
}
}

Java
public class Fruit {

protected String name; // Protected for subclass access


protected String taste;
protected int size;

public Fruit(String name, String taste, int size) {


this.name = name;
this.taste = taste;
this.size = size;
}

public void eat() {


System.out.println("Eating a " + name + ", it tastes " + taste);
}
18
}

class Apple extends Fruit {

public Apple(int size) {


super("apple", "sweet", size); // Call superclass constructor
}

@Override // Override to provide specific taste description


public void eat() {
System.out.println("Eating a crisp, sweet " + name + ", size: " + size);
}
}

class Orange extends Fruit {

public Orange(int size) {


super("orange", "citrusy", size);
}

@Override // Override to provide specific taste description


public void eat() {
System.out.println("Eating a juicy, " + taste + " " + name + ", size: " + size);
}
}

public class InheritanceDemo {

public static void main(String[] args) {


Apple apple = new Apple(2);
Orange orange = new Orange(3);

apple.eat();
orange.eat();
}
}

19
public abstract class Compartment {
public abstract String notice();
}
class FirstClass extends Compartment {
@Override
public String notice() {
return "This is a First Class compartment";
}
}
class Ladies extends Compartment {
@Override
public String notice() {
return "This is a Ladies compartment";
}
20
}
class General extends Compartment {
@Override
public String notice() {
return "This is a General compartment";
}
}
class Luggage extends Compartment {
@Override
public String notice() {
return "This is a Luggage compartment";
}
}

public class TestCompartment {


public static void main(String[] args) {
Compartment[] compartments = new Compartment[10];
for (int i = 0; i < compartments.length; i++) {
int randomNum = (int) (Math.random() * 4) + 1; // Generate random number
between 1 and 4
switch (randomNum) {
case 1:
compartments[i] = new FirstClass();
break;
case 2:
21
compartments[i] = new Ladies();
break;
case 3:
compartments[i] = new General();
break;
case 4:
compartments[i] = new Luggage();
break;
}
}
// Print compartment notices
for (Compartment compartment : compartments) {
System.out.println(compartment.notice());
}
}
}

22
public class Animal {
private String name;
private int age;

public Animal(String name, int age) {


this.name = name;
this.age = age;
}

public void makeSound() {


System.out.println("Generic animal sound");
}

public String getName() {


return name;
}

23
public void setName(String name) {
this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

class Dog extends Animal {


public Dog(String name, int age) {
super(name, age); // Call the superclass constructor to initialize name and age
}

@Override
public void makeSound() {
System.out.println("Woof!");
}
}

24
class Cat extends Animal {
public Cat(String name, int age) {
super(name, age);
}
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Animal animal = new Animal("Generic Animal", 1);
Dog dog = new Dog("Fido", 2);
Cat cat = new Cat("Whiskers", 1);

animal.makeSound(); // Output: Generic animal sound


dog.makeSound(); // Output: Woof!
cat.makeSound(); // Output: Meow!
}
}
5. What is inheritance and its advantages? What are different types of
inheritance supported by using class? Write a Java program for this by using
inheritance.

25
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that
allows you to create new classes based on existing ones. It provides a way to reuse
code and establish relationships between classes. Here's a breakdown of inheritance
and its advantages:

Inheritance:

 Base Class (Super Class): The original class from which new classes inherit
properties and methods.
 Derived Class (Sub Class): The class that inherits from the base class. It can
access and potentially modify inherited attributes and methods.

Advantages of Inheritance:

1. Code Reusability: You can avoid writing the same code repeatedly by
inheriting from a base class. This saves development time and effort.
2. Maintainability: Changes made to the base class propagate to all derived
classes, simplifying maintenance.
3. Extensibility: Inheritance allows you to create specialized classes that extend
the functionality of the base class.
4. Polymorphism: Inheritance enables polymorphic behavior, where objects of
different derived classes can respond differently to the same method call.

Types of Inheritance in Java (using classes):

1. Single Inheritance: A derived class inherits from only one base class. This is
the most common type of inheritance in Java.
2. Multilevel Inheritance: A derived class inherits from another derived class,
which in turn inherits from a base class. It creates a chain of inheritance.
3. Hierarchical Inheritance: Multiple derived classes inherit from the same base
class. This allows for specialization of different functionalities based on the
derived class.

class Animal {

private String name;

private int age;

public Animal(String name, int age) {


26
this.name = name;

this.age = age;

public void makeSound() {

System.out.println("Generic animal sound");

// Getters and setters omitted for brevity

class Dog extends Animal {

public Dog(String name, int age) {

super(name, age); // Call the superclass constructor

@Override

public void makeSound() {

System.out.println("Woof!");

public class InheritanceDemo {

public static void main(String[] args) {

Animal animal = new Animal("Generic Animal", 1);

Dog dog = new Dog("Fido", 2);


27
animal.makeSound(); // Output: Generic animal sound

dog.makeSound(); // Output: Woof!

// Abstract class - cannot be instantiated directly

abstract class Employee {

private String name;

private int id;

private String department;

public Employee(String name, int id, String department) {

this.name = name;

this.id = id;
28
this.department = department;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getDepartment() {

return department;

public void setDepartment(String department) {

this.department = department;

29
// Abstract method - needs implementation in subclasses

public abstract double calculateSalary();

class Manager extends Employee {

private double basicSalary;

private double allowance;

public Manager(String name, int id, String department, double basicSalary,


double allowance) {

super(name, id, department); // Call superclass constructor

this.basicSalary = basicSalary;

this.allowance = allowance;

@Override

public double calculateSalary() {

return basicSalary + allowance;

class Developer extends Employee {

30
private double salary;

private double bonus;

public Developer(String name, int id, String department, double salary,


double bonus) {

super(name, id, department);

this.salary = salary;

this.bonus = bonus;

@Override

public double calculateSalary() {

return salary + bonus;

public class EmployeeTest {

public static void main(String[] args) {

Manager manager = new Manager("Alice", 123, "Engineering", 100000.0,


20000.0);

Developer developer = new Developer("Bob", 456, "IT", 80000.0,


10000.0);

System.out.println("Manager Name: " + manager.getName() + ", Salary: "


+ manager.calculateSalary());

31
System.out.println("Developer Name: " + developer.getName() + ",
Salary: " + developer.calculateSalary());

7.Mention the usage of super keywords used in java programs.

The super keyword in Java is used to refer to the immediate parent class
(superclass) of a subclass. It has multiple important uses in object-oriented
programming.

Calling Superclass Constructor:

 When a subclass constructor is defined, it can call the constructor of its


superclass using super (). This is essential to ensure proper initialization of
inherited members from the parent class.

Accessing Superclass Methods:

 If a subclass has a method with the same name as a method in its superclass,
you can use super to explicitly call the superclass method. This is useful
when you want to reuse some functionality from the parent class while
potentially overriding its behavior in the subclass

Accessing Superclass Fields :

 In rare cases, you can use super to access a field (variable) directly from the
superclass. However, this is generally discouraged as it can tightly couple your
subclass to the implementation details of the parent class and hinder code
maintainability. It's usually better to access the field through getter methods if
possible.

8.Explain the concept of method overloading with suitable examples and also
compare it with constructor overloading. Also compare it with method
overriding.

32
Method overloading is a powerful concept in Java that allows you to define multiple
methods with the same name within a class, but with different parameter lists. This
enables you to create methods that perform similar operations but can handle
different types or numbers of arguments.

Key Points:

 Methods can have the same name but must have different parameter lists. This
differentiation can be based on:
o Number of parameters
o Type of parameters
o Order of parameters
 The compiler determines which overloaded method to call based on the
arguments provided at the time of invocation.

Example:

Java
class Calculator {

public int add(int a, int b) {


return a + b;
}

public double add(double a, double b) {


return a + b;
}

public String add(String a, String b) {


return a + b; // String concatenation
}
}

Constructor Overloading

Constructor overloading is a special case of method overloading that applies to


constructors. It allows you to create constructors with different parameter lists to
initialize objects in various ways.

Similar to method overloading, constructor overloading is based on the number, type,


or order of parameters in the constructor definition.
33
Example:

Java
class Point {

private int x;
private int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}
public Point(int xy) { // Single parameter constructor for setting both x and y
this(xy, xy); // Call the constructor with two parameters
}
}

Method overriding is a concept of inheritance where a subclass redefines a method


inherited from its parent class. The overridden method has the same name, parameter
list, and return type as the method in the parent class.

Key Differences:

1. Inheritance: Method overriding involves inheritance, while overloading


occurs within the same class.
2. Parameter List: Overloading methods must have different parameter lists,
while overriding methods must have the same parameter list (including
number, type, and order).
3. Return Type: Overriding methods can have a covariant return type (a subclass
of the parent class's return type), while overloaded methods can have any
return type.

9.How an abstract modifier is used for a class and method in a Java program.
Explain with an example. Differentiate between abstract class and interface.

 Declaration: Classes can be declared as abstract using the abstract keyword.


 Instantiation: Abstract classes cannot be directly instantiated (creating objects).
They serve as blueprints for creating subclasses.
34
 Purpose: They provide a base structure with shared properties and methods, some
of which may be abstract (unimplemented).
 Abstract Methods: Abstract methods have no implementation within the abstract
class. They are declared with an empty body ({}) and force subclasses to provide
their own implementations.
Example:
abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}

public String getColor() {


return color;
}
// Abstract method - subclasses must implement
public abstract double calculateArea();
}

class Circle extends Shape {


private double radius;

public Circle(String color, double radius) {


super(color); // Call superclass constructor
this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

class Square extends Shape {


private double sideLength;

35
public Square(String color, double sideLength) {
super(color);
this.sideLength = sideLength;
}

@Override
public double calculateArea() {
return sideLength * sideLength;
}
}

Abstract Methods:

 Declaration: Methods can be declared as abstract using the abstract


keyword.
 Implementation: Abstract methods have no implementation body ({ })
within the class.
 Purpose: They define a method signature (name and parameters) that
subclasses must implement.
 Location: Abstract methods can only be declared within abstract classes.

Interfaces:

 Declaration: Interfaces are declared using the interface keyword.


 Instantiation: Interfaces cannot be instantiated either. They define a contract
that classes can implement.
 Purpose: They specify a set of methods that implementing classes must
provide implementations for.
 Method Types: Interfaces can only contain abstract methods (no
implementation) and static and default methods.

interface Drawable {

void draw();

36
class Text implements Drawable {

@Override

public void draw() {

System.out.println("Drawing Text");

class Image implements Drawable {

@Override

public void draw() {

System.out.println("Drawing Image");

Assignment 3

37
1. Write down different types of packages with their predefined classes.

Built-in Packages (Java API):

These packages come pre-defined with the Java installation and provide a rich set of
classes and interfaces for various functionalities. Some commonly used built-in
packages and their predefined classes include:

 java.lang: This is the core package that contains fundamental classes like
Object, String, System, Math, Integer, Double, etc.
 java.util: This package provides utility classes for collections (ArrayList,
HashMap, LinkedList), date and time (Date, Calendar), input/output (Scanner,
System.out), and more.
 java.io: This package deals with input/output operations like file handling
(File, FileReader, FileWriter), network streams (InputStream, OutputStream).
 java.awt: This package provides classes for building graphical user interfaces
(GUIs) in Java (Component, Container, Frame, Button, etc.).
 java.net: This package facilitates network programming, including creating
sockets (Socket, ServerSocket), URLs (URL), and making network
connections.

User-Defined Packages:

 You can create your own packages to organize your custom classes and
interfaces in a hierarchical structure. This helps in code maintainability and
prevents naming conflicts. Here's how to define a user-defined package:

package mypackage; // Define a package named 'mypackage'

public class MyClass {

// Your class definition here

2. Difference between throw vs throws.

The difference between throw and throws lies in their usage within Java code:

throw:

38
 Keyword: It's a keyword used within a method or block of code.
 Purpose: It's used to explicitly throw an exception from the code. When
throw is encountered, the normal flow of execution halts, and the exception is
propagated up the call stack.
 Exception Type: The throw keyword is followed by an instance of an
exception class. This specifies the type of exception being thrown.
 Usage: It's typically used for exceptional situations that the code cannot handle
on its own. By throwing an exception, you signal to the calling code that an
error has occurred and provide information about the error.

throws:

 Keyword: It's a keyword used in the method signature (declaration).


 Purpose: It declares the exceptions that a method might throw during its
execution. This information is used by the compiler to ensure that the calling
code is prepared to handle these exceptions.
 Exception Types: The throws keyword is followed by a comma-separated
list of exception classes that the method might throw.
 Usage: It's used to inform the caller about potential exceptions that the method
can throw. This allows the caller to handle these exceptions appropriately using
try-catch blocks.

3. Write down name of different exception occurred at time of execution.

Java exceptions are a fundamental mechanism for handling errors and unexpected
situations during program execution. Here are some common exceptions you might
encounter at runtime:

Checked Exceptions:

These exceptions are checked by the Java compiler. The code that throws a checked
exception must either handle the exception using a try-catch block or declare throws
clause in the method signature to propagate the exception to the caller. Some
common checked exceptions include:

 IOException: This exception occurs when there's an error performing


input/output operations, such as file reading or writing.
 FileNotFoundException: A subclass of IOException that specifically denotes
a file that cannot be found.

39
 SQLException: This exception occurs when there's an error interacting with a
database.
 ClassNotFoundException: This exception occurs when the Java runtime
cannot find a specific class definition.

Unchecked Exceptions:

These exceptions are not checked by the compiler. They typically represent
programming errors or unexpected conditions that the code should handle gracefully.
Some common unchecked exceptions include:

 ArithmeticException: This exception occurs when an arithmetic operation


results in an error, such as division by zero.
 NullPointerException: This exception occurs when you attempt to use a null
reference (a variable that doesn't point to any object).
 ArrayIndexOutOfBoundsException: This exception occurs when you try to
access an element of an array that is outside its bounds.
 IndexOutOfBoundsException: A more general exception for accessing
elements outside the valid range of various collections (like lists).
 NumberFormatException: This exception occurs when you try to convert a
string to a numerical value but the format is incorrect.

Other Exceptions:

 RuntimeException: This is a general base class for many unchecked


exceptions. There are many specific subclasses of RuntimeException that
represent different types of errors.
 Error: This class represents serious errors or resource exhaustion that usually
indicate a problem with the program itself or the environment in which it's
running. Errors are typically not recoverable, and the program may terminate
abnormally

4. What is string class in java.

In Java, the String class is a fundamental class that represents a sequence of


characters. It's a core part of the Java API (java.lang package) and is used
extensively for manipulating text data.

Key Characteristics:

40
 Immutable: String objects are immutable, meaning their content cannot be
changed after they are created. Any attempt to modify an existing string results
in the creation of a new string object.
 Object Representation: Strings are treated as objects in Java. This allows you
to use methods and properties associated with the String class.
 Literal vs Object Creation: There are two ways to create strings:
o String literals: Enclosing characters in double quotes ("Hello,
world!") directly creates a string object in the constant pool.
o new String() constructor: You can explicitly create string objects
using the new String() constructor, passing a character array or
another string as input.

5. Write down different string class methods.

Essential Methods:

 length(): Returns the number of characters in the string.


 charAt(int index): Returns the character at the specified index (position)
within the string.
 substring(int startIndex, int endIndex): Extracts a portion of the string as a
new string, starting at the startIndex (inclusive) and ending at endIndex
(exclusive).
 concat(String str): Creates a new string by concatenating (joining) the current
string with the argument string (str). (Remember that strings are immutable, so
the original string remains unchanged.)

Comparison Methods:

 equals(String anotherString): Compares the current string with another string


for equality. It returns true if the strings have the same content, considering
case sensitivity.
 equalsIgnoreCase(String anotherString): Similar to equals(), but performs a
case-insensitive comparison.

Searching and Extraction Methods:

41
 indexOf(String str): Returns the index of the first occurrence of a specified
substring (str) within the current string. If the substring is not found, it returns -
1.
 lastIndexOf(String str): Similar to indexOf(), but returns the index of the last
occurrence of the substring.

Case Conversion Methods:

 toUpperCase(): Returns a new string with all characters converted to


uppercase letters.
 toLowerCase(): Returns a new string with all characters converted to
lowercase letters.

Manipulation Methods:

 trim(): Returns a new string with leading and trailing whitespace characters
removed.
 replace(char oldChar, char newChar): Returns a new string where all
occurrences of a specified character (oldChar) are replaced with another
character (newChar).

Other Useful Methods:

 startsWith(String prefix): Checks if the current string starts with a specified


prefix (prefix) and returns true if it does.
 endsWith(String suffix): Checks if the current string ends with a specified
suffix (suffix) and returns true if it does.
 isBlank(): this method checks if the string is empty or consists only of
whitespace characters and returns true if it is.

42
Assignment 4

1.Difference between multithreading and multiprocessing.

 Multithreading:

 Definition: Multithreading involves running multiple threads within a process.


Threads share the same memory space and resources of the process, including
global variables and open files.
 Communication: Threads can communicate directly with each other since
they share memory.
 Resource Overhead: Generally, threads have less overhead in terms of
resource usage compared to processes because they share resources.
 Concurrency: Multithreading is best suited for I/O-bound tasks or when
multiple threads need to perform tasks simultaneously but share the same
resources.
 Example: Web servers handling multiple client requests simultaneously,
where each request is handled by a separate thread.

 Multiprocessing:

 Definition: Multiprocessing involves running multiple processes


simultaneously. Each process has its own memory space and resources.
 Communication: Inter-process communication (IPC) mechanisms are required
for processes to communicate with each other, which usually have higher
overhead compared to thread communication.
 Resource Isolation: Processes are isolated from each other, meaning they do
not share memory by default.
 Concurrency: Multiprocessing is best suited for CPU-bound tasks or when
tasks need to be completely independent of each other.
 Example: Scientific simulations that can be broken down into independent
tasks and run concurrently across multiple CPU cores.

2.What is java I/O package.

43
The Java I/O (Input/Output) package provides classes and interfaces for performing
input and output operations in Java. It allows Java programs to read from and write to
files, streams, and other I/O sources.

Some key components of the Java I/O package include:

1. Streams: Streams represent a sequence of data. Java I/O supports two types of
streams:
o Byte Streams: Used for handling input and output of bytes. These
streams are suitable for binary data.
o Character Streams: Used for handling input and output of characters.
These streams are suitable for text data and provide character encoding
support.
2. Readers and Writers: These are high-level abstractions built on top of byte
streams to handle character-based I/O operations more efficiently.
3. File I/O: Classes such as File, FileInputStream, FileOutputStream, FileReader,
and FileWriter are used for reading from and writing to files on the file system.
4. Buffered I/O: Buffered streams such as BufferedReader and BufferedWriter
provide buffering capabilities to improve I/O performance by reducing the
number of disk or network operations.
5. Byte Array I/O: Classes such as ByteArrayInputStream and
ByteArrayOutputStream allow reading from and writing to byte arrays in
memory.
6. Serialization: Java I/O package provides support for object serialization and
deserialization through classes like ObjectInputStream and
ObjectOutputStream, allowing objects to be converted into a stream of bytes
for storage or transmission.
7. Character Encoding: Java I/O supports various character encodings through
classes like Charset, CharsetEncoder, and CharsetDecoder, allowing
developers to specify how characters are converted to bytes and vice versa.

3.Difference between FileOutputStream and FileInputStream.

FileOutputStream and FileInputStream are both classes in Java's I/O package


(java.io) used for reading from and writing to files, but they serve different purposes:

1. FileOutputStream:
o Purpose: FileOutputStream is used for writing data to a file.

44
o Functionality: It creates an output stream that writes bytes to a file. If
the file does not exist, it creates a new file; if the file already exists, it
overwrites the existing content.
o Usage: You would typically use FileOutputStream when you need to
write data, such as binary data or raw bytes, to a file.

Example:

try (FileOutputStream fos = new FileOutputStream("output.txt")) {


fos.write("Hello, World!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}

4.Define serialization of object.

Serialization is the process of converting an object into a stream of bytes so that it can be easily
stored, transmitted over a network, or persisted to a file. This byte stream can then be reconstructed
back into an object at a later time. Serialization is commonly used in Java for various purposes such
as data persistence, distributed systems, and inter-process communication.

Key points about object serialization:

1. Object to Byte Stream Conversion: During serialization, the state of an


object (its instance variables) is converted into a byte stream. This includes not
only the object's data but also information about its class and the types of data
stored in its instance variables.
2. Serializable Interface: In Java, for an object to be serializable, its class must
implement the Serializable interface. This interface acts as a marker,
indicating to the Java runtime that objects of this class can be serialized.
3. Transient Fields: Fields marked as transient are not serialized. This is
useful for excluding sensitive or unnecessary data from the serialization
process.
4. Externalizable Interface: Java also provides the Externalizable
interface, which allows more control over the serialization process by letting
the class implement custom serialization logic. Classes implementing
Externalizable must provide methods for reading and writing their state
explicitly.

45
5. Object Deserialization: Deserialization is the reverse process of serialization.
It involves reconstructing an object from the byte stream. During
deserialization, the byte stream is converted back into an object, and its state is
restored.
6. Versioning and Compatibility: Care must be taken to ensure that changes to
serialized classes do not break compatibility with existing serialized objects.
Java provides mechanisms such as serialVersionUID and versioning to
handle this.

Example:

import java.io.*;

public class SerializationExample {

public static void main(String[] args) {

// Object to serialize

Person person = new Person("John", 30);

// Serialize the object

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("person.ser"))) {

oos.writeObject(person);

System.out.println("Object serialized successfully.");

} catch (IOException e) {

e.printStackTrace();

// Deserialize the object

try (ObjectInputStream ois = new ObjectInputStream(new


FileInputStream("person.ser"))) {

Person deserializedPerson = (Person) ois.readObject();


46
System.out.println("Object deserialized successfully: " + deserializedPerson);

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

class Person implements Serializable {

private static final long serialVersionUID = 1L;

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

@Override

public String toString() {

return "Person{name='" + name + "', age=" + age + '}';

47
Assignment 5
1. Define JDBC.
Define JDBC: JDBC stands for Java Database Connectivity. It is a Java API that
allows Java programs to interact with databases. JDBC provides a standard
interface for connecting to relational databases, executing SQL queries, and
processing the results. It enables Java applications to perform operations such
as inserting, updating, deleting, and querying data in a database. JDBC
consists of a set of classes and interfaces in the java.sql package and its
subpackages.

2. Why we use collection framework in java.

The collection framework in Java provides a set of classes and interfaces to store,
manipulate, and process groups of objects. It offers several benefits:

 Convenience: Collections provide easy-to-use data structures like lists, sets,


maps, etc., which simplify programming tasks.
 Efficiency: The collection framework offers efficient implementations of
common data structures, optimized for performance and memory usage.
 Type Safety: Generics in the collection framework ensure type safety,
reducing the chance of runtime errors.
 Flexibility: Collections can store objects of different types, allowing for
flexible data manipulation and processing.
 Interoperability: Collections can be easily integrated with other Java APIs
and libraries, facilitating development.

3. Define run time memory management in java.

Runtime memory management in Java refers to the process of allocating and


deallocating memory for objects during the execution of a Java program. It involves
the Java Virtual Machine (JVM) managing memory resources dynamically while the
program is running. Key aspects of runtime memory management include:

 Automatic Memory Management: Java uses automatic memory management


through garbage collection, where the JVM automatically deallocates memory
for objects that are no longer referenced.

48
 Heap Memory: Objects in Java are typically allocated memory on the heap, a
region of memory dedicated to storing objects.
 Garbage Collection: The JVM periodically identifies and removes
unreferenced objects from memory to reclaim memory resources. Garbage
collection algorithms vary in different JVM implementations.
 Memory Leaks: Proper memory management is essential to avoid memory
leaks, where objects are unintentionally retained in memory, consuming
resources and potentially leading to out-of-memory errors

4. Steps of JDBC to connect with database.


 Load the JDBC Driver: Use Class.forName() to dynamically load the JDBC
driver class.
 Establish Connection: Use DriverManager.getConnection() to establish a
connection to the database, providing the database URL, username, and
password.
 Create Statement/PreparedStatement/CallableStatement: Create a
statement, prepared statement, or callable statement to execute SQL queries or
commands.
 Execute SQL Queries: Use the created statement to execute SQL queries or
commands against the database.
 Process Results: Process the results returned by the database, if any, such as
retrieving data from ResultSet objects.
 Close Resources: Close the statement, connection, and any other JDBC
resources using close() method to release database and JDBC resources.

5. Define wrapper class.

In Java, a wrapper class is a class that encapsulates (wraps) primitive data


types into objects. Java provides wrapper classes for each of the primitive
data types (byte, short, int, long, float, double, char, boolean),
allowing them to be treated as objects. Wrapper classes are useful when
working with collections, as collections typically store objects rather than
primitives. The wrapper classes also provide utility methods for converting
between primitive data types and their corresponding wrapper objects, as
well as for performing various operations on the data. For example,
Integer, Double, Boolean, etc., are wrapper classes for int, double,
boolean, etc., respectively.

49
50

You might also like