0% found this document useful (0 votes)
8 views24 pages

Java OOP Laboratory Manual 2024-2025

This laboratory manual for the Bachelor of Technology in Computer Science and Engineering outlines various experiments focused on Object Oriented Programming with Java for the session 2024-2025. It includes exercises on fundamental concepts such as inheritance, abstraction, encapsulation, method overloading, and exception handling. Each experiment provides a program to be written along with expected outputs, facilitating hands-on learning of Java programming techniques.

Uploaded by

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

Java OOP Laboratory Manual 2024-2025

This laboratory manual for the Bachelor of Technology in Computer Science and Engineering outlines various experiments focused on Object Oriented Programming with Java for the session 2024-2025. It includes exercises on fundamental concepts such as inheritance, abstraction, encapsulation, method overloading, and exception handling. Each experiment provides a program to be written along with expected outputs, facilitating hands-on learning of Java programming techniques.

Uploaded by

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

Object Oriented

Programming with Java


(BCS-452)
LABORATORY MANUAL
FOR
Bachelor of Technology
In
Computer Science and Engineering
Session: 2024-2025
(Roll No: 2300951530002)

MGM'S COLLEGE OF ENGINEERING &


TECHNOLOGY
A-09, Sec-62, NOIDA, U.P
Experiment - 1
Write a program to print Hello World.

Program:

Output:
Understand OOPS Concept and Basic Java Programs

Experiment - 2
Write a Java program to illustrate the concept of inheritance
base class.

Program:
Output:
Experiment - 3
Write a program Java Program to Illustrate, Invocation of
Constructor, Calling Without Usage of super Keyword.

Program:
Output:
Abstraction In Java
Experiment - 4
Write a Java program to illustrate Abstraction.

Program:
Output:
Encapsulation in JAVA

Experiment - 5
Java Program to demonstrate Java Encapsulation.

Program:
Output:
Experiment - 6
Write a Java Program for Method overloading By using
Different Types of Arguments.

Program:

Output:
Java Interfaces
Experiment - 7​
Write a java program to demonstrate how diamond problems are
handled in case of default methods.

Program:
Output:
Experiment - 8
Write a program to access Packages in java.

Program:
Exception Handling
Experiment - 9
Java Program to Illustrate Exception Handling with Method
Overriding.

Case 1:
Output:
Case 2:
If SuperClass doesn’t declare any exception and SubClass declare
Unchecked exception:

Experiment - 10
Program:
Output:
Experiment - 11
Java program to illustrate standard input output streams.

Program:
Output:
Experiment - 12
Write a Program to Implementing WebApplicationInitializer
using Spring.

Program:

Common questions

Powered by AI

In Java, constructors can invoke other constructors within the same class (known as constructor chaining) without using the 'super' keyword by using 'this()' instead. 'This()' calls another constructor in the same class. Here is an example illustrating constructor chaining: ``` class Base { Base() { this(10); System.out.println("Default constructor"); } Base(int x) { System.out.println("Parameterized constructor with value: " + x); } } public class TestConstructor { public static void main(String[] args) { new Base(); } } ``` In this example, the default constructor calls a parameterized constructor of the same class using 'this(10)', allowing different constructions within the same class without using 'super'.

The diamond problem in Java arises when a class inherits from multiple classes that share a common base class, leading to ambiguity in which base class implementation is used. Although Java does not support multiple inheritance of classes, interfaces can still create a similar scenario. This is mitigated using default methods in interfaces. Default methods provide a way for interfaces to offer method implementations. In cases where multiple interfaces provide the same default methods, the class implementing the interfaces must explicitly override the conflicting method, thereby resolving the ambiguity. For example: ``` interface A { default void display() { System.out.println("A"); } } interface B { default void display() { System.out.println("B"); } } class C implements A, B { @Override public void display() { A.super.display(); // Resolution } } ``` In this case, class `C` resolves the ambiguity by explicitly using the `display()` method from interface `A`.

Inheritance in Java allows a new class, called a subclass, to inherit the properties and behavior (methods) of another class, referred to as a superclass or base class. This promotes code reuse and establishes a natural hierarchy between classes. For example, consider a base class `Animal` with a method `eat()`. A subclass `Dog` can be created which inherits `eat()` and can have additional methods like `bark()`. Here is a simple illustration: ``` class Animal { void eat() { System.out.println("Eating..."); } } class Dog extends Animal { void bark() { System.out.println("Barking..."); } } public class TestInheritance { public static void main(String args[]) { Dog d = new Dog(); d.eat(); d.bark(); } } ```

In Java, exception handling involves managing errors using try-catch blocks, and it's integrated within method overriding—the method signature in a subclass must conform to those in the superclass. When a superclass method does not declare checked exceptions, the subclass method cannot throw checked exceptions. However, the subclass method may declare unchecked exceptions (RuntimeException and its subclasses). Unchecked exceptions do not require mandatory handling and do not affect overriding. For example, if a superclass method does not declare any exceptions, a subclass may override it and declare an unchecked exception like this: ``` class SuperClass { void display() { System.out.println("SuperClass display"); } } class SubClass extends SuperClass { @Override void display() throws ArithmeticException { System.out.println("SubClass display with an Unchecked Exception"); } } ``` Although `SubClass#display()` declares an unchecked `ArithmeticException`, the code compiles and executes without mandatory exception handling or affecting the overriding functionality, illustrating flexible exception handling in subclass methods.

Method overloading in Java occurs when two or more methods in the same class have the same name but different parameters (different type or number of parameters). This allows each method to perform different operations based on the input argument types. For instance: ``` class Display { void show(int num) { System.out.println("Number: " + num); } void show(String message) { System.out.println("Message: " + message); } } public class TestOverloading { public static void main(String[] args) { Display obj = new Display(); obj.show(25); obj.show("Hello"); } } ``` In this example, `show()` is overloaded with different parameter types, allowing it to handle integer and string inputs differently.

Java Standard I/O streams are critical for handling input and output operations in applications, facilitating character and byte data flow between the program and the external environment (like files or network sockets). Java provides InputStream and OutputStream classes for byte-based operations, and Reader and Writer classes for character-based input/output. These streams support various operations like reading, writing, buffering, and filtering data, thus allowing developers to manage read operations (like receiving user input), write operations (like displaying output), and external file manipulations seamlessly. For instance, using `BufferedReader` for efficient reading of characters in contrast to unbuffered reading, significantly boosts performance: ``` BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter data: "); String data = br.readLine(); System.out.println("Data entered: " + data); ``` This example efficiently reads text input from the user using `BufferedReader` to buffer characters, thereby improving I/O operation performance compared to using unbuffered reading classes. Java I/O streams facilitate scalable application development by abstracting complex I/O operations, offering a straightforward API to interact with diverse input and output resources.

Encapsulation in Java improves software development by enhancing modularity, maintainability, and data integrity. It involves bundling data (variables) and the methods that manipulate this data into a single unit or class and restricting the direct access of some components (e.g., using private access modifiers). This control over data is demonstrated through getter and setter methods, which provide controlled access to the private variables. This ensures that objects cannot be in inconsistent states and that unexpected changes are prevented. Encapsulation facilitates debugging and testing since each class can be tested independently. Here is a Java illustration: ``` class BankAccount { private int balance; public int getBalance() { return balance; } public void deposit(int amount) { if (amount > 0) { balance += amount; } } public void withdraw(int amount) { if (amount > 0 && balance >= amount) { balance -= amount; } } } ``` This example demonstrates data encapsulation, preventing direct access to `balance`, while providing methods to safely modify the data.

Interfaces in Java are fundamental for implementing polymorphism and resolving issues associated with multiple inheritance, such as the diamond problem. Polymorphism allows objects to be treated as instances of their parent interface, promoting flexible and reusable code. Interfaces allow different classes to implement methods defined in the interfaces, ensuring a contract for behavior but allowing each class to provide its implementation. When multiple interfaces are implemented by a single class, the problem of method conflicts is resolved by requiring the class to provide specific implementations for any conflicting default methods, allowing controlled multiple inheritance scenarios via polymorphism. For example: ``` interface Drawable { void draw(); // abstract method } interface Paintable { default void draw() { System.out.println("Paintable draw method"); } } class Circle implements Drawable, Paintable { @Override public void draw() { System.out.println("Drawing a circle"); } } public class TestInterfacePolymorphism { public static void main(String[] args) { Drawable d = new Circle(); d.draw(); // Calls Circle's draw } } ``` Here, `Circle` implements both `Drawable` and `Paintable`. The `draw()` method is overridden in `Circle` to resolve any potential conflict and demonstrate polymorphism by allowing a single `draw()` method to be customized for different implementations.

The Spring Framework's WebApplicationInitializer simplifies creating web applications by eliminating the need for web.xml-based configurations and instead, programmatically configuring the servlet context. This approach, introduced with Servlet 3.0+, enhances module system resilience and allows annotation-based configurations, leading to more manageable codebases. This method provides greater flexibility, improves startup time with on-demand initialization, and supports enhanced component scanning capabilities which are cumbersome to manage with XML configurations. Using `WebApplicationInitializer`, developers achieve streamlined setups, decoupling the application from the tedious XML deployment descriptors, and enabling dynamic servlet mappings and listener configurations directly in Java classes. This programmatic configuration approach aligns with the Spring Framework's emphasis on convention over configuration and eases integration with modern deployment technologies. Here is a basic implementation of `WebApplicationInitializer`: ``` public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(AppConfig.class); ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); } } ``` In this example, `MyWebAppInitializer` configures the application context and maps the dispatcher servlet, enabling a more flexible and code-centric setup of Spring applications. This declarative method aligns with current development practices favoring less XML and more code, streamlining enterprise application development.

Abstraction in Java focuses on hiding the complex implementation details and showing only the essential features of an object. This is typically achieved through abstract classes and interfaces. Encapsulation, on the other hand, is about bundling the data (variables) and methods that operate on the data into a single unit, and restricting access to the details. This is done by using private variables and providing public getter and setter methods. Abstraction helps in reducing code complexity, while encapsulation helps in protecting the integrity of data by restricting unauthorized access and modification. Together, they promote clean, modular, and maintainable code.

You might also like