0% found this document useful (0 votes)
18 views27 pages

Java Programming Basics and Techniques

The document outlines a series of Java programming experiments covering various topics such as using the Eclipse IDE, command-line arguments, object-oriented programming concepts, inheritance, polymorphism, exception handling, multithreading, Java packages, I/O operations, and building applications with the Spring Framework. Each experiment includes objectives, theoretical explanations, and sample code. The document is structured to guide users through practical applications of Java programming techniques.

Uploaded by

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

Java Programming Basics and Techniques

The document outlines a series of Java programming experiments covering various topics such as using the Eclipse IDE, command-line arguments, object-oriented programming concepts, inheritance, polymorphism, exception handling, multithreading, Java packages, I/O operations, and building applications with the Spring Framework. Each experiment includes objectives, theoretical explanations, and sample code. The document is structured to guide users through practical applications of Java programming techniques.

Uploaded by

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

EXPERIMENT-1

AIM : Use Java compiler and eclipse platform to write and execute java program.

THEORY :

1. Install Eclipse

• Download and install the Eclipse IDE from the official website
([Link]

• Follow the installation instructions for your operating system.

2. Open Eclipse:
• Launch Eclipse IDE after installation.

3. Create a New Java Project:

• Go to File > New > Java Project.


• Enter a project name (e.g., FirstProgram) and click Finish.

4. Create a Java Class:

• Right-click on the “src” folder inside your project.


• Go to New > Class.
• Enter a class name (e.g., FirstProgram) and check the box for public static void
main(String[] args).
• Click Finish.

5. Write Java Code:


In the editor window for [Link], write your Java code. Below is a simple "Hello World"
example:

package javafile;
public class FirstProgram {
public static void main(String[] args) {
[Link]("Hello world");

}
6. Save the Java File:
• Press Ctrl + S (Windows/Linux) or Cmd + S (Mac) to save the Java file.
7. Compile the Java Program:
• Eclipse automatically compiles the Java program when you save the file.
• Any compilation errors will be shown in the Problems tab.
8. Run the Java Program:
• Right-click on the FirstProgram class file in the Package Explorer.
• Select Run at top.
• The program output (Hello world) will be displayed in the Console view at the bottom.

Yuvraj Singh AIML-2 2200911530129


OUTPUT (SNAPSHOT):

Yuvraj Singh AIML-2 2200911530129


EXPERIMENT-2

AIM: Create a simple Java program using command line arguments.


THEORY:

1. Check Command-Line Arguments:


o Start by checking if any command-line arguments were provided ([Link] > 0). If not,
display a usage message and exit.
2. Initialize Variables: o Declare an integer variable sum to store the cumulative sum of
integers provided as arguments.
3. Iterate Through Arguments: o Use a for loop to iterate through each argument (arg) in the args
array.
4. Convert and Sum Integers:
o Inside the loop, convert each argument (arg) from a String to an int using
[Link](arg). o Add each
converted integer to the sum variable.
5. Handle Number Format Exception:
o Use a try-catch block to catch NumberFormatException, which occurs if an argument cannot
be parsed as an integer (e.g., contains non-numeric characters).
6. Output the Result: o After iterating through all arguments, print the total sum of integers.

CODE

public class CommandLineSum {


public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Usage: java CommandLineSum <integer1> <integer2> ... <integerN>");
return;
}

int sum = 0;

for (String arg : args) {


try {
int num = [Link](arg);
sum += num;
} catch (NumberFormatException e) {
[Link]("Error: One of the arguments is not an integer."); return;
}
}

Yuvraj Singh AIML-2 2200911530129


[Link]("Sum of integers: " + sum);
}
}
OUTPUT (SNAPSHOT):

Yuvraj Singh AIML-2 2200911530129


EXPERIMENT-3

AIM: Understand OOP concepts and basics of Java programming.


THEORY:

1. Objects and Classes:

• Learn the concept of objects and classes.


• Understand how to define a class and create objects in Java.

2. Four Pillars of OOP:

• Encapsulation:
o Understand how to bundle data (variables) and methods (functions) into a single unit
(class).
o Learn about access modifiers (private, public, protected, default).
• Abstraction:
o Learn to simplify complex reality by modeling classes appropriate to the problem.
o Use abstract classes and interfaces.
• Inheritance:
o Understand how one class can inherit fields and methods from another class.
o Learn about the extends keyword.
• Polymorphism:
o Study how a single action can behave differently based on the object that it is acting
upon.
o Understand method overloading and method overriding.

Code:

package javafile;
class Vehicle {
private String brand;
public Vehicle(String brand) {
[Link] = brand;
}

public void drive() {


[Link](brand + " is driving.");
}
public String getBrand() { return
brand;
}
public void setBrand(String brand) { [Link] = brand;
}
}

Yuvraj Singh AIML-2 2200911530129


class Car extends Vehicle {
public Car(String brand) {
super(brand);
}
@Override
public void drive() {
[Link](getBrand() + " car is driving."); }
}
class Bike extends Vehicle {
public Bike(String brand) {
super(brand);
}

@Override
public void drive() {
[Link](getBrand() + " bike is driving."); }
}

public class Oops {


public static void main(String[] args) { Vehicle
myCar = new Car("Toyota"); Vehicle
myBike = new Bike("Yamaha");

[Link](); [Link]();
[Link]("Honda");
[Link]("Car's new brand: " + [Link]());

Vehicle[] vehicles = {myCar, myBike}; for


(Vehicle vehicle : vehicles) { [Link]();
}
}
}
OUTPUT (SNAPSHOT):

Yuvraj Singh AIML-2 2200911530129


Yuvraj Singh AIML-2 2200911530129
EXPERIMENT-4

OBJECTIVE: Create Java programs using inheritance and polymorphism.

THEORY:

1. Define the Base Class (Appliance):


o Declare a base class Appliance with a private field brand.
o Add a constructor to initialize the brand. o Include a method operate() to be overridden by
subclasses.
o Implement getter and setter methods for the brand field.
2. Define Subclasses (WashingMachine and Refrigerator):
o Create WashingMachine and Refrigerator classes that extend the Appliance class.
o Override the operate() method in both subclasses.
3. Main Class to Demonstrate Inheritance and Polymorphism:
o Create a Main class with the main method. o Instantiate objects of WashingMachine and
Refrigerator using Appliance references.
o Demonstrate polymorphism by calling the operate() method on these objects. o Show
encapsulation by modifying and accessing the brand field using getter and setter methods.

CODE:

package javafile;

class Appliance { private


String brand;

public Appliance(String brand) { [Link] = brand;


}
public void operate() {
[Link](brand + " is operating."); }
public String getBrand() { return
brand;
}

public void setBrand(String brand) { [Link] = brand;


}
}
class WashingMachine extends Appliance { public
WashingMachine(String brand) { super(brand);
}
@Override
public void operate() {
[Link](getBrand() + " washing machine is cleaning clothes.");
}
}
class Refrigerator extends Appliance { public
Refrigerator(String brand) { super(brand);
}

Yuvraj Singh AIML-2 2200911530129


@Override
public void operate() {
[Link](getBrand() + " refrigerator is cooling food.");
}
}

public class Oops { public static void main(String[]


args) {
Appliance myWashingMachine = new WashingMachine("Samsung"); Appliance
myRefrigerator = new Refrigerator("LG");

[Link]();
[Link]();
[Link]("Whirlpool");
[Link]("Washing Machine's new brand: " +
[Link]());

Appliance[] appliances = {myWashingMachine, myRefrigerator}; for


(Appliance appliance : appliances) { [Link]();
}
}
}
OUTPUT (SNAPSHOT):

Yuvraj Singh AIML-2 2200911530129


EXPERIMENT-5
AIM: Implement error-handling techniques using exception handling and multithreading.
THEORY:

1. Understand the Basics of Exception Handling:

• Learn about different types of exceptions: checked exceptions, unchecked exceptions, and
errors.
• Understand the try-catch block, finally clause, and throwing exceptions.

2. Define a Class to Demonstrate Exception Handling:

• Create a class with methods that can throw exceptions.


• Implement custom exception classes if needed.

3. Implement Exception Handling:

• Use try-catch blocks to handle exceptions in your methods.


• Use the finally block to clean up resources.

4. Understand the Basics of Multithreading:

• Learn about creating threads using the Thread class and the Runnable interface.
• Understand thread life cycle and thread synchronization.

5. Define a Class to Demonstrate Multithreading:

• Create a class that implements Runnable or extends Thread.


• Implement the run method with thread-specific tasks.

6. Combine Exception Handling and Multithreading:

• Handle exceptions within the run method.

• Ensure thread safety by using synchronization techniques if needed.

CODE:

package javafile;

class CustomException extends Exception { public


CustomException(String message) { super(message);
}
}

class Task implements Runnable { private String


taskName;

Yuvraj Singh AIML-2 2200911530129


public Task(String taskName) { [Link] =
taskName;
}

@Override public void


run() { try {
[Link](taskName + " is running."); if ([Link]() > 0.7) { throw
new CustomException(taskName + " encountered an error.");
}
[Link](taskName + " completed successfully.");
} catch (CustomException e) {
[Link]([Link]());
} finally {
[Link](taskName + " is cleaning up resources.");
}
}
}

public class Main { public static void main(String[]


args) {
Task[] tasks = { new
Task("Task 1"), new
Task("Task 2"), new
Task("Task 3"), new
Task("Task 4"), new
Task("Task 5")
};

Thread[] threads = new Thread[[Link]];

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


Thread(tasks[i]); threads[i].start();
}
for (Thread thread : threads) { try {
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted."); }
}

[Link]("All tasks completed."); }


}
OUTPUT (SNAPSHOT):

Yuvraj Singh AIML-2 2200911530129


Yuvraj Singh AIML-2 2200911530129
EXPERIMENT-6
AIM: Create java program with the use of java packages.
THEORY:

1. Set Up Your Project Structure

• Create a directory structure for your project.


• Create directories for the package and main
application.

2. Create the Package

• Define a package and create a class within it.

3. Use the Package in the Main Program

Import the package in your main program and use its class.

CODE with Output:

Package has been created

Yuvraj Singh AIML-2 2200911530129


Experiment-7
AIM: Construct java program using Java I/O package.
THEORY:

1. Set Up Your Project Structure

• Create a directory structure for your project.

2. Create the Main Program

• Define the main class and methods for reading from and writing to files.

3. Implement File Reading

• Use Java I/O classes to read content from a file.

4. Implement File Writing

• Use Java I/O classes to write content to a file.

CODE:

package javafile;
import [Link]; import
[Link]; import
[Link]; import
[Link];
public class FileReadWrite {

public static void main(String[] args) {


String inputFilePath = "data/[Link]";
String outputFilePath = "data/[Link]";

File inputFile = new File(inputFilePath); if (!


[Link]()) { try {
[Link]().mkdirs();
[Link]();
[Link]("Created new [Link] file.");
} catch (IOException e) {
[Link]("Error creating [Link]: " + [Link]());
}
}

try {
String content = readFile(inputFilePath);
content += "END OF FILE\n";
writeFile(outputFilePath, content);
[Link]("File content copied successfully.");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]()); }

Yuvraj Singh AIML-2 2200911530129


}
private static String readFile(String filePath) throws IOException
{ StringBuilder content = new StringBuilder(); try (Scanner scanner = new
Scanner(new File(filePath))) { while ([Link]()) {
[Link]([Link]()).append("\n"); }
}
return [Link]();
}

private static void writeFile(String filePath, String content) throws IOException { try
(FileWriter writer = new FileWriter(filePath)) { [Link](content);
}
}
}
Code with Output:

EXPERIMENT-8

OBJECTIVE: Create industry oriented application using Spring Framework.


THEORY:

1. Set Up Your Development Environment

Yuvraj Singh AIML-2 2200911530129


• Install Java Development Kit (JDK)
• Install an Integrated Development Environment (IDE)
• Set up a build tool (Maven or Gradle)

2. Initialize the Spring Boot Project

• Use Spring Initializr to create a new Spring Boot project

3. Create the Project Structure

• Define the necessary packages and classes

4. Set Up the Application Properties

• Configure application properties

5. Create the Domain Model

• Define the entities and data models

6. Set Up the Repository Layer

• Create repositories for data access

7. Implement the Service Layer

• Define the business logic

8. Create the Controller Layer

• Implement RESTful endpoints

9. Test the Application

• Write unit and integration tests

10. Run the Application

• Run the application and test the endpoints

11. Package and Deploy the Application


• Package the application into a deployable unit
• Deploy to a web server or cloud platform

CODE:
import [Link]; import
[Link];
import [Link].*; import
[Link]; import

Yuvraj Singh AIML-2 2200911530129


[Link]; import
[Link]; import
[Link]; import [Link].*;
import [Link];

@SpringBootApplication
public class DemoApplication
{
public static void main(String[] args) {
[Link]([Link], args);
}
}

// Domain Model
@Entity
class User {
@Id
@GeneratedValue(strategy =
[Link]) private Long id; private
String name; private String email;

// Getters and setters public Long getId() { return id; }


public void setId(Long id) { [Link] = id; } public String
getName() { return name; } public void
setName(String name) { [Link] = name; } public
String getEmail() { return email; } public void
setEmail(String email) { [Link] = email; }
}
// Repository Layer @Repository interface UserRepository
extends JpaRepository<User, Long> { }

// Service Layer @Service class


UserService { @Autowired private
UserRepository userRepository;

public List<User> getAllUsers() {


return [Link]();
}

public User getUserById(Long id) {


return [Link](id).orElse(null);
}

Yuvraj Singh AIML-2 2200911530129


public User saveUser(User user) {
return [Link](user);
}

public void deleteUser(Long id) {


[Link](id);
}
}

// Controller Layer
@RestController
@RequestMapping("/users")
class UserController
{ @Autowired
private UserService userService;

@GetMapping
public List<User> getAllUsers()
{ return [Link]();
@GetMapping("/{id}") public User
getUserById(@PathVariable Long
id) {
return [Link](id);
}

@PostMapping public User


createUser(@RequestBody User user) {
return [Link](user);
}

@DeleteMapping("/{id}") public void


deleteUser(@PathVariable Long id) {
[Link](id);
}
}

OUTPUT (SNAPSHOT):

Yuvraj Singh AIML-2 2200911530129


EXPERIMENT-9
OBJECTIVE: Test RESTful web services using Spring Boot.
THEORY:

1. Set Up the Project

• Create a new Spring Boot project: Use Spring Initializr or your IDE's project creation
wizard to set up a new Spring Boot project. Add dependencies for Spring Web and Spring
Boot Starter Test.

2. Create a REST Controller

• Define your REST controller: Create a simple REST controller with CRUD endpoints.

3. Create a Test Class

• Write unit tests using Spring Boot's testing support: Create a test class to test the REST
endpoints.

4. Run the Tests

• Execute the tests: Run the test class using your IDE or Maven.

CODE:

import [Link]; import

[Link];

import [Link]; import

[Link].*; import

Yuvraj Singh AIML-2 2200911530129


[Link]; import

[Link]; import

[Link]; import

[Link]; import

[Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link]; import

[Link]; import [Link];

@SpringBootApplication

public class DemoApplication

public static void main(String[] args) {

[Link]([Link], args);

@Bean

CommandLineRunner initDatabase(UserRepository userRepository)

{ return args -> { [Link](new User("John Doe",

"john@[Link]")); [Link](new User("Jane Doe",

"jane@[Link]"));

};

Yuvraj Singh AIML-2 2200911530129


}

@RestController

@RequestMapping("/api/users")

class UserController {

private UserRepository userRepository;

@GetMapping

public ResponseEntity<Iterable<User>> getAllUsers() { return new

ResponseEntity<>([Link](), [Link]);

@GetMapping("/{id}") public ResponseEntity<User>

getUser(@PathVariable Long id) { return

[Link](id)

.map(user -> new ResponseEntity<>(user, [Link]))

.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));

@PostMapping public ResponseEntity<User>

createUser(@RequestBody User user) { User savedUser =

[Link](user); return new

ResponseEntity<>(savedUser, [Link]);

@DeleteMapping("/{id}") public ResponseEntity<Void>

deleteUser(@PathVariable Long id)

Yuvraj Singh AIML-2 2200911530129


{ [Link](id); return new

ResponseEntity<>(HttpStatus.NO_CONTENT);

}
interface UserRepository extends CrudRepository<User, Long> {}

@Entity

class User {

@Id

@GeneratedValue(strategy =

[Link]) private Long id; private

String name; private String email;

public User() {}

public User(String name, String email)

{ [Link] = name; [Link] =

email;

public Long getId() { return id; } public void

setId(Long id) { [Link] = id; } public String getName()

{ return name; } public void setName(String name)

{ [Link] = name; } public String getEmail() { return

email; } public void setEmail(String email) { [Link]

= email; }

}
class UserControllerTest {

Yuvraj Singh AIML-2 2200911530129


@Autowired

private TestRestTemplate restTemplate;

@Test public void

testCreateUser() {

User user = new User("Alice Doe", "alice@[Link]");

ResponseEntity<User> response = [Link]("/api/users", user,


[Link]); assertEquals([Link],

[Link]());

assertNotNull([Link]().getId());

@Test public void

testGetUser() {

User user = new User("Bob Doe", "bob@[Link]");

ResponseEntity<User> response = [Link]("/api/users", user,


[Link]);

Long userId = [Link]().getId();

ResponseEntity<User> getUserResponse = [Link]("/api/users/" + userId,


[Link]); assertEquals([Link],

[Link]()); assertEquals("Bob Doe",

[Link]().getName());

}
public void testDeleteUser() {

User user = new User("Carol Doe", "carol@[Link]");

ResponseEntity<User> response = [Link]("/api/users", user,


[Link]);

Long userId = [Link]().getId();

[Link]("/api/users/" + userId);

Yuvraj Singh AIML-2 2200911530129


ResponseEntity<User> getUserResponse = [Link]("/api/users/" + userId,
[Link]); assertEquals(HttpStatus.NOT_FOUND,

[Link]());

}
}

OUTPUT (SNAPSHOT):

EXPERIMENT-10
OBJECTIVE: Test Frontend web application with Spring Boot
THEORY:

1. Set Up Your Project

• Create a Spring Boot project: Use Spring Initializr or your IDE to create a new Spring Boot
project with dependencies for Spring Web, Spring Boot Starter Test, and Thymeleaf (if you use
server-side rendering).

2. Create a Simple Frontend

• Create a simple HTML page using Thymeleaf

3. Write Unit Tests

• Write unit tests for your controller:

4. Write Integration Tests

• Test the entire Spring Boot application context

5. Set Up End-to-End Tests

• Configure Selenium for E2E tests

Yuvraj Singh AIML-2 2200911530129


CODE:

import [Link]; import


[Link];
import [Link]; import
[Link].*; import
[Link]; import
[Link];
import [Link];

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {


[Link]([Link], args);
}

@RestController
@RequestMapping("/api")
class HelloController {

@GetMapping("/hello")
public ResponseEntity<String> hello()
{ return [Link]("Hello,
World!");
}
}

@SpringBootTest(webEnvironment = [Link].DEFINED_PORT)
class HelloControllerTest {

private final String baseUrl = "[Link]

Yuvraj Singh AIML-2 2200911530129


private final RestTemplate restTemplate = new RestTemplate();

@Test
public void testHelloEndpoint() {
ResponseEntity<String> response = [Link](baseUrl + "/hello",
[Link]);
assertEquals([Link], [Link]());
assertEquals("Hello, World!", [Link]());
}
}

Yuvraj Singh AIML-2 2200911530129


Yuvraj Singh AIML-2 2200911530129

You might also like