[Go to site: main page, start]

0% found this document useful (0 votes)
4 views40 pages

Complete Java Programming Guide

The document is a comprehensive Java Programming Guide covering essential topics such as Java Basics, Object-Oriented Programming, Core Java Concepts, Collections Framework, Exception Handling, and Multithreading. It includes code examples for various concepts like data types, control flow, classes, inheritance, polymorphism, and exception handling. Additionally, it discusses modern Java features and best practices for effective programming.

Uploaded by

kottalarishi
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)
4 views40 pages

Complete Java Programming Guide

The document is a comprehensive Java Programming Guide covering essential topics such as Java Basics, Object-Oriented Programming, Core Java Concepts, Collections Framework, Exception Handling, and Multithreading. It includes code examples for various concepts like data types, control flow, classes, inheritance, polymorphism, and exception handling. Additionally, it discusses modern Java features and best practices for effective programming.

Uploaded by

kottalarishi
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

Complete Java Programming Guide

Table of Contents
1. Java Basics
2. Object-Oriented Programming
3. Core Java Concepts
4. Collections Framework
5. Exception Handling
6. Multithreading
7. Java I/O
8. Modern Java Features
9. Best Practices

Java Basics
Hello World

java

public class HelloWorld {


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

Data Types

Primitive Types:

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): decimal numbers
double (64-bit): decimal numbers
boolean: true or false
char (16-bit): Unicode character

Reference Types: Objects, Arrays, Strings

Variables and Constants

java
// Variables
int age = 25;
String name = "John";
double salary = 50000.50;

// Constants
final double PI = 3.14159;
final int MAX_SIZE = 100;

Operators

java

// Arithmetic: +, -, *, /, %
int sum = 10 + 5;
int mod = 10 % 3;

// Comparison: ==, !=, <, >, <=, >=


boolean isEqual = (5 == 5);

// Logical: &&, ||, !


boolean result = (true && false) || true;

// Assignment: =, +=, -=, *=, /=, %=


int x = 10;
x += 5; // x = x + 5

Control Flow

java
// If-Else
if (age >= 18) {
[Link]("Adult");
} else if (age >= 13) {
[Link]("Teenager");
} else {
[Link]("Child");
}

// Switch
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Other day");
}

// Enhanced Switch (Java 14+)


String result = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};

Loops

java
// For loop
for (int i = 0; i < 10; i++) {
[Link](i);
}

// Enhanced for loop


int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
[Link](num);
}

// While loop
int i = 0;
while (i < 10) {
[Link](i);
i++;
}

// Do-While loop
do {
[Link](i);
i++;
} while (i < 10);

Arrays

java

// Declaration and initialization


int[] numbers = new int[5];
int[] values = {1, 2, 3, 4, 5};

// Multidimensional arrays
int[][] matrix = new int[3][3];
int[][] grid = {{1, 2}, {3, 4}, {5, 6}};

// Array operations
int length = [Link];
numbers[0] = 10;
Object-Oriented Programming
Classes and Objects

java

public class Person {


// Fields (attributes)
private String name;
private int age;

// Constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}

// Methods
public void introduce() {
[Link]("Hi, I'm " + name + " and I'm " + age + " years old.");
}

// Getters and Setters


public String getName() {
return name;
}

public void setName(String name) {


[Link] = name;
}
}

// Creating objects
Person person = new Person("Alice", 30);
[Link]();

Encapsulation

java
public class BankAccount {
private double balance; // Private field

public double getBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
}
}

public boolean withdraw(double amount) {


if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
}

Inheritance

java
// Parent class
public class Animal {
protected String name;

public Animal(String name) {


[Link] = name;
}

public void eat() {


[Link](name + " is eating");
}
}

// Child class
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}

public void bark() {


[Link](name + " is barking");
}

@Override
public void eat() {
[Link](name + " is eating dog food");
}
}

Polymorphism

java
// Method Overloading (Compile-time polymorphism)
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

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


return a + b + c;
}
}

// Method Overriding (Runtime polymorphism)


Animal animal = new Dog("Buddy");
[Link](); // Calls Dog's eat() method

Abstraction

java
// Abstract class
public abstract class Shape {
protected String color;

public abstract double calculateArea();

public void display() {


[Link]("Color: " + color);
}
}

public class Circle extends Shape {


private double radius;

public Circle(double radius, String color) {


[Link] = radius;
[Link] = color;
}

@Override
public double calculateArea() {
return [Link] * radius * radius;
}
}

Interfaces

java
public interface Drawable {
void draw(); // Abstract method (implicitly public abstract)

default void display() { // Default method (Java 8+)


[Link]("Displaying shape");
}

static void info() { // Static method (Java 8+)


[Link]("This is a drawable interface");
}
}

public class Rectangle implements Drawable {


@Override
public void draw() {
[Link]("Drawing rectangle");
}
}

Core Java Concepts


String Handling

java
// String creation
String str1 = "Hello";
String str2 = new String("World");

// String methods
int length = [Link]();
char ch = [Link](0);
String sub = [Link](1, 4);
String upper = [Link]();
String lower = [Link]();
boolean equals = [Link](str2);
boolean contains = [Link]("ell");
String[] parts = "a,b,c".split(",");

// StringBuilder (mutable)
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](5, ",");
[Link](5, 6);
String result = [Link]();

// String formatting
String formatted = [Link]("Name: %s, Age: %d", "John", 25);

Static Members

java
public class Counter {
private static int count = 0; // Shared across all instances
private int id;

public Counter() {
count++;
id = count;
}

public static int getCount() {


return count;
}

public int getId() {


return id;
}
}

// Usage
Counter c1 = new Counter();
Counter c2 = new Counter();
[Link]([Link]()); // 2

Inner Classes

java
public class Outer {
private int x = 10;

// Member inner class


class Inner {
public void display() {
[Link]("x = " + x);
}
}

// Static nested class


static class StaticNested {
public void show() {
[Link]("Static nested class");
}
}

// Method local inner class


public void method() {
class LocalInner {
public void print() {
[Link]("Local inner class");
}
}
new LocalInner().print();
}

// Anonymous inner class


public void anonymousExample() {
Runnable r = new Runnable() {
@Override
public void run() {
[Link]("Anonymous class");
}
};
}
}

Enums

java
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

// Enum with fields and methods


public enum Planet {
MERCURY(3.303e23, 2.4397e6),
EARTH(5.976e24, 6.37814e6),
MARS(6.421e23, 3.3972e6);

private final double mass;


private final double radius;

Planet(double mass, double radius) {


[Link] = mass;
[Link] = radius;
}

public double getMass() {


return mass;
}
}

// Usage
Day today = [Link];
switch (today) {
case MONDAY:
[Link]("Start of week");
break;
default:
[Link]("Other day");
}

Collections Framework
List Interface

java
// ArrayList
List<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link](1, "Cherry"); // Insert at index
[Link]("Apple");
[Link](0);
String item = [Link](0);
int size = [Link]();
boolean contains = [Link]("Banana");

// LinkedList
List<String> linkedList = new LinkedList<>();
[Link]("First");
[Link]("Last");

// Vector (synchronized)
List<String> vector = new Vector<>();

Set Interface

java

// HashSet (unordered, unique elements)


Set<Integer> hashSet = new HashSet<>();
[Link](1);
[Link](2);
[Link](1); // Duplicate, won't be added

// LinkedHashSet (maintains insertion order)


Set<String> linkedHashSet = new LinkedHashSet<>();

// TreeSet (sorted)
Set<Integer> treeSet = new TreeSet<>();
[Link](5);
[Link](1);
[Link](3); // Stored as: 1, 3, 5

Map Interface
java

// HashMap
Map<String, Integer> map = new HashMap<>();
[Link]("Alice", 25);
[Link]("Bob", 30);
Integer age = [Link]("Alice");
[Link]("Bob");
boolean hasKey = [Link]("Alice");
boolean hasValue = [Link](25);

// Iterating
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + ": " + [Link]());
}

// LinkedHashMap (maintains insertion order)


Map<String, Integer> linkedMap = new LinkedHashMap<>();

// TreeMap (sorted by keys)


Map<String, Integer> treeMap = new TreeMap<>();

Queue and Deque

java
// Queue (FIFO)
Queue<String> queue = new LinkedList<>();
[Link]("First");
[Link]("Second");
String head = [Link](); // Removes and returns head
String peek = [Link](); // Returns head without removing

// PriorityQueue (natural ordering)


Queue<Integer> pq = new PriorityQueue<>();
[Link](5);
[Link](1);
[Link](3);
[Link]([Link]()); // 1

// Deque (Double-ended queue)


Deque<String> deque = new ArrayDeque<>();
[Link]("First");
[Link]("Last");
[Link]();
[Link]();

Collections Utility Class

java
List<Integer> list = [Link](3, 1, 4, 1, 5);

[Link](list); // Sort
[Link](list); // Reverse
[Link](list); // Shuffle
int max = [Link](list);
int min = [Link](list);
int freq = [Link](list, 1);
[Link](list, 0); // Fill with value

// Binary search (list must be sorted)


int index = [Link](list, 3);

// Synchronized collections
List<String> syncList = [Link](new ArrayList<>());

// Unmodifiable collections
List<String> immutable = [Link](list);

Exception Handling
Try-Catch-Finally

java
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
} finally {
[Link]("This always executes");
}

// Multiple catch blocks


try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
} catch (Exception e) {
[Link]("General error");
}

// Multi-catch (Java 7+)


try {
// code
} catch (IOException | SQLException e) {
[Link]("IO or SQL error");
}

Try-with-Resources

java

// Automatic resource management (Java 7+)


try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line = [Link]();
} catch (IOException e) {
[Link]();
}
// br is automatically closed

Throwing Exceptions

java
public void checkAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}

// Checked exceptions must be declared


public void readFile() throws IOException {
FileReader fr = new FileReader("[Link]");
}

Custom Exceptions

java

public class InsufficientFundsException extends Exception {


private double amount;

public InsufficientFundsException(double amount) {


super("Insufficient funds: " + amount);
[Link] = amount;
}

public double getAmount() {


return amount;
}
}

// Usage
public void withdraw(double amount) throws InsufficientFundsException {
if (balance < amount) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
Multithreading
Creating Threads

java

// Method 1: Extending Thread class


class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + ": " + i);
}
}
}

MyThread t1 = new MyThread();


[Link]();

// Method 2: Implementing Runnable


class MyRunnable implements Runnable {
@Override
public void run() {
[Link]("Thread running: " + [Link]().getName());
}
}

Thread t2 = new Thread(new MyRunnable());


[Link]();

// Lambda expression (Java 8+)


Thread t3 = new Thread(() -> {
[Link]("Lambda thread");
} );
[Link]();

Thread Methods

java
Thread t = new Thread(() -> {
// Thread code
} );

[Link](); // Start the thread


[Link](); // Wait for thread to complete
[Link](1000); // Sleep for 1 second
[Link](Thread.MAX_PRIORITY); // Set priority (1-10)
[Link](true); // Daemon thread
String name = [Link]();
boolean isAlive = [Link]();

Synchronization

java

public class Counter {


private int count = 0;

// Synchronized method
public synchronized void increment() {
count++;
}

// Synchronized block
public void decrement() {
synchronized(this) {
count--;
}
}

public int getCount() {


return count;
}
}

Wait and Notify

java
class SharedResource {
private boolean available = false;

public synchronized void produce() {


while (available) {
try {
wait(); // Release lock and wait
} catch (InterruptedException e) {
[Link]();
}
}
[Link]("Produced");
available = true;
notify(); // Notify waiting thread
}

public synchronized void consume() {


while (!available) {
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
[Link]("Consumed");
available = false;
notify();
}
}

ExecutorService

java
ExecutorService executor = [Link](5);

// Submit tasks
[Link](() -> {
[Link]("Task 1");
} );

[Link](() -> {
[Link]("Task 2");
} );

// Shutdown
[Link]();

// Future for return values


Future<Integer> future = [Link](() -> {
return 42;
} );

try {
Integer result = [Link](); // Blocking call
} catch (Exception e) {
[Link]();
}

Java I/O
File Operations

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

// Check if file exists


File file = new File("[Link]");
boolean exists = [Link]();
boolean isFile = [Link]();
boolean isDir = [Link]();

// Create file/directory
[Link]();
new File("mydir").mkdir();
new File("path/to/dir").mkdirs();

// Delete file
[Link]();

// List files
File dir = new File(".");
String[] files = [Link]();
File[] fileArray = [Link]();

Reading Files

java
// BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}

// Scanner
try (Scanner scanner = new Scanner(new File("[Link]"))) {
while ([Link]()) {
String line = [Link]();
[Link](line);
}
}

// Files (Java 7+)


List<String> lines = [Link]([Link]("[Link]"));
String content = [Link]([Link]("[Link]")); // Java 11+

Writing Files

java
// BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello World");
[Link]();
[Link]("Second line");
} catch (IOException e) {
[Link]();
}

// PrintWriter
try (PrintWriter pw = new PrintWriter("[Link]")) {
[Link]("Line 1");
[Link]("Line 2");
}

// Files (Java 7+)


[Link]([Link]("[Link]"), "Content".getBytes());
[Link]([Link]("[Link]"), "Content"); // Java 11+

Serialization

java
// Serializable class
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;

public Person(String name, int age) {


[Link] = name;
[Link] = age;
}
}

// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("[Link]"))) {
Person person = new Person("Alice", 30);
[Link](person);
}

// Deserialize
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("[Link]"))) {
Person person = (Person) [Link]();
}

Modern Java Features


Lambda Expressions (Java 8)

java
// Syntax: (parameters) -> expression or {statements}

// No parameters
Runnable r = () -> [Link]("Hello");

// Single parameter
Consumer<String> print = s -> [Link](s);

// Multiple parameters
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;

// With block
Comparator<String> comp = (s1, s2) -> {
int len1 = [Link]();
int len2 = [Link]();
return [Link](len1, len2);
};

Streams API (Java 8)

java
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Filter and collect


List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0)
.collect([Link]());

// Map
List<Integer> squares = [Link]()
.map(n -> n * n)
.collect([Link]());

// Reduce
int sum = [Link]()
.reduce(0, (a, b) -> a + b);

// Sorted
List<String> sorted = [Link]()
.sorted()
.collect([Link]());

// ForEach
[Link]().forEach([Link]::println);

// Count
long count = [Link]()
.filter(n -> n > 5)
.count();

// AnyMatch, AllMatch, NoneMatch


boolean hasEven = [Link]().anyMatch(n -> n % 2 == 0);
boolean allPositive = [Link]().allMatch(n -> n > 0);

// Distinct
List<Integer> unique = [Link]()
.distinct()
.collect([Link]());

// Limit and Skip


List<Integer> limited = [Link]()
.limit(5)
.collect([Link]());
Optional (Java 8)

java

// Creating Optional
Optional<String> optional = [Link]("Hello");
Optional<String> empty = [Link]();
Optional<String> nullable = [Link](null);

// Checking and retrieving


if ([Link]()) {
String value = [Link]();
}

// ifPresent with consumer


[Link](s -> [Link](s));

// orElse
String result = [Link]("Default");

// orElseGet
String result2 = [Link](() -> "Computed default");

// orElseThrow
String result3 = [Link](() -> new RuntimeException("Not found"));

// map and flatMap


Optional<Integer> length = [Link](String::length);

// filter
Optional<String> filtered = [Link](s -> [Link]() > 3);

Method References (Java 8)

java
// Static method reference
Function<String, Integer> parser = Integer::parseInt;

// Instance method reference


String str = "Hello";
Supplier<Integer> lengthGetter = str::length;

// Constructor reference
Supplier<List<String>> listFactory = ArrayList::new;

// Usage in streams
List<String> strings = [Link]("a", "b", "c");
[Link]([Link]::println);

List<Integer> lengths = [Link]()


.map(String::length)
.collect([Link]());

Default and Static Methods in Interfaces (Java 8)

java

interface Vehicle {
// Abstract method
void start();

// Default method
default void stop() {
[Link]("Vehicle stopped");
}

// Static method
static void service() {
[Link]("Servicing vehicle");
}
}

Records (Java 14+)

java
// Concise data class
public record Person(String name, int age) {
// Compact constructor
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}

// Usage
Person person = new Person("Alice", 30);
[Link]([Link]()); // Auto-generated accessor
[Link](person); // Auto-generated toString()

Text Blocks (Java 15+)

java

String json = """


{
"name": "John",
"age": 30,
"city": "New York"
}
""";

String html = """


<html>
<body>
<h1>Hello World</h1>
</body>
</html>
""";

Pattern Matching (Java 16+)

java
// instanceof with pattern matching
if (obj instanceof String s) {
[Link]([Link]());
}

// Switch with pattern matching (Java 17+)


Object obj = "Hello";
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
case null -> "Null value";
default -> "Unknown type";
};

Sealed Classes (Java 17+)

java

public sealed class Shape permits Circle, Rectangle, Triangle {


// Common methods
}

public final class Circle extends Shape {


// Circle implementation
}

public final class Rectangle extends Shape {


// Rectangle implementation
}

public non-sealed class Triangle extends Shape {


// Triangle can be extended
}

Best Practices
Naming Conventions

Classes: PascalCase (e.g., MyClass, PersonDetails)


Methods: camelCase (e.g., calculateTotal, getName)
Variables: camelCase (e.g., firstName, totalAmount)
Constants: UPPER_SNAKE_CASE (e.g., MAX_SIZE, PI)
Packages: lowercase (e.g., [Link])

Code Organization

java
// 1. Package declaration
package [Link];

// 2. Import statements
import [Link].*;
import [Link].*;

// 3. Class declaration with documentation


/**
* Represents a bank account with basic operations.
* @author Your Name
* @version 1.0
*/
public class BankAccount {
// 4. Static variables
private static int accountCount = 0;

// 5. Instance variables
private String accountNumber;
private double balance;

// 6. Constructors
public BankAccount(String accountNumber) {
[Link] = accountNumber;
accountCount++;
}

// 7. Methods
public void deposit(double amount) {
// Implementation
}

// 8. Getters/Setters
public double getBalance() {
return balance;
}

// 9. Static methods
public static int getAccountCount() {
return accountCount;
}
}
Common Patterns

java
// Singleton Pattern
public class Singleton {
private static Singleton instance;

private Singleton() {}

public static synchronized Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

// Builder Pattern
public class User {
private final String firstName;
private final String lastName;
private final int age;

private User(Builder builder) {


[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}

public static class Builder {


private String firstName;
private String lastName;
private int age;

public Builder firstName(String firstName) {


[Link] = firstName;
return this;
}

public Builder lastName(String lastName) {


[Link] = lastName;
return this;
}

public Builder age(int age) {


[Link] = age;
return this;
}

public User build() {


return new User(this);
}
}
}

// Usage
User user = new [Link]()
.firstName("John")
.lastName("Doe")
.age(30)
.build();

Performance Tips
1. Use StringBuilder for string concatenation in loops
2. Initialize collections with capacity when size is known
3. Use enhanced for loop for iteration
4. Close resources properly (use try-with-resources)
5. Avoid creating unnecessary objects
6. Use primitives instead of wrappers when possible
7. Cache frequently used objects
8. Use lazy initialization when appropriate

Security Best Practices

1. Validate all user input


2. Use PreparedStatement to prevent SQL injection
3. Don't hardcode credentials
4. Use secure random number generators
5. Avoid serialization of sensitive data
6. Keep dependencies updated
7. Use proper exception handling (don't expose stack traces)

Testing

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

public class CalculatorTest {


@Test
public void testAddition() {
Calculator calc = new Calculator();
assertEquals(5, [Link](2, 3));
}

@Test
public void testDivisionByZero() {
Calculator calc = new Calculator();
assertThrows([Link], () -> {
[Link](10, 0);
} );
}
}

Quick Reference
Common Classes to Know

String: Text manipulation


StringBuilder/StringBuffer: Mutable strings
Math: Mathematical

You might also like