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

Java Packages Comprehensive Guide

The document is a comprehensive learning guide on Java packages, covering various core packages such as java.lang, java.util, java.io, and more. It includes explanations, examples, and key methods for each package, along with topics like enumerations, collections, input/output, and security. The guide serves as a complete reference for understanding and utilizing Java's package system effectively.

Uploaded by

24761a05bd
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)
10 views20 pages

Java Packages Comprehensive Guide

The document is a comprehensive learning guide on Java packages, covering various core packages such as java.lang, java.util, java.io, and more. It includes explanations, examples, and key methods for each package, along with topics like enumerations, collections, input/output, and security. The guide serves as a complete reference for understanding and utilizing Java's package system effectively.

Uploaded by

24761a05bd
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 Packages Learning Guide

Table of Contents
All Topics in One File - Easy to Learn with Examples

Table of Contents
1. Java Package System Basics
What is a Package?
2. [Link] Package - Core Java

2.1 Object Class (Root of All Classes)


2.2 String Class
2.3 StringBuilder (Mutable Strings)

2.4 Wrapper Classes & Autoboxing

2.5 Math Class


3. Enumerations (Enums)
4. [Link] Package - Collections & Utilities
4.1 ArrayList (Dynamic Array)
4.2 HashMap (Key-Value Pairs)
4.3 HashSet (Unique Elements)
5. [Link] Package - Input/Output

5.1 File Writing (FileWriter)


5.2 File Reading (BufferedReader)
5.3 File Operations (File Class)
6. [Link] Package - Networking
6.1 URL Connection
6.2 InetAddress

7. [Link] Package - Database


8. [Link] & [Link] - GUI

9. [Link] Package - Security


9.1 SHA-256 Hash
9.2 SecureRandom
9.3 AES Encryption
10. [Link] Package - Formatting
10.1 Date Formatting
10.2 Number Formatting
10.3 MessageFormat
11. Quick Reference Tables
Package Summary
Common String Methods
Collection Comparison
I/O Stream Types
All Topics in One File - Easy to Learn with Examples
Complete reference for [Link], [Link], [Link], [Link], [Link], [Link], [Link], [Link], and [Link]

Table of Contents
1. Java Package System Basics
2. [Link] Package - Core Java
3. Enumerations (Enums)

4. [Link] Package - Collections & Utilities


5. [Link] Package - Input/Output
6. [Link] Package - Networking

7. [Link] Package - Database


8. [Link] & [Link] - GUI
9. [Link] Package - Security

10. [Link] Package - Formatting


11. Quick Reference Tables

1. Java Package System Basics


What is a Package?
A package is a folder/namespace that organizes related classes and interfaces.

Syntax:

package [Link]; // Declare package

import [Link]; // Import specific class


import [Link].*; // Import all classes from package

Example: Creating and Using Package

// File: com/myapp/models/[Link]
package [Link];

public class Student {


private String name;
private int rollNo;

public Student(String name, int rollNo) {


[Link] = name;
[Link] = rollNo;
}

public String toString() {


return "Student[" + name + ", " + rollNo + "]";
}
}

// File: com/myapp/[Link]
package [Link];

import [Link];

public class Main {


public static void main(String[] args) {
Student s = new Student("Alice", 101);
[Link](s);
}
}

Output:

Student[Alice, 101]

2. [Link] Package - Core Java


Auto-imported in every Java program. Contains fundamental classes.

2.1 Object Class (Root of All Classes)


Key Methods:

toString() - String representation

equals() - Compare objects

hashCode() - Hash value

getClass() - Runtime class info

Example:

class Person {
String name;
int age;

Person(String name, int age) {


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

@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Person)) return false;
Person p = (Person) obj;
return age == [Link] && [Link]([Link]);
}
}

public class ObjectDemo {


public static void main(String[] args) {
Person p1 = new Person("Alice", 25);
Person p2 = new Person("Alice", 25);

[Link]("p1: " + p1);


[Link]("p2: " + p2);
[Link]("Are equal? " + [Link](p2));
[Link]("Same reference? " + (p1 == p2));
}
}

Output:

p1: Person{name='Alice', age=25}


p2: Person{name='Alice', age=25}
Are equal? true
Same reference? false
2.2 String Class
Key Methods:

length() - Number of characters

charAt(i) - Character at index

substring(start, end) - Extract substring

indexOf(str) - Find position

toLowerCase() / toUpperCase() - Change case

trim() - Remove whitespace

split(regex) - Split into array

replace(old, new) - Replace characters

equals() / equalsIgnoreCase() - Compare

Example 1: Basic String Operations

public class StringBasics {


public static void main(String[] args) {
String text = " Hello World ";

[Link]("Original: '" + text + "'");


[Link]("Length: " + [Link]());
[Link]("Trimmed: '" + [Link]() + "'");
[Link]("Uppercase: " + [Link]());
[Link]("Character at 2: " + [Link](2));
[Link]("Index of 'World': " + [Link]("World"));
[Link]("Substring(2,7): '" + [Link](2, 7) + "'");
}
}

Output:

Original: ' Hello World '


Length: 15
Trimmed: 'Hello World'
Uppercase: HELLO WORLD
Character at 2: H
Index of 'World': 8
Substring(2,7): 'Hello'

Example 2: String Manipulation

public class StringManipulation {


public static void main(String[] args) {
String email = "user@[Link]";

// Split at @
String[] parts = [Link]("@");
[Link]("Username: " + parts[0]);
[Link]("Domain: " + parts[1]);

// Replace
String censored = [Link]("user", "****");
[Link]("Censored: " + censored);

// Check conditions
[Link]("Contains '@': " + [Link]("@"));
[Link]("Starts with 'user': " + [Link]("user"));
[Link]("Ends with '.com': " + [Link](".com"));
}
}

Output:
Username: user
Domain: [Link]
Censored: ****@[Link]
Contains '@': true
Starts with 'user': true
Ends with '.com': true

2.3 StringBuilder (Mutable Strings)


Why use it? String is immutable. StringBuilder is mutable and efficient for concatenation.

Key Methods:

append(str) - Add to end

insert(index, str) - Insert at position

delete(start, end) - Remove characters

reverse() - Reverse string

toString() - Convert to String

Example:

public class StringBuilderDemo {


public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");

[Link]("Initial: " + sb);

[Link](" World");
[Link]("After append: " + sb);

[Link](5, ",");
[Link]("After insert: " + sb);

[Link](5, 6);
[Link]("After delete: " + sb);

[Link]();
[Link]("Reversed: " + sb);

String result = [Link]();


[Link]("Final string: " + result);
}
}

Output:

Initial: Hello
After append: Hello World
After insert: Hello, World
After delete: Hello World
Reversed: dlroW olleH
Final string: dlroW olleH

2.4 Wrapper Classes & Autoboxing


Wrapper classes convert primitives to objects.

Primitive Wrapper Class

int Integer

double Double
Primitive Wrapper Class

boolean Boolean

char Character

long Long

float Float

Example:

public class WrapperDemo {


public static void main(String[] args) {
// Autoboxing (primitive → object)
Integer num = 100;
Double pi = 3.14;

// Unboxing (object → primitive)


int n = num;
double p = pi;

[Link]("Integer: " + num);


[Link]("int: " + n);

// Parsing
int parsed = [Link]("123");
[Link]("Parsed: " + parsed);

// Constants
[Link]("Integer MAX: " + Integer.MAX_VALUE);
[Link]("Integer MIN: " + Integer.MIN_VALUE);

// Conversion
String binary = [Link](10);
String hex = [Link](255);
[Link]("10 in binary: " + binary);
[Link]("255 in hex: " + hex);
}
}

Output:

Integer: 100
int: 100
Parsed: 123
Integer MAX: 2147483647
Integer MIN: -2147483648
10 in binary: 1010
255 in hex: ff

2.5 Math Class


Key Methods:

abs(x) - Absolute value

max(a, b) / min(a, b) - Maximum/Minimum

pow(base, exp) - Power

sqrt(x) - Square root

ceil(x) / floor(x) / round(x) - Rounding

random() - Random 0.0 to 1.0

sin(), cos(), tan() - Trigonometry


Example:

public class MathDemo {


public static void main(String[] args) {
[Link]("abs(-5): " + [Link](-5));
[Link]("max(10, 20): " + [Link](10, 20));
[Link]("pow(2, 3): " + [Link](2, 3));
[Link]("sqrt(16): " + [Link](16));
[Link]("ceil(3.2): " + [Link](3.2));
[Link]("floor(3.8): " + [Link](3.8));
[Link]("round(3.5): " + [Link](3.5));

// Random number between 1-100


int random = (int)([Link]() * 100) + 1;
[Link]("Random 1-100: " + random);

[Link]("PI: " + [Link]);


[Link]("E: " + Math.E);
}
}

Output:

abs(-5): 5
max(10, 20): 20
pow(2, 3): 8.0
sqrt(16): 4.0
ceil(3.2): 4.0
floor(3.8): 3.0
round(3.5): 4
Random 1-100: 42
PI: 3.141592653589793
E: 2.718281828459045

3. Enumerations (Enums)
Enums define a fixed set of constants.

Example 1: Basic Enum

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

public class EnumBasic {


public static void main(String[] args) {
Day today = [Link];

[Link]("Today is: " + today);

// Switch statement
switch(today) {
case MONDAY:
[Link]("Start of work week");
break;
case FRIDAY:
[Link]("Almost weekend!");
break;
case SATURDAY:
case SUNDAY:
[Link]("Weekend!");
break;
}

// Loop through all values


[Link]("\nAll days:");
for (Day d : [Link]()) {
[Link](d);
}
}
}

Output:

Today is: MONDAY


Start of work week

All days:
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Example 2: Enum with Fields and Methods

enum Size {
SMALL("S", 10),
MEDIUM("M", 20),
LARGE("L", 30),
XLARGE("XL", 40);

private String code;


private int price;

Size(String code, int price) {


[Link] = code;
[Link] = price;
}

public String getCode() { return code; }


public int getPrice() { return price; }
}

public class EnumAdvanced {


public static void main(String[] args) {
Size mySize = [Link];

[Link]("Size: " + mySize);


[Link]("Code: " + [Link]());
[Link]("Price: $" + [Link]());

[Link]("\nAll sizes:");
for (Size s : [Link]()) {
[Link](s + " (" + [Link]() + ") = $" + [Link]());
}
}
}

Output:

Size: MEDIUM
Code: M
Price: $20

All sizes:
SMALL (S) = $10
MEDIUM (M) = $20
LARGE (L) = $30
XLARGE (XL) = $40
4. [Link] Package - Collections & Utilities
4.1 ArrayList (Dynamic Array)
Key Methods:

add(element) - Add element

get(index) - Get element

set(index, element) - Replace element

remove(index) - Remove element

size() - Number of elements

contains(element) - Check if exists

Example:

import [Link];

public class ArrayListDemo {


public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();

// Add elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

[Link]("Fruits: " + fruits);


[Link]("Size: " + [Link]());

// Access element
[Link]("First fruit: " + [Link](0));

// Modify element
[Link](1, "Blueberry");
[Link]("After modification: " + fruits);

// Check if contains
[Link]("Contains Apple? " + [Link]("Apple"));

// Remove element
[Link](0);
[Link]("After removal: " + fruits);

// Loop through
[Link]("\nLooping:");
for (String fruit : fruits) {
[Link]("- " + fruit);
}
}
}

Output:

Fruits: [Apple, Banana, Cherry]


Size: 3
First fruit: Apple
After modification: [Apple, Blueberry, Cherry]
Contains Apple? true
After removal: [Blueberry, Cherry]

Looping:
- Blueberry
- Cherry
4.2 HashMap (Key-Value Pairs)
Key Methods:

put(key, value) - Add/update entry

get(key) - Get value by key

remove(key) - Remove entry

containsKey(key) - Check if key exists

keySet() - Get all keys

values() - Get all values

Example:

import [Link];

public class HashMapDemo {


public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();

// Add entries
[Link]("Alice", 95);
[Link]("Bob", 87);
[Link]("Charlie", 92);

[Link]("Scores: " + scores);

// Get value
[Link]("Alice's score: " + [Link]("Alice"));

// Update value
[Link]("Bob", 90);
[Link]("Updated Bob's score: " + [Link]("Bob"));

// Check if key exists


[Link]("Contains Charlie? " + [Link]("Charlie"));

// Loop through entries


[Link]("\nAll scores:");
for (String name : [Link]()) {
[Link](name + ": " + [Link](name));
}
}
}

Output:

Scores: {Alice=95, Bob=87, Charlie=92}


Alice's score: 95
Updated Bob's score: 90
Contains Charlie? true

All scores:
Alice: 95
Bob: 90
Charlie: 92

4.3 HashSet (Unique Elements)


Example:

import [Link];

public class HashSetDemo {


public static void main(String[] args) {
HashSet<String> cities = new HashSet<>();
[Link]("Delhi");
[Link]("Mumbai");
[Link]("Delhi"); // Duplicate - won't be added
[Link]("Bangalore");

[Link]("Cities: " + cities);


[Link]("Size: " + [Link]());
[Link]("Contains Mumbai? " + [Link]("Mumbai"));

[Link]("Mumbai");
[Link]("After removal: " + cities);
}
}

Output:

Cities: [Delhi, Mumbai, Bangalore]


Size: 3
Contains Mumbai? true
After removal: [Delhi, Bangalore]

5. [Link] Package - Input/Output


5.1 File Writing (FileWriter)
Example:

import [Link].*;

public class FileWriteDemo {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello, File I/O!\n");
[Link]("This is line 2.\n");
[Link]("End of file.");
[Link]();

[Link]("✓ File written successfully!");


} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}

Output:

✓ File written successfully!

File Contents ([Link]):

Hello, File I/O!


This is line 2.
End of file.
5.2 File Reading (BufferedReader)
Example:

import [Link].*;

public class FileReadDemo {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("[Link]"));

[Link]("=== File Contents ===");


String line;
int lineNum = 1;

while ((line = [Link]()) != null) {


[Link](lineNum + ". " + line);
lineNum++;
}

[Link]();
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}

Output:

=== File Contents ===


1. Hello, File I/O!
2. This is line 2.
3. End of file.

5.3 File Operations (File Class)


Example:

import [Link].*;

public class FileOperations {


public static void main(String[] args) {
File file = new File("[Link]");

[Link]("File name: " + [Link]());


[Link]("Exists: " + [Link]());
[Link]("Can read: " + [Link]());
[Link]("Can write: " + [Link]());
[Link]("Size: " + [Link]() + " bytes");
[Link]("Is file: " + [Link]());
[Link]("Is directory: " + [Link]());
}
}

Output:

File name: [Link]


Exists: true
Can read: true
Can write: true
Size: 45 bytes
Is file: true
Is directory: false
6. [Link] Package - Networking
6.1 URL Connection

Example:

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

public class URLDemo {


public static void main(String[] args) {
try {
URL url = new URL("[Link]

[Link]("Protocol: " + [Link]());


[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Path: " + [Link]());

[Link]("\nReading content...");
BufferedReader reader = new BufferedReader(
new InputStreamReader([Link]())
);

String line;
int lines = 0;
while ((line = [Link]()) != null && lines < 5) {
[Link](line);
lines++;
}
[Link]();

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}

6.2 InetAddress
Example:

import [Link].*;

public class InetAddressDemo {


public static void main(String[] args) {
try {
InetAddress local = [Link]();
[Link]("Local Host: " + [Link]());
[Link]("Local IP: " + [Link]());

InetAddress google = [Link]("[Link]");


[Link]("\nGoogle Host: " + [Link]());
[Link]("Google IP: " + [Link]());

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}

Output:

Local Host: YourComputer


Local IP: [Link]
Google Host: [Link]
Google IP: [Link]

7. [Link] Package - Database


Example: JDBC Connection

import [Link].*;

public class JDBCDemo {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";

try {
// Connect to database
Connection conn = [Link](url, user, password);
[Link]("✓ Connected to database!");

// Create statement
Statement stmt = [Link]();

// Execute query
ResultSet rs = [Link]("SELECT * FROM users");

// Process results
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link]("ID: " + id + ", Name: " + name);
}

// Close connections
[Link]();
[Link]();
[Link]();

} catch (SQLException e) {
[Link]("Error: " + [Link]());
}
}
}

Example: PreparedStatement (Safer)

import [Link].*;

public class PreparedStatementDemo {


public static void main(String[] args) {
try {
Connection conn = [Link](url, user, password);

// Insert with PreparedStatement


String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement pstmt = [Link](sql);

[Link](1, "Alice");
[Link](2, 25);

int rows = [Link]();


[Link](rows + " row(s) inserted");

[Link]();
[Link]();

} catch (SQLException e) {
[Link]("Error: " + [Link]());
}
}
}

8. [Link] & [Link] - GUI


Example: Simple Swing Window

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

public class SimpleGUI extends JFrame {


private JTextField nameField;
private JLabel resultLabel;

public SimpleGUI() {
setTitle("Simple GUI Demo");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Components
JLabel nameLabel = new JLabel("Enter your name:");
nameField = new JTextField(20);
JButton submitButton = new JButton("Submit");
resultLabel = new JLabel("");

// Button action
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = [Link]();
[Link]("Hello, " + name + "!");
}
});

// Add components
add(nameLabel);
add(nameField);
add(submitButton);
add(resultLabel);

setVisible(true);
}

public static void main(String[] args) {


new SimpleGUI();
}
}

9. [Link] Package - Security


9.1 SHA-256 Hash
Example:

import [Link].*;

public class HashDemo {


public static void main(String[] args) {
try {
String data = "Hello Security";

MessageDigest md = [Link]("SHA-256");
byte[] hash = [Link]([Link]());
// Convert to hex
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
[Link]([Link]("%02x", b));
}

[Link]("Original: " + data);


[Link]("SHA-256: " + [Link]());

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}

Output:

Original: Hello Security


SHA-256: 8c7dd922ad47494fc02c388e12c00eac278d4e6e8c0a8ae7c60f4e6c74c0d08f

9.2 SecureRandom
Example:

import [Link];

public class SecureRandomDemo {


public static void main(String[] args) {
SecureRandom sr = new SecureRandom();

// Random integer
int randomInt = [Link](100);
[Link]("Random (0-99): " + randomInt);

// Random password
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder password = new StringBuilder();
for (int i = 0; i < 8; i++) {
[Link]([Link]([Link]([Link]())));
}
[Link]("Random password: " + password);
}
}

Output:

Random (0-99): 42
Random password: aK9mP2xL

9.3 AES Encryption


Example:

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

public class AESDemo {


public static void main(String[] args) {
try {
String plainText = "Secret Message";
byte[] keyBytes = "1234567890123456".getBytes(); // 16 bytes
SecretKey key = new SecretKeySpec(keyBytes, "AES");

// Encrypt
Cipher cipher = [Link]("AES");
[Link](Cipher.ENCRYPT_MODE, key);
byte[] encrypted = [Link]([Link]());
String encryptedBase64 = [Link]().encodeToString(encrypted);

[Link]("Original: " + plainText);


[Link]("Encrypted: " + encryptedBase64);

// Decrypt
[Link](Cipher.DECRYPT_MODE, key);
byte[] decrypted = [Link](encrypted);
String decryptedText = new String(decrypted);

[Link]("Decrypted: " + decryptedText);

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}

Output:

Original: Secret Message


Encrypted: 7Kj9mP3xQ8vL2nR5wT1yF4dS6aZ8bC0e
Decrypted: Secret Message

10. [Link] Package - Formatting


10.1 Date Formatting
Example:

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

public class DateFormatDemo {


public static void main(String[] args) {
Date now = new Date();

SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");


SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss");

[Link]("Current date: " + now);


[Link]("Format 1: " + [Link](now));
[Link]("Format 2: " + [Link](now));
[Link]("Format 3: " + [Link](now));

// Parse date
try {
Date parsed = [Link]("25/10/2025");
[Link]("Parsed date: " + parsed);
} catch (ParseException e) {
[Link]();
}
}
}

Output:

Current date: Sat Oct 25 11:30:45 IST 2025


Format 1: 25/10/2025
Format 2: October 25, 2025
Format 3: 11:30:45
Parsed date: Sat Oct 25 00:00:00 IST 2025
10.2 Number Formatting
Example:

import [Link].*;

public class NumberFormatDemo {


public static void main(String[] args) {
double number = 12345.6789;

NumberFormat nf = [Link]();
NumberFormat cf = [Link]();
NumberFormat pf = [Link]();

[Link]("Number: " + [Link](number));


[Link]("Currency: " + [Link](number));
[Link]("Percent: " + [Link](0.75));

// Custom format
DecimalFormat df = new DecimalFormat("#,##0.00");
[Link]("Custom: " + [Link](number));
}
}

Output:

Number: 12,345.679
Currency: $12,345.68
Percent: 75%
Custom: 12,345.68

10.3 MessageFormat
Example:

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

public class MessageFormatDemo {


public static void main(String[] args) {
String pattern = "Hello {0}, your balance is ${1} as of {2}";
Object[] args = {"Alice", 1500.50, new Date()};

String message = [Link](pattern, args);


[Link](message);
}
}

Output:

Hello Alice, your balance is $1500.5 as of 10/25/25 11:30 AM

11. Quick Reference Tables


Package Summary

Package Purpose Key Classes

[Link] Core language features Object, String, Math, Integer, Thread

[Link] Collections, utilities ArrayList, HashMap, Scanner, Random


Package Purpose Key Classes

[Link] Input/Output operations File, FileReader, BufferedReader

[Link] Networking URL, Socket, InetAddress

[Link] Database connectivity Connection, Statement, ResultSet

[Link] GUI (heavyweight) Frame, Button, Label

[Link] GUI (lightweight) JFrame, JButton, JLabel

[Link] Security, cryptography MessageDigest, SecureRandom, Cipher

[Link] Text formatting DateFormat, NumberFormat, MessageFormat

Common String Methods

Method Description Example

length() Get length "hello".length() → 5

charAt(i) Get character "hello".charAt(0) → 'h'

substring(i, j) Extract substring "hello".substring(0,2) → "he"

toLowerCase() Convert to lowercase "HELLO".toLowerCase() → "hello"

toUpperCase() Convert to uppercase "hello".toUpperCase() → "HELLO"

trim() Remove spaces " hi ".trim() → "hi"

split(regex) Split string "a,b,c".split(",") → ["a","b","c"]

replace(old, new) Replace characters "hello".replace('l','x') → "hexxo"

equals(str) Compare content "hi".equals("hi") → true

contains(str) Check if contains "hello".contains("ll") → true

Collection Comparison

Feature ArrayList HashMap HashSet

Type List Map Set

Duplicates Allowed Keys: No, Values: Yes Not allowed

Order Insertion order No order No order

Access By index By key No direct access

Null Multiple nulls One null key One null value

I/O Stream Types

Purpose Byte Stream Character Stream

Read from file FileInputStream FileReader

Write to file FileOutputStream FileWriter


Purpose Byte Stream Character Stream

Buffered reading BufferedInputStream BufferedReader

Buffered writing BufferedOutputStream BufferedWriter

Formatted output PrintStream PrintWriter

✓ This guide covers all essential Java packages with easy-to-understand examples.
✓ Each example is complete, runnable, and shows expected output.
✓ Perfect for quick learning and exam preparation.

Common questions

Powered by AI

A HashMap offers constant-time complexity for get and put operations, making it highly efficient for frequent accesses and updates. However, it doesn't guarantee any order of the keys. In contrast, a TreeMap maintains keys in a sorted order, usually implemented as a Red-Black tree, guaranteeing ordered traversal, which is helpful for range queries. The trade-off is that operations like get and put in a TreeMap require O(log n) time due to re-balancing operations. Thus, choosing between a HashMap and a TreeMap depends on the need for ordering operations versus performance in insertions and lookups .

String immutability in Java is fundamental for memory management and performance optimizations. It allows for safe sharing of string instances across different threads, reducing the need for synchronization. Moreover, the internal use of the String Pool conserves memory by reusing existing string objects, which minimizes heap space usage and garbage collection overhead. As strings are immutable, they can serve as reliable keys for Hashed data structures, guaranteeing consistent hash codes. These properties collectively promote optimization by ensuring efficiency and safety in concurrent applications .

Java's MessageFormat class facilitates locale-sensitive formatting by enabling developers to construct parameterized messages that automatically adapt to the locale's customs. This class supports the incorporation of text, numbers, dates, and choices into messages. For example, consider a billing system that outputs a localized message indicating the user's remaining balance on a given date. A pattern like 'Hello {0}, your balance is {1, number, currency} as of {2, date}' could dynamically insert a user's name, balance amount formatted as currency, and current date formatted as per the user's locale. MessageFormat seamlessly adjusts formats based on the specified Locale, promoting internationalization without the need for explicit formatting logic tailored to each region .

The SecureRandom class is specifically designed for cryptographic purposes and outperforms the Random class due to its enhanced entropy quality and unpredictability. SecureRandom uses a cryptographically strong pseudo-random number generator (CSPRNG), ensuring that generated numbers are unpredictable and suitable for security-sensitive applications such as key generation, random tokens, and secure UUIDs. Conversely, the Random class produces predictable sequences if its seed is known, posing a significant risk for security applications where unpredictability is crucial .

Enum types in Java enhance code safety by providing a type-safe approach to define a fixed set of constants. These constants come with inherent safety against erroneous assignments that often plague integer-based constant representations. Enums improve readability by clearly indicating the domain-specific values expected in a variable, making the code self-documenting. Finally, they allow the inclusion of fields and methods, facilitating behavior encapsulation related to each constant, which further enhances maintainability and clarity in software design .

Using Java's JDBC API, secure handling of database transactions and concurrency can be achieved by employing transactions with appropriate isolation levels. Begin by setting up a connection with auto-commit disabled using `conn.setAutoCommit(false)`. Employ `conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE)` for the highest isolation, if data anomalies cannot be tolerated, though it might lead to reduced concurrency. Use PreparedStatements to mitigate SQL injection risks. Wrap transaction logic in try-catch blocks, committing upon success with `conn.commit()` and rolling back with `conn.rollback()` on failure. Additionally, to handle potential deadlocks, implement a retry mechanism to re-attempt transactions .

Using BufferedReader with FileReader improves performance significantly when reading large files due to its buffering capability. BufferedReader reads large chunks of data at once into an internal buffer, reducing the number of I/O operations compared to FileReader, which reads data one character at a time. This reduction in read operations minimizes the interaction with the disk and can lead to better performance, especially on systems with slower I/O performance. Additionally, buffering reduces CPU overhead and can also economize on system resources, making BufferedReader preferable for applications processing large text files .

Immutability in Java's wrapper classes like Integer, Double ensures that once an instance is created, its value cannot be modified, which is essential for reliable behavior when used as keys in data structures such as HashMap or elements in a HashSet. This is crucial in scenarios where collections might undergo modifications, as it prevents accidental side-effects like unintentional alteration of values impacting consistent hashing behavior. However, immutability can also lead to increased object creation overhead in scenarios requiring frequent value changes, affecting memory allocation and garbage collection negatively due to numerous object instantiations .

The java.nio package, known for its non-blocking and buffer-oriented I/O operations, improves performance through features such as Channels and Buffers, which enable direct reading and writing of byte buffers to and from I/O devices without intermediate data copying. FileChannel, for instance, allows for more efficient file transfers using memory-mapped I/O, which can be significantly faster than traditional streams for large files. Furthermore, the selectable channel feature allows handling multiple I/O operations asynchronously, which is advantageous for scalable network servers handling numerous connections simultaneously .

Java's autoboxing automates the conversion between primitive types and their corresponding wrapper classes, simplifying code when using collections like HashMap and HashSet which require objects. While autoboxing enhances readability, it can introduce performance overhead due to frequent boxing and unboxing operations, particularly when these collections are frequently modified. Additionally, it poses a risk for bugs due to unintended null handling and equality comparisons. For example, using '== instead of '.equals() for boxed types might lead to unexpected results, as the former compares object references .

You might also like