0% found this document useful (0 votes)
36 views15 pages

Java Programming Experiments Guide

Uploaded by

Manish Verma
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)
36 views15 pages

Java Programming Experiments Guide

Uploaded by

Manish Verma
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

Content Page

S. No. Experiment Title

1 Use Java Compiler and Eclipse Platform to Write and Execute Java Program

2 Create Java Program using Command Line Arguments

3 Understand OOP Concepts and Basics of Java Programming

4 Create Java Programs using Inheritance and Polymorphism

5 Implement Error Handling using Exception Handling and Multithreading

6 Create Java Programs using Packages

7 Construct Java Programs using Java I/O Package

8 Create Industry-Oriented Application using Spring Framework

9 Test RESTful Web Services using Spring Boot

10 Test Frontend Web Application with Spring Boot


Experiment No. 1 – Use Java Compiler and Eclipse Platform to Write and Execute Java
Program

Aim:

To write, compile, and execute a simple Java program using Java compiler and Eclipse IDE.

Tools Required:

 JDK (Java Development Kit)

 Eclipse IDE

Procedure:

1. Open Eclipse IDE and create a new Java project.

2. Create a new Java class file ([Link]).

3. Write a basic Java program using main() method.

4. Save the program and click Run to compile and execute.

Sample Code:

public class HelloWorld {

public static void main(String[] args) {

[Link]("Hello, World!");

Output:

Hello, World!

Conclusion:

A Java program was successfully written, compiled, and executed using Eclipse IDE, verifying
basic setup and understanding of Java environment.
Experiment No. 2 – Create Java Program using Command Line Arguments

Aim:

To create a Java program that accepts input through command line arguments.

Tools Required:

 JDK

 Command Prompt / Terminal

Procedure:

1. Open any text editor and write the Java program.

2. Save it as [Link].

3. Open terminal, compile using javac, and run using java followed by arguments.

Sample Code:

public class CommandLineDemo {

public static void main(String[] args) {

for (int i = 0; i < [Link]; i++) {

[Link]("Argument " + i + ": " + args[i]);

Execution:

javac [Link]

java CommandLineDemo Hello Java World

Output:

Argument 0: Hello

Argument 1: Java
Argument 2: World

Conclusion:

Java programs can accept inputs at runtime using command line arguments, which are
accessible through the args[] array in the main() method.

Experiment No. 3 – Understand OOP Concepts and Basics of Java Programming

Aim:

To understand and implement basic Object-Oriented Programming concepts using Java.

Tools Required:

 JDK

 Eclipse IDE or any text editor

Procedure:

1. Create a Java class with fields and methods.

2. Demonstrate OOP principles like Class, Object, Encapsulation, and Method Calling.

3. Compile and run the program.

Sample Code:

class Student {

String name;

int age;

void display() {

[Link]("Name: " + name + ", Age: " + age);

}
public class TestStudent {

public static void main(String[] args) {

Student s = new Student();

[Link] = "Rahul";

[Link] = 20;

[Link]();

Output:

Name: Rahul, Age: 20

Conclusion:

Basic OOP principles such as class creation, object instantiation, and encapsulation were
successfully implemented in Java.

Experiment No. 4 – Create Java Programs using Inheritance and Polymorphism

Aim:

To implement Inheritance and Polymorphism in Java.

Tools Required:

 JDK

 Any Java IDE or text editor

Procedure:

1. Create a base class and a derived class to demonstrate inheritance.


2. Override a method in the derived class to show runtime polymorphism.

3. Compile and execute the program.

Sample Code:

class Animal {

void sound() {

[Link]("Animal makes sound");

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

public class TestPolymorphism {

public static void main(String[] args) {

Animal a = new Dog(); // Runtime polymorphism

[Link]();

Output:

Dog barks

Conclusion:

Inheritance allows one class to acquire properties of another, and polymorphism enables
method overriding, which was successfully implemented using dynamic method dispatch.
Experiment No. 5 – Implement Error Handling using Exception Handling and Multithreading

Aim:

To implement exception handling and multithreading in Java.

Tools Required:

 JDK

 Any Java IDE or text editor

Procedure:

1. Write code using try, catch, and finally blocks for exception handling.

2. Create and run multiple threads using the Thread class.

3. Compile and execute the program.

Sample Code:

class MyThread extends Thread {

public void run() {

[Link]("Thread is running: " + getName());

public class ExceptionAndThreadDemo {

public static void main(String[] args) {

try {

int a = 5 / 0;

} catch (ArithmeticException e) {

[Link]("Exception caught: " + e);

MyThread t1 = new MyThread();


[Link]();

Output:

Exception caught: [Link]: / by zero

Thread is running: Thread-0

Conclusion:

Java provides built-in support for handling runtime errors using exception handling, and
multithreading enables concurrent execution of code, both of which were successfully
demonstrated.

Experiment No. 6 – Create Java Programs using Packages

Aim:

To create and use packages in Java for modular programming.

Tools Required:

 JDK

 Any Java IDE or terminal

Procedure:

1. Create a Java file with a package declaration.

2. Save it inside a folder named as the package.

3. Compile using javac -d . [Link].

4. Import and use the package in another class.

Sample Code:

File: mypack/[Link]

package mypack;
public class Message {

public void show() {

[Link]("Hello from Package!");

File: [Link]

import [Link];

public class TestPackage {

public static void main(String[] args) {

Message m = new Message();

[Link]();

Output:

Hello from Package!

Conclusion:

Packages in Java help organize classes and interfaces into namespaces, improving code
maintainability and modularity.

Experiment No. 7 – Construct Java Programs using Java I/O Package

Aim:

To perform file input and output operations using Java I/O package.

Tools Required:
 JDK

 Any Java IDE or text editor

Procedure:

1. Import [Link].* package.

2. Use FileWriter to write data into a file.

3. Use FileReader to read data from the file.

4. Compile and run the program.

Sample Code:

import [Link].*;

public class FileIODemo {

public static void main(String[] args) throws IOException {

FileWriter fw = new FileWriter("[Link]");

[Link]("Hello Java I/O");

[Link]();

FileReader fr = new FileReader("[Link]");

int i;

while ((i = [Link]()) != -1)

[Link]((char) i);

[Link]();

Output:

Hello Java I/O

Conclusion:
Java I/O package provides classes to read from and write to files, allowing basic file handling
operations like reading, writing, and closing file streams.

Experiment No. 8 – Create Industry-Oriented Application using Spring Framework

Aim:

To create a basic Spring Framework application demonstrating dependency injection.

Tools Required:

 Spring Framework

 Java IDE (e.g., Eclipse/IntelliJ)

 Maven/Gradle (build tool)

Procedure:

1. Create a Java project with Spring dependencies.

2. Define a simple component class and a service class.

3. Use @Component, @Autowired, and @Configuration annotations.

4. Initialize context using AnnotationConfigApplicationContext.

5. Run and observe the injected output.

Sample Code:

@Component

class HelloService {

public void sayHello() {

[Link]("Hello from Spring!");

@Configuration
@ComponentScan("[Link]")

class AppConfig {}

public class MainApp {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext([Link]);

HelloService hs = [Link]([Link]);

[Link]();

[Link]();

Output:

Hello from Spring!

Conclusion:

Spring Framework simplifies Java development by providing built-in support for dependency
injection and component management, making applications more modular and maintainable.

Experiment No. 9 – Test RESTful Web Services using Spring Boot

Aim:

To develop and test a basic RESTful API using Spring Boot.

Tools Required:

 Spring Boot

 IDE (Eclipse/IntelliJ)

 Postman or browser

Procedure:
1. Create a Spring Boot project using Spring Initializr with Spring Web dependency.

2. Create a REST controller using @RestController.

3. Map a GET request using @GetMapping.

4. Run the application and test the endpoint using Postman or browser.

Sample Code:

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello() {

return "Hello from REST API!";

Application runs at:

[Link]

Output:

Hello from REST API!

Conclusion:

Spring Boot makes it easy to create REST APIs. Using @RestController and annotations like
@GetMapping, web services can be tested quickly and effectively.
Experiment No. 10 – Test Frontend Web Application with Spring Boot

Aim:

To test a simple frontend web application built using Spring Boot and Thymeleaf or HTML
templates.

Tools Required:

 Spring Boot

 IDE (Eclipse/IntelliJ)

 Browser

Procedure:

1. Create a Spring Boot project with Spring Web and Thymeleaf dependencies.

2. Create an HTML page inside src/main/resources/templates/.

3. Create a controller to map the HTML page using @Controller and @GetMapping.

4. Run the application and test the UI in browser.

Sample Code:

[Link]

@Controller

public class HelloController {

@GetMapping("/home")

public String homePage() {

return "index"; // returns [Link]

[Link] (in templates folder)

<!DOCTYPE html>

<html>

<head><title>Home</title></head>
<body>

<h1>Welcome to Spring Boot Web App!</h1>

</body>

</html>

Run on:

[Link]

Output:

Browser displays:

Welcome to Spring Boot Web App!

Conclusion:

Spring Boot with Thymeleaf allows easy integration of backend with frontend, enabling full-
stack web development using Java.

Common questions

Powered by AI

Fundamental OOP principles demonstrated in a basic Java program include encapsulation, class creation, and object instantiation. Encapsulation is showcased by defining attributes and methods within a class, controlling access via public or private access modifiers as needed. Class creation involves defining the blueprint of an object, while object instantiation refers to creating an instance of that class. For example, in a basic Java program: class Student { String name; int age; void display() { System.out.println("Name: " + name + ", Age: " + age); } } Here, 'Student' is a class with encapsulation shown by fields 'name' and 'age'. The 'display()' method is also encapsulated within the class, demonstrating encapsulation, while 'TestStudent' instantiates 'Student' class .

Exception handling in Java is implemented using try, catch, and finally blocks. This helps manage runtime errors gracefully, preventing program crashes. A try block encloses code that might throw an exception; catch blocks are for handling specific exceptions; and finally defines code that executes post-try/catch regardless of an exception. Multithreading permits concurrent execution using the Thread class or Runnable interface. Threads allow programs to perform multiple operations simultaneously, improving performance. For instance: class MyThread extends Thread { public void run() { System.out.println("Thread is running: " + getName()); } } public class ExceptionAndThreadDemo { public static void main(String[] args) { try { int a = 5 / 0; // raises ArithmeticException } catch (ArithmeticException e) { System.out.println("Exception caught: " + e); } MyThread t1 = new MyThread(); t1.start(); } } This example catches division by zero errors and initiates a new thread, demonstrating how exceptions are handled and threads are spawned in Java .

The Spring Framework greatly simplifies Java application development through dependency injection (DI), a core concept where objects do not create their dependencies but are passed them. This promotes loose coupling, making systems more modular and easier to manage or test. Spring achieves DI using annotations like @Component, @Autowired, and @Configuration, along with an IoC container that manages bean lifecycles. For instance, Spring automatically injects dependencies using configuration classes and scans components within specified packages: @Component class HelloService { public void sayHello() { System.out.println("Hello from Spring!"); } } @Configuration @ComponentScan("com.example") class AppConfig {} public class MainApp { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); HelloService hs = context.getBean(HelloService.class); hs.sayHello(); context.close(); } } Output is 'Hello from Spring!'. The framework's flexible configuration reduces boilerplate code and enhances manageability .

The steps to write, compile, and execute a simple Java program using Eclipse IDE include: 1. Open Eclipse and create a new Java project. 2. Create a new Java class file, e.g., HelloWorld.java. 3. Write the Java code inside the main() method. 4. Save the program and click Run to compile and execute. Sample code of the program is: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } The output of this program will be 'Hello, World!' .

Command line argument handling in Java programs involves accepting user inputs at runtime using the 'args' array in the main() method. Each argument passed to the program corresponds to an element in the 'args' array. For instance, if the program is executed as 'java CommandLineDemo Hello Java World', each word will be treated as a separate argument. In the provided sample code, this looks like: public class CommandLineDemo { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("Argument " + i + ": " + args[i]); } } } The output is: Argument 0: Hello Argument 1: Java Argument 2: World This method allows flexible input handling without hardcoding values .

Packages in Java provide a namespace mechanism that helps organize classes and interfaces logically. They enhance modularity by grouping related classes and interfaces, which simplifies code management, enhances readability, and reduces naming conflicts. For example, a package declaration precedes a class definition, and the Java file is placed in a corresponding directory structure. Sample procedure: 1. Declare a package at the top of a Java source file: 'package mypack;'. 2. Save this file inside a directory named 'mypack'. 3. Compile with 'javac -d . FileName.java' to generate a directory structure matching the package. 4. Access the package in another class using 'import mypack.ClassName;'. A basic demonstration: package mypack; public class Message { public void show() { System.out.println("Hello from Package!"); } } Test code: import mypack.Message; public class TestPackage { public static void main(String[] args) { Message m = new Message(); m.show(); } } This setup outputs 'Hello from Package!', reinforcing how packages facilitate modular design .

Spring Boot streamlines the development and testing of RESTful web services by using pre-configured templates, reducing setup time. It efficiently manages dependencies through tools like Spring Initializr and supports various annotations to simplify REST API creation. The framework automates many infrastructural concerns such as embedding servers, auto configuration, and metrics. Here is a basic implementation process: 1. Create a Spring Boot project via Spring Initializr, including the Spring Web dependency. 2. Define REST endpoints using controllers marked with @RestController. 3. Map HTTP methods (e.g., GET) to methods using @RequestMapping or @GetMapping. An example: @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello from REST API!"; } } This service runs on 'http://localhost:8080/hello', returning 'Hello from REST API!'. Spring Boot facilitates rapid prototyping and instant endpoint testing using tools like Postman, thereby enhancing developer productivity .

Inheritance and polymorphism are key OOP concepts that foster code reusability and flexibility in Java. Inheritance allows a class (called derived or child) to inherit attributes and methods from another class (called base or parent). This reduces code duplication and promotes reuse. Polymorphism allows a single method to behave differently based on the object that it acts upon, making the system more flexible and modular. For example: class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } The 'Animal' class is the parent class and 'Dog' is a child class that inherits from it. Polymorphism is demonstrated by overriding the 'sound()' method in the 'Dog' class, allowing different sound outputs even when using an 'Animal' type reference: Animal a = new Dog(); a.sound(); This outputs "Dog barks" showing polymorphism via dynamic method dispatch, enhancing system flexibility .

Spring Boot combined with Thymeleaf supports full-stack web application development by integrating backend logic with frontend rendering seamlessly. Thymeleaf serves as the templating engine, allowing dynamic HTML content generation directly from server-side Java objects. The integration involves: 1. Configuring a Spring Boot project to include Spring Web and Thymeleaf dependencies. 2. Creating HTML templates (.html) within 'src/main/resources/templates'. 3. Developing controllers using Spring's @Controller and @GetMapping annotations to handle HTTP requests and route to different template views. For example: @Controller public class HelloController { @GetMapping("/home") public String homePage() { return "index"; // returns index.html } } The HTML page (index.html) is returned as the view when '/home' is accessed using a browser. This leads to a UI rendering saying 'Welcome to Spring Boot Web App!' at 'http://localhost:8080/home'. Thus, Thymeleaf integrates smoothly with Spring to deliver cohesive and responsive web applications, leveraging Spring's feature-rich environment .

The Java I/O package provides classes essential for basic file handling operations, such as reading from and writing to files, enhancing data persistence capabilities in Java programs. Key benefits include ease of use, flexibility in reading/writing different data forms, and built-in error handling mechanisms. For instance, 'FileWriter' allows text to be written, while 'FileReader' facilitates reading text data efficiently. An example: import java.io.*; public class FileIODemo { public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("output.txt"); fw.write("Hello Java I/O"); fw.close(); FileReader fr = new FileReader("output.txt"); int i; while ((i = fr.read()) != -1) System.out.print((char) i); fr.close(); } } This code writes and then reads text from 'output.txt', effectively demonstrating flexibility and ease of use in file operations, with automatic resource management enhancing reliability .

You might also like