0% found this document useful (0 votes)
34 views13 pages

Module 3 Java

Module III covers Java packages and access modifiers, string handling, input/output classes, and basic networking. It explains package organization, naming conventions, access protection, string operations, and the hierarchy of input/output classes. Additionally, it introduces Java's networking protocols and classes for TCP and UDP communication.
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)
34 views13 pages

Module 3 Java

Module III covers Java packages and access modifiers, string handling, input/output classes, and basic networking. It explains package organization, naming conventions, access protection, string operations, and the hierarchy of input/output classes. Additionally, it introduces Java's networking protocols and classes for TCP and UDP communication.
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

📗 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 [Link]​

○​ File Classes​

○​ InputStream and OutputStream Classes​

■​ FilterInputStream​

■​ FilterOutputStream​

○​ Reader and Writer Classes​

●​ Basics of Networking​

○​ Java's Networking Protocol​

○​ Hierarchy of Classes in [Link]​

○​ 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
[Link] and [Link]
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 [Link], the package name starts as:

package [Link];

Inside myproject, you might have sub-packages:

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

The Package Declaration

●​ Must be the first statement in a Java source file.​

●​ Defines the package that the class belongs to.​

Example:

package [Link];

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 [Link];
import [Link];

You can also import all classes in a package:

import [Link].*;

Java Language Packages

Java provides a set of core packages:


●​ [Link]: Fundamental classes, e.g., String, System, Math. Imported automatically.​

●​ [Link]: Utility classes like collections (ArrayList, HashMap), dates, random number
generation.​

●​ [Link]: Input/output classes for file handling, streams, readers/writers.​

●​ [Link]: Networking classes (sockets, URLs).​

●​ [Link]: 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 [Link];

public class MyClass {


public int pubVar;
protected int protVar;
int defVar; // default
private int privVar;

public void demo() {


[Link](pubVar); // Accessible
[Link](protVar); // Accessible
[Link](defVar); // Accessible
[Link](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 = [Link](); // returns 11

●​ Check if empty:

boolean empty = [Link](); // false

●​ Trim whitespace:

String trimmed = [Link]();

Character Extraction Methods

●​ charAt(int index)

char c = [Link](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([Link](s2)) {
[Link]("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 = [Link](123); // "123"


String boolStr = [Link](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");


[Link](" World");
[Link](5, ",");
[Link](6, 11, "Java");
[Link](5, 6);
[Link]();

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 [Link]


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("[Link]");


if([Link]()) {
[Link]("File size: " + [Link]());
}

InputStream and OutputStream Classes

●​ Work with raw bytes.​

●​ Example reading a file byte-by-byte:

try(FileInputStream fis = new FileInputStream("[Link]")) {


int data;
while((data = [Link]()) != -1) {
[Link]((char)data);
}
} catch(IOException e) {
[Link]();
}

FilterInputStream and FilterOutputStream

●​ Wrap existing streams to add functionality.

Example: BufferedInputStream buffers input for efficiency.

FileInputStream fis = new FileInputStream("[Link]");


BufferedInputStream bis = new BufferedInputStream(fis);

int data;
while((data = [Link]()) != -1) {
[Link]((char)data);
}
[Link]();
[Link]();

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("[Link]"));


String line;
while((line = [Link]()) != null) {
[Link](line);
}
[Link]();

4. Basics of Networking

Java's Networking Protocol

●​ Supports TCP (reliable, connection-oriented)​

●​ Supports UDP (unreliable, connectionless)​

Hierarchy of Classes in [Link]


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 = [Link](); // waits for client

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);

String message = [Link]();


[Link]("Received: " + message);
[Link]("Hello Client!");

Example client:

Socket socket = new Socket("localhost", 1234);

PrintWriter out = new PrintWriter([Link](), true);


BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));

[Link]("Hello Server");
String response = [Link]();
[Link]("Server says: " + response);

You might also like