0% found this document useful (0 votes)
2 views20 pages

Java_file_final

The document outlines a series of Java programming experiments, each with specific objectives and sample code. It covers fundamental concepts such as escape sequences, command-line arguments, classes, inheritance, exception handling, file I/O, Spring-based applications, RESTful services, and frontend integration with Thymeleaf. Each experiment includes program code and expected output, demonstrating practical applications of Java programming techniques.

Uploaded by

deadendrider78
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)
2 views20 pages

Java_file_final

The document outlines a series of Java programming experiments, each with specific objectives and sample code. It covers fundamental concepts such as escape sequences, command-line arguments, classes, inheritance, exception handling, file I/O, Spring-based applications, RESTful services, and frontend integration with Thymeleaf. Each experiment includes program code and expected output, demonstrating practical applications of Java programming techniques.

Uploaded by

deadendrider78
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
You are on page 1/ 20

Experiment No.

Objective: Write a simple Java program using Eclipse IDE to display the message "Hello, Java
World from Eclipse!" on the console, also use all major escape sequences including \n
(newline), \t (tab), \\ (backslash), \" (double quote), \' (single quote), and \r (carriage return).
The program should demonstrate the basic structure of a Java application including the main()
method and System.out.println() function for output.

Program:

public class EscapeSequenceExample {


public static void main(String[] args) {
// Displaying a welcome message
System.out.println("Greetings from Eclipse using Java!");

// Demonstrating newline (\n)


System.out.println("\nThis text appears on the next line.");

// Demonstrating tab (\t)


System.out.println("Student:\tMandy Smith");
System.out.println("ID No.:\t\t202");

// Demonstrating backslash (\\)


System.out.println("Installation path: D:\\Software\\Java\\bin");

// Demonstrating double quote (\")


System.out.println("The instructor said, \"Practice makes perfect.\"");

// Demonstrating single quote (\')


System.out.println("Don\'t skip your Java lessons!");

// Demonstrating carriage return (\r)


System.out.println("Java programming is cool!\rNote: ");
// The \r will bring cursor back to the beginning of the line.
}
}

Page | 1
OUTPUT:-

Greetings from Eclipse using Java!

This text appears on the next line.


Student: Mandy Smith
ID No.: 202
Installation path: D:\Software\Java\bin
The instructor said, "Practice makes perfect."
Don't skip your Java lessons!
Note: Programming is cool!

Page | 2
Experiment No. 2

Objective: Write a Java program that accepts two integer numbers as command-line
arguments, calculates their sum, and displays the result. Ensure that the program properly
parses the command-line arguments and handles basic integer operations.

Program:

public class SumFromCommandLine {


public static void main(String[] args) {
// Ensure exactly two arguments are passed
if (args.length < 2) {
System.out.println("Error: Two integer inputs are required as command-line
arguments.");
return;
}

try {
// Convert input strings to integers
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);

// Compute the total


int total = firstNumber + secondNumber;

// Print the outcome


System.out.println("The total of " + firstNumber + " and " + secondNumber + " is: " +
total);
} catch (NumberFormatException ex) {
System.out.println("Invalid input! Please enter valid whole numbers.");
}
}
}

Page | 3
OUTPUT:

Command-line args: 12 7
Sum: 19

Page | 4
Experiment No. 3

Objective: Write a Java program to create two classes: Student and Rectangle.
• The student class should have two data members: name and rollNo, with a method
to display the student's details.
• The Rectangle class should have two data members: length and width, with a
method to calculate and display the area of the rectangle.
Create objects for both classes, assign values to the data members, and invoke their
respective methods to display the output.

Program:

class Learner {
String fullName;
int studentId;

Learner(String fullName, int studentId) {


this.fullName = fullName;
this.studentId = studentId;
}

void showInfo() {
System.out.println("Learner Name: " + fullName);
System.out.println("Student ID: " + studentId);
}
}

class ShapeRectangle {
double height;
double breadth;

ShapeRectangle(double height, double breadth) {


this.height = height;
this.breadth = breadth;
}

void showArea() {
double area = height * breadth;
System.out.println("Area of Rectangle: " + area);
}
}

public class Main {


public static void main(String[] args) {

Page | 5
Learner learner1 = new Learner("Bob", 202);
learner1.showInfo();

System.out.println();

ShapeRectangle rect1 = new ShapeRectangle(7.0, 4.5);


rect1.showArea();
}
}

OUTPUT:-

Learner Name: Bob


Student ID: 202

Area of Rectangle: 31.5

Page | 6
Experiment No. 4

Objective: Write a Java program to demonstrate the concepts of inheritance and


polymorphism:
• Create two classes, Animal and Dog, where Dog inherits from Animal to
demonstrate single-level inheritance.
• Override a method in the Dog class to demonstrate method overriding (runtime
polymorphism).
• Implement method overloading within the Dog class by creating multiple
versions of a bark() method with different parameters to demonstrate compile-
time polymorphism.
The program should create objects of the classes and invoke the methods to show the
behavior of inheritance, method overriding, and method overloading.

Program:

class Creature {
void sound() {
System.out.println("The creature produces a sound.");
}
}

class Puppy extends Creature {


@Override
void sound() {
System.out.println("The puppy howls.");
}

void howl() {
System.out.println("Puppy is howling softly.");
}

void howl(String style) {


System.out.println("Puppy is howling in a " + style + " manner.");
}

void howl(int count) {


System.out.println("Puppy howled " + count + " times.");
}
}

public class Main {


public static void main(String[] args) {
Creature wildCreature = new Creature();
Page | 7
Creature petPuppy = new Puppy();

wildCreature.sound();
petPuppy.sound();

Puppy myPuppy = new Puppy();


myPuppy.howl();
myPuppy.howl("energetic");
myPuppy.howl(5);
}
}

OUTPUT:-

The creature produces a sound.


The puppy howls.
Puppy is howling softly.
Puppy is howling in a energetic manner.
Puppy howled 5 times.

Page | 8
Experiment No. 5

Objective: Write a Java program that demonstrates exception handling using try,
catch, and finally blocks to handle arithmetic exceptions. Extend the program to
implement multithreading by creating and running two threads that print a message
concurrently.

Program:

class Demo {
void divide(int a, int b) {
try {
System.out.println("Result: " + (a / b));
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Division done.");
}
}
}

class MyThread extends Thread {


String name;
MyThread(String name) { this.name = name; }
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(name + " running: " + i);
try { Thread.sleep(400); } catch (InterruptedException e) {}
}
}
}

public class Main {


public static void main(String[] args) throws InterruptedException {
Demo d = new Demo();
d.divide(10, 2);
d.divide(10, 0);

Thread t1 = new MyThread("Thread1");


Thread t2 = new MyThread("Thread2");
t1.start();
t2.start();

t1.join();
Page | 9
t2.join();

System.out.println("Main finished.");
}
}

OUTPUT:-

Result: 5
Division done.
Cannot divide by zero.
Division done.
Thread2 running: 0
Thread1 running: 0
Thread2 running: 1
Thread1 running: 1
Thread2 running: 2
Thread1 running: 2
Main finished.

Page | 10
Experiment No. 6

Objective: Write a Java program that creates a user-defined package named


studentinfo, containing a class Student with basic details. In another class, import this
package and display the student information, demonstrating the use of Java packages
for modular development.

Program:

class Student {
String name;
int rollNo;
String department;

public Student(String name, int rollNo, String department) {


this.name = name;
this.rollNo = rollNo;
this.department = department;
}

public void showDetails() {


System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + rollNo);
System.out.println("Department: " + department);
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student("Mandy", 202, "Computer Science");
s.showDetails();
}
}

Page | 11
OUTPUT:

Student Name: Mandy


Roll Number: 202
Department: Computer Science

Page | 12
Experiment No. 7

Objective: Write a Java program that uses Java I/O streams to read data from a text
file and write data to another text file. The program should demonstrate file reading
using FileReader and writing using FileWriter, along with proper exception handling.

Program:

import java.io.*;

public class FileCopyDemo {


public static void main(String[] args) {
try {
// Write some content to input.txt (simulating file presence)
FileWriter fw = new FileWriter("input.txt");
fw.write("Hello, this is a sample input file.\nJava file I/O is working!");
fw.close();

// Now read from input.txt and write to output.txt


FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");

int ch;
while ((ch = reader.read()) != -1) {
writer.write(ch);
}

reader.close();
writer.close();

System.out.println("Content successfully copied from input.txt to output.txt");


} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Page | 13
OUTPUT:-

Content successfully copied from input.txt to output.txt

Page | 14
Experiment No. 8

Objective: Create a simple Spring-based Java application using annotation-based


configuration. The program should demonstrate dependency injection and include a
service class and a main class to invoke a method through Spring's @Component and
@Autowired annotations.

Program:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;

@Component
class MyService {
public void serve() {
System.out.println("Service method called");
}
}

@SpringBootApplication
public class MyApp implements CommandLineRunner {

@Autowired
MyService service;

public static void main(String[] args) {


SpringApplication.run(MyApp.class, args);
}

@Override
public void run(String... args) throws Exception {
service.serve();
}
}

Page | 15
OUTPUT:-

Service method called

Page | 16
Experiment No. 9

Objective: Develop a RESTful web service using Spring Boot. Create a controller that
responds to HTTP GET requests and returns a simple JSON message. Use Spring Boot
annotations like @RestController and @GetMapping to handle requests.

Program:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class RestServiceApp {
public static void main(String[] args) {
SpringApplication.run(RestServiceApp.class, args);
}
}

@RestController
class HelloController {

@GetMapping("/hello")
public Message sayHello() {
return new Message("Hello, this is a JSON response!");
}
}

class Message {
private String message;

public Message(String message) {


this.message = message;
}

public String getMessage() {


return message;
}

Page | 17
public void setMessage(String message) {
this.message = message;
}
}

OUTPUT:-

{
"message": "Hello, this is a JSON response!"
}

Page | 18
Experiment No. 10

Objective: Build a basic frontend web application using Spring Boot and Thymeleaf.
Create a webpage that collects user input from a form and displays the submitted data
back to the user. Demonstrate integration of backend logic with frontend rendering
using @Controller and Model.

Program:

<!—form.html -->
<form action="/submit" method="post">
<input type="text" name="username" />
<button type="submit">Submit</button>
</form>

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class FormController {

@GetMapping("/")
public String showForm() {
return "form";
}

@PostMapping("/submit")
public String submit(@RequestParam String username, Model model) {
model.addAttribute("user", username);
return "result";
}
}

Page | 19
OUTPUT:-

Displays submitted user input on result page.

Page | 20

You might also like