[Go to site: main page, start]

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

Java Programming Basics and Techniques

The document outlines a series of practical exercises for learning Java programming, covering topics such as basic Java syntax, object-oriented programming concepts, exception handling, multithreading, and the use of Java packages. It also includes instructions for creating a simple industry-oriented application using the Spring Framework. Each section provides step-by-step guidance on writing and executing Java programs, along with example code snippets.

Uploaded by

rajputananya238
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)
22 views24 pages

Java Programming Basics and Techniques

The document outlines a series of practical exercises for learning Java programming, covering topics such as basic Java syntax, object-oriented programming concepts, exception handling, multithreading, and the use of Java packages. It also includes instructions for creating a simple industry-oriented application using the Spring Framework. Each section provides step-by-step guidance on writing and executing Java programs, along with example code snippets.

Uploaded by

rajputananya238
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

INDEX

Sno. Practical Name Date Faculty’s


Signature

1. Use Java compiler and eclipse platform to write


and execute java program.

2. Creating simple java programs 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 techniques using exception


handling and multithreading.

6. Create java program with the use of java packages.

Construct java program using Java I/O package.


7.

8. Create industry-oriented application using Spring


Framework.

9. Test RESTful web services using Spring Boot.

10. Test Frontend web application with Spring Boot


1- Use Java compiler and eclipse platform to write and execute java
program.

Requirements:

• Eclipse IDE installed (Download from [Link]


• Java JDK installed and configured in Eclipse

▶ Steps to Write and Run Java Program:

1. Open Eclipse
2. Go to File > New > Java Project
o Name it (e.g., MyFirstProject) → Click Finish
3. Right-click the src folder → New > Class
o Name: HelloWorld
o Check the box: public static void main (String[] args)
o Click Finish
4. In the editor, type your code:

java
CopyEdit
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

5. Click the green run button (▶) on the toolbar

6. Console Output:

Hello, World!
2- Creating simple java programs using command line arguments

Requirements:

• Java JDK installed (check using java -version and javac -version)
• A text editor (e.g., Notepad, VS Code)

Sample Java Program ([Link])

java
CopyEdit
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

▶ Steps to Compile and Run:

1. Save the above code in a file named [Link]


2. Open Command Prompt (Windows) or Terminal (macOS/Linux)
3. Navigate to the folder where your file is saved:

cd path\to\your\file

4. Compile the program:

javac [Link]

This creates [Link]

5. Run the program:

java HelloWorld

Output:

Hello, World!
3- Understand OOPs concepts and basics of Java programming.
Java is a pure object-oriented programming language, which means everything revolves around
classes and objects.

1. Class and Object

• Class: Blueprint for creating objects.


• Object: Instance of a class.

java
CopyEdit
// Class
public class Car {
String color = "Red";

void drive() {
[Link]("The car is driving.");
}
}

// Main method to create object


public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object
[Link]([Link]); // Access attribute
[Link](); // Call method
}
}

2. Encapsulation

• Wrapping data (variables) and code (methods) into a single unit (class).
• Achieved using private variables and public getters/setters.

java
CopyEdit
public class Person {
private String name; // Private data

public String getName() {


return name;
}

public void setName(String newName) {


name = newName;
}
}
3. Inheritance

• One class inherits the fields and methods of another.


• Use extends keyword.

java
CopyEdit
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited
[Link](); // Own method
}
}

4. Polymorphism

• One interface, many implementations.


• Achieved via method overloading and overriding.

a. Method Overloading (same method name, different parameters)

class Math {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}
b. Method Overriding (subclass provides specific implementation)
c.

class Animal {
void sound() {
[Link]("Some sound");
}
}

class Cat extends Animal {


void sound() {
[Link]("Meow");
}
}

5. Abstraction

• Hiding internal details and showing only essential information.


• Achieved using abstract classes and interfaces.

a. Abstract Class

java
CopyEdit
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


void draw() {
[Link]("Drawing Circle");
}
}

b. Interface

interface Vehicle {
void move();
}

class Bike implements Vehicle {


public void move() {
[Link]("Bike moves");
}
}
4- Create Java programs using inheritance and polymorphism.

1. Java Program Using Inheritance

We'll create a basic program where a Vehicle class is inherited by a Car class.

Example: [Link] and [Link]

java
CopyEdit
// Base class (superclass)
class Vehicle {
String brand = "Generic Vehicle";

void start() {
[Link]("Vehicle is starting...");
}
}

// Derived class (subclass)


class Car extends Vehicle {
String model = "Sedan";

void drive() {
[Link]("Car is driving...");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
[Link]("Brand: " + [Link]); // Inherited property
[Link]("Model: " + [Link]);
[Link](); // Inherited method
[Link](); // Own method
}
}
Output:

Brand: Generic Vehicle


Model: Sedan
Vehicle is starting...
Car is driving...
2. Java Program Using Polymorphism

Part A: Method Overriding

class Animal {
void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
[Link]("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal a1 = new Dog(); // Polymorphism
Animal a2 = new Cat();

[Link](); // Output: Dog barks


[Link](); // Output: Cat meows
}
}
Part B: Method Overloading

class Calculator {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Add 2 numbers: " + [Link](5, 10)); // 15 }}
5- Implement error-handling techniques using exception handling
and multithreading

Part 1: Exception Handling in Java

Java provides try-catch-finally blocks and custom exceptions for robust error-handling.

Example: Division with Exception Handling

java
CopyEdit
import [Link];

public class ExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
[Link]("Enter numerator: ");
int a = [Link]();
[Link]("Enter denominator: ");
int b = [Link]();

int result = a / b; // May throw ArithmeticException


[Link]("Result: " + result);

} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
} catch (Exception e) {
[Link]("An error occurred: " + [Link]());
} finally {
[Link]("This block always executes.");
[Link]();
}
}
}

Output Example:

Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero!
This block always executes.
Part 2: Multithreading in Java

Multithreading allows multiple threads to run concurrently. You can create threads by:

• Extending the Thread class


• Implementing the Runnable interface

Example: Using Thread Class

java
CopyEdit
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("From MyThread: " + i);
try {
[Link](500); // Pause for 0.5 seconds
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}

Example: Using Runnable Interface

java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("From MyRunnable: " + i);
try {
[Link](700); // Pause for 0.7 seconds
} catch (InterruptedException e) {
[Link]("Runnable thread interrupted.");
}
}
}
}

Main Program to Run Both:

java
CopyEdit
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
Thread t2 = new Thread(new MyRunnable());

[Link](); // Start thread by extending Thread


[Link](); // Start thread using Runnable
}
}

Handling Exceptions Inside Threads

Always handle exceptions inside the run() method, as uncaught exceptions can crash a thread.

Feature What It Does Example Used

try-catch-finally Catch runtime errors safely Division example

extends Thread Simple way to create a thread MyThread class

implements Runnable Preferred for multithreaded class sharing MyRunnable class

[Link]() Pause execution of a thread Inside loop


6- Create java program with the use of java packages.

What Are Java Packages?

• Packages group related classes and interfaces.


• Two types:
o Built-in: [Link], [Link]
o User-defined: Custom packages you create

Step-by-Step Example of a User-Defined Package

We'll create a program that:

• Defines a package mypackage


• Contains a class Greeting inside the package
• Uses the Greeting class from another file

Step 1: Create the Package and Class

File: mypackage/[Link]

package mypackage;

public class Greeting {


public void sayHello() {
[Link]("Hello from the mypackage!");
}
}

Step 2: Create the Main Program to Use the Package

File: [Link]

import [Link]; // Import the class from package

public class MainApp {


public static void main(String[] args) {
Greeting g = new Greeting();
[Link](); // Call method from package
}
}
How to Compile and Run

1. Open a terminal and go to the ProjectFolder


2. Compile the package class:

javac mypackage/[Link]

3. Compile the main class:

javac [Link]

4. Run the program:

java MainApp

Output:

Hello from the mypackage!

Concept Description

package keyword Declares a class as part of a package

import keyword Brings in classes from a package

Folder = Package Java requires folder structure to match package names


7- Construct java program using Java I/O package.
Writing to a file
Reading from a file

We’ll use the following classes from [Link]:

• FileWriter and BufferedWriter for writing


• FileReader and BufferedReader for reading

1. Writing to a File

File: [Link]

java
CopyEdit
import [Link];
import [Link];
import [Link];

public class FileWriteExample {


public static void main(String[] args) {
String fileName = "[Link]";

try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
[Link]("Hello, this is a sample file.\n");
[Link]("This content was written using Java I/O.");
[Link](); // Always close streams
[Link]("File written successfully.");
} catch (IOException e) {
[Link]("An error occurred while writing to the file.");
[Link]();
}
}
}

2. Reading from a File

File: [Link]

import [Link];
import [Link];
import [Link];
public class FileReadExample {
public static void main(String[] args) {
String fileName = "[Link]";

try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
[Link]("Reading from file:");
while ((line = [Link]()) != null) {
[Link](line);
}
[Link](); // Always close streams
} catch (IOException e) {
[Link]("An error occurred while reading the file.");
[Link]();
}
}
}

How to Compile and Run


javac [Link]
javac [Link]

java FileWriteExample
java FileReadExample

Output:
File written successfully.
Reading from file:
Hello, this is a sample file.
This content was written using Java I/O.
8- Create industry-oriented application using Spring Framework

Project Name: EmployeeManagementSystem


Tech Stack:
• Spring Boot (Spring Framework core)
• Spring Web (REST APIs)
• Spring Data JPA (Database access)
• H2 Database (for testing; can be replaced with MySQL/PostgreSQL)
• Maven or Gradle

Features
• Add employee
• View all employees
• Get employee by ID
• Delete employee

Project Structure
css
CopyEdit
src/
└── main/
├── java/com/example/employeemanagement/
│ ├── controller/
│ ├── service/
│ ├── repository/
│ ├── model/
│ └── [Link]
└── resources/
└── [Link]

Step-by-Step Implementation
1. Create Spring Boot Project
Use [Link]
• Project: Maven
• Dependencies:
o Spring Web
o Spring Data JPA
o H2 Database
o Lombok (optional)

2. Model Class
File: model/[Link]

package [Link];

import [Link].*;

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = [Link])
private Long id;

private String name;


private String email;
private String department;

// Getters and setters


}

3. Repository Interface
File: repository/[Link]

package [Link];

import [Link];
import [Link];

public interface EmployeeRepository extends JpaRepository<Employee, Long> {


}

4. Service Layer
File: service/[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

@Service
public class EmployeeService {

@Autowired
private EmployeeRepository repo;

public Employee addEmployee(Employee e) {


return [Link](e);
}

public List<Employee> getAllEmployees() {


return [Link]();
}

public Employee getEmployeeById(Long id) {


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

public void deleteEmployee(Long id) {


[Link](id);
}
}

5. Controller Layer
File: controller/[Link]
package [Link];

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

import [Link];

@RestController
@RequestMapping("/employees")
public class EmployeeController {

@Autowired
private EmployeeService service;

@PostMapping
public Employee add(@RequestBody Employee e) {
return [Link](e);
}

@GetMapping
public List<Employee> getAll() {
return [Link]();
}

@GetMapping("/{id}")
public Employee getById(@PathVariable Long id) {
return [Link](id);
}

@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
[Link](id);
}
}

6. Main Class
File: [Link]

package [Link];
import [Link];
import [Link];

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

7. Configuration File
File: resources/[Link]
[Link]=jdbc:h2:mem:testdb
[Link]=[Link]
[Link]=sa
[Link]=
[Link]-platform=[Link].H2Dialect
[Link]=true
[Link]-sql=true
[Link]-auto=update

Run and Test the API


Use Postman or curl:
• POST /employees
{
"name": "John Doe",
"email": "[Link]@[Link]",
"department": "Engineering"
}
• GET /employees
• GET /employees/1
• DELETE /employees/1
9- Test RESTful web services using Spring Boot.

1. Unit Tests with @WebMvcTest

Tests the controller layer in isolation (no service/database logic).

2. Integration Tests with @SpringBootTest

Tests the entire Spring context — controller, service, and repository.

Example: Employee REST API

Assuming you already have this endpoint in your controller:

java
CopyEdit
@RestController
@RequestMapping("/employees")
public class EmployeeController {

@Autowired
private EmployeeService service;

@GetMapping("/{id}")
public Employee getById(@PathVariable Long id) {
return [Link](id);
}
}

1. Unit Test Using @WebMvcTest

File: [Link]

package [Link];

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

@WebMvcTest([Link])
public class EmployeeControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private EmployeeService employeeService;

@Test
void testGetEmployeeById() throws Exception {
Employee emp = new Employee();
[Link](1L);
[Link]("John Doe");
[Link]("john@[Link]");
[Link]("HR");

when([Link](1L)).thenReturn(emp);

[Link](get("/employees/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.email").value("john@[Link]"));
}
}

2. Integration Test Using @SpringBootTest

File: [Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import static [Link];

@SpringBootTest(webEnvironment = [Link].RANDOM_PORT)
public class EmployeeIntegrationTest {

@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

@Autowired
private EmployeeRepository repo;

@BeforeEach
void setUp() {
Employee emp = new Employee();
[Link]("Alice");
[Link]("alice@[Link]");
[Link]("Finance");
[Link](emp);
}

@Test
void testGetEmployee() {
String url = "[Link] + port + "/employees/1";
Employee emp = [Link](url, [Link]);
assertThat([Link]()).isEqualTo("Alice");
}
}

Maven Dependencies (if not already present)

Add to your [Link]:

xml
CopyEdit
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Test Type Annotation Purpose

Unit Test @WebMvcTest Tests only controller logic

Integration Test @SpringBootTest Tests full app with DB

HTTP mocking MockMvc Simulate HTTP calls without server

Real calls TestRestTemplate Real HTTP calls with full Spring Boot context
10- Test Frontend web application with Spring Boot
1. Spring MVC with JSP or Thymeleaf (server-side rendering)
2. Spring Boot REST API + separate frontend (React, Angular, Vue, etc.)

1. Testing Server-Side Rendered Frontend (e.g., Thymeleaf)

Tools You Can Use:

• MockMvc (for simulating HTTP requests)


• HtmlUnit (headless browser to test rendered HTML)
• Selenium (UI testing with actual browser)

Example: Test Thymeleaf Page with MockMvc

Suppose you have a simple controller:


@Controller
public class HomeController {

@GetMapping("/")
public String home(Model model) {
[Link]("message", "Welcome to Spring Boot!");
return "home"; // Thymeleaf template: [Link]
}
}

Test Using MockMvcava

@WebMvcTest([Link])
public class HomeControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
void testHomePageLoads() throws Exception {
[Link](get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(model().attributeExists("message"));
}
}
2. Testing REST API + JS Frontend (React, Angular, Vue)

Here, the frontend is usually tested independently using JavaScript test frameworks, and the Spring
Boot backend is tested using:

• ✅ MockMvc or TestRestTemplate
• ✅ Integration testing of REST endpoints
• ✅ UI end-to-end testing via Selenium, Cypress, or Playwright

Option A: UI End-to-End Test with Selenium (Spring Boot + HTML)

Add Selenium dependency (Maven):


xml
<dependency>
<groupId>[Link]</groupId>
<artifactId>selenium-java</artifactId>
<version>4.20.0</version>
</dependency>
Example Selenium Test:
import [Link];
import [Link];
import [Link];
import static [Link].*;

public class FrontendSeleniumTest {

@Test
public void testHomePageTitle() {
[Link]("[Link]", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
[Link]("[Link]
String title = [Link]();
assertEquals("Home Page", title); // Assuming title in <title> tag
[Link]();
}
}

Setup Recommended Testing Tools

Spring Boot + Thymeleaf MockMvc, HtmlUnit, Selenium

Spring Boot + REST + JS MockMvc + frontend tools (Jest, Cypress)

Full-stack E2E Selenium, Cypress, Playwright

Common questions

Powered by AI

Encapsulation and abstraction are core to Java's OOP, providing a foundation for building complex systems. Encapsulation restricts direct access to an object's components, using private variables and public methods to maintain integrity and hide implementation details. Abstraction further hides complexity by allowing users to interact with object functionalities through simple interfaces or abstract classes without exposing internal workings. Together, these principles create modular, user-oriented, and maintainable software architectures .

Inheritance allows a new class to inherit properties and behaviors from an existing class (superclass), promoting code reuse and establishing a natural class hierarchy. Polymorphism enables objects to be treated as instances of their parent class, allowing one interface to be used for general class actions. Through method overriding and overloading, polymorphism provides flexibility and can handle various object types and structures in software design, making programs easier to extend and maintain .

Multithreading enhances performance by enabling concurrent execution of tasks, optimizing CPU usage, and improving application responsiveness, especially in I/O-bound and computationally intensive programs. However, developers must manage synchronization issues between threads to avoid race conditions, deadlocks, and thread starvation. Properly handling these issues requires careful design to maintain data consistency and ensure correct thread interaction .

The Java I/O package provides classes to perform input and output with files and data streams, essential for application data handling. File reading is accomplished with FileReader and BufferedReader, enabling line-by-line text reading, whereas FileWriter and BufferedWriter support efficient file writing. Implementing these involves creating a BufferedReader for reading and a BufferedWriter for writing, closing streams afterward to release resources, ensuring accurate and efficient file manipulation .

Multithreading in Java allows concurrent execution of threads, whereas exception handling ensures errors are managed. When combined, exception handling within a thread's run() method prevents uncaught exceptions from crashing programs, allowing threads to safely execute specific tasks despite potential runtime errors. This combination maximizes resource utilization and application responsiveness while maintaining stability and graceful degradation in case of thread-specific issues .

@WebMvcTest is used for isolating tests to the web layer, primarily focusing on controller testing with mocked service layer interactions. It is optimal for validating API request/response without full context setup. @SpringBootTest loads the complete Spring application context, ideal for integration tests which cover interactions between multiple layers like controller, service, and repository. Choosing between these depends on whether isolated component behavior or end-to-end application workflows need verification .

Exception handling in Java is accomplished with try-catch-finally blocks. A try block contains code that might throw an exception, whereas a catch block handles specific exceptions that occur. The finally block executes code irrespective of exceptions, often used to release resources. Exception handling is crucial because it prevents program crashes, manages expected and unexpected errors, and maintains program stability and data integrity by allowing the program to recover gracefully .

The Spring Framework provides infrastructure level support for developing robust enterprise applications. It simplifies development with dependency injection, aspect-oriented programming, declarative transaction management, and simplifies database integration through Spring Data JPA. Spring Boot further enhances development efficiency by offering auto-configuration and starter dependencies, reducing boilerplate code and configuration chores. This setup accelerates development, focuses on business logic, and delivers rapidly marketable solutions .

Java packages help organize classes and interfaces into namespaces which prevent naming conflicts and control access using visibility modifiers. They improve maintainability and ease collaborative development by segmenting the application into manageable parts. For example, a user-defined package can be created by defining a directory structure that reflects the package name and with a class inside it. A package 'mypackage' might contain a class 'Greeting' that prints a greeting message, then imported in another program to utilize its functionality .

Unit testing a RESTful service in Spring Boot can be achieved using @WebMvcTest, which tests the controller layer by mocking service and repository layers. An example includes using MockMvc to simulate HTTP requests and verify output. Integration testing leverages @SpringBootTest to evaluate the complete application context. This involves real REST calls using TestRestTemplate to ensure end-to-end functionality of components, thus guaranteeing correct application behavior in a production-like environment .

You might also like