📗 Module III: Packages and Access Modifiers, Handling String, Input
Output Classes
( By Santosh )
● Packages and Access Modifiers
○ Recommended Package Naming Convention
○ The Package Declaration
○ The CLASSPATH Variable
○ The Import Statement
○ Java Language Packages
○ Importance of Package Design
● Access Protection
● Handling Strings
○ Create Strings
○ Operations on Strings
○ Character Extraction Method
○ String Comparison Method
○ Searching and Modifying Strings
○ Data Conversions and valueOf()
○ Methods of StringBuffer and StringBuilder
○ Changing Case of Characters
○ Wrapper Classes
● Input and Output Classes
○ Hierarchy of Classes in java.io
○ File Classes
○ InputStream and OutputStream Classes
■ FilterInputStream
■ FilterOutputStream
○ Reader and Writer Classes
● Basics of Networking
○ Java's Networking Protocol
○ Hierarchy of Classes in java.net
○ Connection-oriented Protocol Classes
1. Packages and Access Modifiers
What is a Package?
In Java, a package is like a folder or directory that groups related classes and interfaces
together.
● Packages help avoid name conflicts. For example, you can have
com.companyA.project.Employee and com.companyB.project.Employee
without collision.
● They provide access protection (access modifiers interact with package boundaries).
● They make maintenance and organization easier.
Recommended Package Naming Convention
Why reverse domain name?
● Domains are unique worldwide, so reversing them makes the package names globally
unique.
● It also reflects ownership and avoids conflicts.
Example:
If your organization’s domain is example.com, the package name starts as:
package com.example.myproject;
Inside myproject, you might have sub-packages:
package com.example.myproject.utils;
package com.example.myproject.models;
package com.example.myproject.services;
The Package Declaration
● Must be the first statement in a Java source file.
● Defines the package that the class belongs to.
Example:
package com.example.shapes;
public class Circle {
// class code
}
If omitted, the class goes into the default package, which is discouraged for larger projects.
The CLASSPATH Variable
● When compiling or running Java programs, the JVM and compiler need to know where
to look for classes.
● CLASSPATH is an environment variable or command-line option that tells JVM where to
look for classes and packages.
Example:
Suppose your class files are in /home/user/classes.
Set CLASSPATH on Linux:
export CLASSPATH=/home/user/classes:.
The . ensures the current directory is included.
The Import Statement
Used to access classes from other packages without typing their full package names every time.
Syntax:
import package_name.class_name;
Example:
import java.util.ArrayList;
import java.util.HashMap;
You can also import all classes in a package:
import java.util.*;
Java Language Packages
Java provides a set of core packages:
● java.lang: Fundamental classes, e.g., String, System, Math. Imported automatically.
● java.util: Utility classes like collections (ArrayList, HashMap), dates, random number
generation.
● java.io: Input/output classes for file handling, streams, readers/writers.
● java.net: Networking classes (sockets, URLs).
● java.nio: New I/O classes with buffer-oriented I/O and non-blocking I/O.
Importance of Package Design
● Modularization: Splits large projects into logical modules/packages.
● Reusability: Well-designed packages can be reused in multiple projects.
● Maintainability: Easier to update and debug code organized by function.
● Access Control: Packages define access boundaries via access modifiers.
Access Protection (Access Modifiers)
Java access modifiers control visibility:
Modifier Within Package Subclass (same Subclass (different Everywher
Class (same) package) package) e
public Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes No
default Yes Yes Yes No No
private Yes No No No No
Examples:
package com.example;
public class MyClass {
public int pubVar;
protected int protVar;
int defVar; // default
private int privVar;
public void demo() {
System.out.println(pubVar); // Accessible
System.out.println(protVar); // Accessible
System.out.println(defVar); // Accessible
System.out.println(privVar); // Accessible
}
}
If another class in the same package accesses MyClass, it can see pubVar, protVar, and
defVar, but not privVar.
If another class is in a different package and is not a subclass, it can only access pubVar.
2. Handling Strings
Creating Strings
● Strings in Java are immutable objects.
● Created either by string literals or with the new keyword.
String s1 = "Hello"; // Literal, stored in String Pool
String s2 = new String("Hello"); // New object on the heap
Operations on Strings
● Concatenation:
String s = "Hello" + " World"; // "Hello World"
● Length:
int len = s.length(); // returns 11
● Check if empty:
boolean empty = s.isEmpty(); // false
● Trim whitespace:
String trimmed = s.trim();
Character Extraction Methods
● charAt(int index)
char c = s.charAt(0); // 'H'
● getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from the string into an array.
String Comparison Methods
● equals(String another)
Checks if two strings have the same content.
if(s1.equals(s2)) {
System.out.println("Equal");
}
● equalsIgnoreCase(String another)
Ignores case differences.
● compareTo(String another)
Lexicographically compares strings (returns negative if less, 0 if equal, positive if greater).
Searching and Modifying Strings
● indexOf(String substr)
Returns index of the first occurrence, or -1 if not found.
● lastIndexOf(String substr)
Returns index of last occurrence.
● substring(int beginIndex, int endIndex)
Extracts a substring.
● replace(char oldChar, char newChar)
Replaces all occurrences of a character.
Data Conversions and valueOf()
● Converts primitive types to strings:
String intStr = String.valueOf(123); // "123"
String boolStr = String.valueOf(true); // "true"
● Can convert objects too.
Methods of StringBuffer and StringBuilder
● StringBuffer is thread-safe (synchronized).
● StringBuilder is faster but not thread-safe.
● Both allow mutable strings (unlike String).
Common methods:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.replace(6, 11, "Java");
sb.delete(5, 6);
sb.reverse();
Changing Case of Characters
● toUpperCase() converts all characters to uppercase.
● toLowerCase() converts all characters to lowercase.
Wrapper Classes
Primitive types and their wrapper classes:
Primitive Wrapper Class
int Integer
char Character
boolean Boolean
double Double
Supports autoboxing/unboxing.
Example:
Integer num = 10; // autoboxing
int n = num; // unboxing
3. Input and Output Classes
Hierarchy of Classes in java.io
Abstract Purpose Common subclasses
class
InputStream Reads bytes FileInputStream,
BufferedInputStream
OutputStrea Writes bytes FileOutputStream,
m BufferedOutputStream
Reader Reads FileReader, BufferedReader
characters
Writer Writes characters FileWriter, BufferedWriter
File Class
● Represents file or directory path.
● Can create, delete, check file info.
File file = new File("example.txt");
if(file.exists()) {
System.out.println("File size: " + file.length());
}
InputStream and OutputStream Classes
● Work with raw bytes.
● Example reading a file byte-by-byte:
try(FileInputStream fis = new FileInputStream("input.txt")) {
int data;
while((data = fis.read()) != -1) {
System.out.print((char)data);
}
} catch(IOException e) {
e.printStackTrace();
}
FilterInputStream and FilterOutputStream
● Wrap existing streams to add functionality.
Example: BufferedInputStream buffers input for efficiency.
FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int data;
while((data = bis.read()) != -1) {
System.out.print((char)data);
}
bis.close();
fis.close();
Reader and Writer Classes
● For reading and writing characters (Unicode).
● Usually preferred for text data.
Example reading with BufferedReader:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
4. Basics of Networking
Java's Networking Protocol
● Supports TCP (reliable, connection-oriented)
● Supports UDP (unreliable, connectionless)
Hierarchy of Classes in java.net
Class Purpose
Socket Client TCP socket
ServerSocke Server socket for listening
t
URL Uniform Resource Locator
InetAddress IP Address resolution
DatagramSoc UDP socket
ket
DatagramPac UDP packet
ket
Connection-oriented Protocol Classes
TCP sockets:
● Server creates a ServerSocket to listen on a port.
● Client creates a Socket to connect to server.
● Both can send/receive data via streams.
Example server:
ServerSocket server = new ServerSocket(1234);
Socket client = server.accept(); // waits for client
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
String message = in.readLine();
System.out.println("Received: " + message);
out.println("Hello Client!");
Example client:
Socket socket = new Socket("localhost", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out.println("Hello Server");
String response = in.readLine();
System.out.println("Server says: " + response);