[Go to site: main page, start]

0% found this document useful (0 votes)
5 views10 pages

Java Programming Guide

This document is a comprehensive guide to Java programming, covering essential concepts such as Java basics, object-oriented programming, collections framework, exception handling, and modern features introduced in Java 8. It also includes an overview of Spring Boot and best practices for Java and Spring Boot development. The guide is structured with clear examples and explanations to aid developers in understanding and utilizing Java effectively.
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)
5 views10 pages

Java Programming Guide

This document is a comprehensive guide to Java programming, covering essential concepts such as Java basics, object-oriented programming, collections framework, exception handling, and modern features introduced in Java 8. It also includes an overview of Spring Boot and best practices for Java and Spring Boot development. The guide is structured with clear examples and explanations to aid developers in understanding and utilizing Java effectively.
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

Java Programming

Complete Developer Guide

Java is one of the most widely used programming languages in the world. From enterprise applications to
Android development, Java powers billions of devices and systems globally. This guide covers the
essential concepts every Java developer should know — from core syntax and OOP principles to modern
features introduced in Java 8 and beyond.

Page Topic
2 Java Basics & Data Types
3 Object-Oriented Programming
4 Inheritance & Polymorphism
5 Collections Framework
6 Exception Handling
7 Java 8 – Stream API
8 Spring Boot Overview
9 Spring Boot CRUD REST API
10 Best Practices & Tips
Java Basics & Data Types
What is Java?
Java is a class-based, object-oriented language designed to have as few implementation dependencies
as possible. It follows the principle of Write Once, Run Anywhere (WORA) — compiled Java code can
run on all platforms that support the Java Virtual Machine (JVM).

Primitive Data Types


Type Size Range / Description
byte 8-bit -128 to 127
short 16-bit -32,768 to 32,767
int 32-bit -2³¹ to 2³¹ - 1
long 64-bit -2■³ to 2■³ - 1
float 32-bit Single-precision decimal
double 64-bit Double-precision decimal
char 16-bit Single Unicode character
boolean 1-bit true or false

Hello World Example


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Object-Oriented Programming (OOP)
OOP is a programming paradigm that organizes software design around data, or objects, rather than
functions and logic. Java is built around four core OOP principles:

• Encapsulation – Bundling data and methods that operate on the data within a class.
• Abstraction – Hiding complex implementation details and showing only the necessary features.
• Inheritance – A class can acquire properties and methods of another class.
• Polymorphism – Objects can take many forms; one interface, multiple implementations.

Example – Encapsulation with Getters & Setters


public class Person {
private String name;
private int age;

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public int getAge() { return age; }


public void setAge(int age) { [Link] = age; }
}

Classes & Objects


Person p = new Person();
[Link]("Biswa");
[Link](25);
[Link]([Link]()); // Output: Biswa
Inheritance & Polymorphism
Inheritance allows a child class to reuse the code of a parent class. Use the extends keyword to inherit
from a class.

Inheritance Example
// Parent class
public class Animal {
public void speak() {
[Link]("Some sound...");
}
}

// Child class
public class Dog extends Animal {
@Override
public void speak() {
[Link]("Woof!");
}
}

Polymorphism
With polymorphism, a parent reference can point to a child object. The correct method is resolved at
runtime.

Animal a = new Dog();


[Link](); // Output: Woof!

Abstract Classes & Interfaces


• Abstract Class – Cannot be instantiated; may have abstract and concrete methods.
• Interface – A contract that classes must implement; all methods are abstract by default (pre-Java 8).
• Key difference – A class can implement multiple interfaces but extend only one class.
Collections Framework
The Java Collections Framework provides a set of classes and interfaces for storing and manipulating
groups of data efficiently.

Collection Type Key Feature


ArrayList List Dynamic array; allows duplicates; ordered
LinkedList List/Deque Doubly linked; fast insert/delete
HashSet Set No duplicates; unordered
TreeSet Set No duplicates; sorted order
HashMap Map Key-value pairs; no duplicate keys
LinkedHashMap Map Key-value pairs; insertion order
PriorityQueue Queue Elements ordered by priority

ArrayList Example
List<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Mango");
[Link]("Banana");
[Link]([Link]::println);

HashMap Example
Map<String, Integer> scores = new HashMap<>();
[Link]("Alice", 95);
[Link]("Bob", 87);
[Link]([Link]("Alice")); // 95
Exception Handling
Exception handling allows a program to deal with runtime errors gracefully without crashing. Java uses
try-catch-finally blocks for this purpose.

Types of Exceptions
• Checked Exceptions – Must be handled at compile time (e.g., IOException, SQLException).
• Unchecked Exceptions – Runtime exceptions not required to be caught (e.g.,
NullPointerException, ArrayIndexOutOfBoundsException).
• Errors – Serious problems that the application should not try to catch (e.g., OutOfMemoryError).

Try-Catch-Finally Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("This always runs.");
}

Custom Exception
public class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}

// Usage
if (age < 0) throw new InvalidAgeException("Age cannot be negative.");
Java 8 – Stream API
The Stream API introduced in Java 8 allows functional-style operations on collections. Streams are lazy,
meaning intermediate operations are not executed until a terminal operation is invoked.

Common Stream Operations


Operation Type Description
filter() Intermediate Filters elements by a condition
map() Intermediate Transforms each element
sorted() Intermediate Sorts the stream
distinct() Intermediate Removes duplicates
collect() Terminal Collects results into a collection
forEach() Terminal Iterates over each element
count() Terminal Returns count of elements
reduce() Terminal Reduces to a single value

Stream Example
List<Integer> numbers = [Link](5, 3, 8, 1, 9, 2, 7);

List<Integer> result = [Link]()


.filter(n -> n > 3)
.sorted()
.collect([Link]());

// result: [5, 7, 8, 9]
Spring Boot Overview
Spring Boot is an open-source Java framework that simplifies the creation of production-ready Spring
applications. It eliminates boilerplate configuration and provides embedded servers so you can run
applications with a simple main() method.

Core Annotations
Annotation Purpose
@SpringBootApplication Marks the main class; enables auto-configuration
@RestController Marks class as REST API controller
@RequestMapping Maps HTTP requests to handler methods
@GetMapping / @PostMapping Shortcuts for GET and POST request mapping
@Service Marks class as a service layer component
@Repository Marks class as a data access layer component
@Autowired Injects dependencies automatically
@Entity Marks class as a JPA database entity

Layered Architecture
• Controller Layer – Handles HTTP requests and sends responses.
• Service Layer – Contains business logic.
• Repository Layer – Communicates with the database.
• Model/Entity Layer – Represents database tables as Java objects.
Spring Boot CRUD REST API
REST Endpoints at a Glance
Method Endpoint Action
GET /api/users Fetch all users
GET /api/users/{id} Fetch user by ID
POST /api/users Create a new user
PUT /api/users/{id} Update an existing user
DELETE /api/users/{id} Delete a user

Controller Example
@RestController
@RequestMapping("/api/users")
public class UserController {

@Autowired
private UserService userService;

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

@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
[Link](id);
return [Link]().build();
}
}
Best Practices & Tips
General Java Best Practices
• Use meaningful variable and method names to improve readability.
• Prefer interfaces over concrete classes when declaring variables (e.g., List instead of ArrayList).
• Always close resources (streams, connections) using try-with-resources.
• Avoid null returns; use Optional<T> introduced in Java 8.
• Use final for variables that should not be reassigned.
• Favor composition over inheritance when designing classes.
• Write unit tests for every service method using JUnit and Mockito.

Spring Boot Best Practices


• Keep controller methods thin — put business logic in the service layer.
• Use @Transactional in service methods that modify data.
• Validate request bodies with @Valid and Bean Validation annotations.
• Use DTOs (Data Transfer Objects) to separate API responses from entities.
• Centralize error handling with @ControllerAdvice and @ExceptionHandler.
• Store configuration in [Link] or [Link].

Keep coding, keep learning — Java rewards consistency and curiosity. ■

You might also like