0% found this document useful (0 votes)
9 views55 pages

JavaPaper

Chapter 2 provides an overview of Java, focusing on Object-Oriented Programming (OOP) principles such as encapsulation, inheritance, and polymorphism. It explains how to write, compile, and run simple Java programs, including basic syntax and the use of built-in libraries. Additionally, it introduces the concept of packages for organizing code and controlling access within Java projects.

Uploaded by

rabbiakhanzadii
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)
9 views55 pages

JavaPaper

Chapter 2 provides an overview of Java, focusing on Object-Oriented Programming (OOP) principles such as encapsulation, inheritance, and polymorphism. It explains how to write, compile, and run simple Java programs, including basic syntax and the use of built-in libraries. Additionally, it introduces the concept of packages for organizing code and controlling access within Java projects.

Uploaded by

rabbiakhanzadii
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
You are on page 1/ 55

Chapter 2: An Overview of Java (Basically, a Quick Tour)

This chapter is like a quick peek at what Java is all about. Java's parts all work together,
so sometimes explaining one thing means you need to know a bit about another. This
chapter gives you the basics so you can start understanding and writing simple Java
programs.

1. Object-Oriented Programming (OOP) - The Heart of Java

• What it is: Java is built around an idea called "Object-Oriented Programming"


(OOP). You have to use OOP in Java; it's not optional like in some other
languages.
• Think of it like this:
o Old Way (Process-Oriented): Imagine a recipe. You have a list of steps
(code) that you do to ingredients (data). The focus is on the steps.
o New Way (Object-Oriented): Imagine building with LEGOs. You have
different types of blocks (objects), and each block knows what it is (its
data) and what it can do (its code/actions). The focus is on the blocks
(objects).
o OOP helps organize programs around "objects" (data) and how they
interact.
• Abstraction - Hiding the Complex Stuff:
o When you drive a car, you don't think about all the thousands of tiny parts
working together. You just think of it as a "car" that you can steer,
accelerate, and brake. This is abstraction – focusing on what
something does rather than how it does it.
o OOP lets us create "objects" in our programs that hide their complicated
inner workings. We just use them.

2. The Three Main Ideas of OOP (The Superpowers)

OOP has three main principles or tools:

• a) Encapsulation - Keeping Things Bundled and Safe:


o This means bundling data (like an object's information) and the code that
works on that data together into a single unit, like a capsule.
o It also protects this data from being messed with from the outside. You
can only interact with it through specific, well-defined ways (like buttons on
a TV remote).
o In Java: This "capsule" is usually a class.
▪ Member Variables (or Instance Variables): The data inside the
class.
▪ Methods (or Member Methods): The code (actions) that can work
on that data.
▪ Public vs. Private:
▪ public: Anyone can access/use it.
▪ private: Only code inside the same class can access/use it.
This protects data.
• b) Inheritance - Reusing and Building Upon Ideas:
o This is like family traits. A "Golden Retriever" is a type of "Dog." A "Dog" is
a type of "Mammal."
o A new object (or class) can "inherit" (get) all the features of an existing
one and then add its own unique features.
o So, a "SportsCar" class could inherit all the basic features of a "Car" class
(wheels, engine) and then add its own special features (spoiler, turbo).
This saves you from re-writing common stuff.
• c) Polymorphism - One Name, Many Actions:
o "Poly" means many, "morph" means form. So, "many forms."
o This means you can use one name or one interface to do different things
depending on the situation or the object involved.
o Example: Think of a "draw" command. If you tell a "Circle" object to draw,
it draws a circle. If you tell a "Square" object to draw, it draws a square.
Same "draw" command, different results based on the object.
o Another Example: Your dog's nose. It smells food, it salivates. It smells a
cat, it barks. Same nose, different reactions to different "data" (smells).

How Encapsulation, Inheritance, and Polymorphism Work Together:


These three ideas make programs more robust (strong), easier to change, and easier to
understand and build upon. The car example is good:

• Encapsulation: The gas pedal is simple to use (interface), but hides complex
engine mechanics.
• Inheritance: You know how to drive a sedan, so you can probably figure out a
minivan because they inherit from a general "vehicle" concept.
• Polymorphism: You press the brake pedal. Whether you have standard brakes
or anti-lock brakes (different implementations), the pedal (interface) works the
same way to stop the car.
3. A First Simple Java Program - "Hello World!"

Let's look at a very basic Java program:

/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example { // 1. Defines a 'class' named Example
// Your program begins with a call to main().
public static void main(String args[]) { // 2. The starting
point of the program
System.out.println("This is a simple Java program."); //
3. Prints text to the screen
}
}
• File Name: The file must be named Example.java (same as the class name, and
Java cares about uppercase/lowercase).
• Compiling (Building):
1. You type your program into a .java file.
2. You use a command like javac Example.java. This turns your human-
readable code into "bytecode" (a .class file, e.g., Example.class). Computers
don't run .java files directly.
• Running (Executing):
1. You use a command like java Example. This tells the Java system to run
the bytecode in Example.class.

Closer Look at the Code:

• /* ... */ or // ...: These are comments. They are notes for humans; the computer
ignores them.
• class Example { ... }: This declares a class named Example. All Java code lives
inside classes.
• public static void main(String args[]) { ... }: This is the main method. It's the special
starting point for any Java application.
o public: Means it can be accessed from anywhere.
o static: Means you can run this method without creating an "object" of
the Example class first.
o void: Means this method doesn't return any value when it's done.
o main: This specific name tells Java where to start.
o String args[]: This is a place to receive any arguments you might type on
the command line when you run the program (we're not using it here).
• System.out.println("This is a simple Java program.");:
o System.out: A standard way to access system output (like the screen).
o println(): A method that prints whatever is in the parentheses to the
screen, and then moves to a new line.
• ; (Semicolon): Marks the end of a statement (like a period at the end of a
sentence).
• { } (Curly Braces): Define blocks of code, like the body of the class or the body of
the method.

4. A Second Short Program - Using Variables

Variables are like named boxes where you can store information.

class Example2 {
public static void main(String args[]) {
int num; // 1. Declares an integer variable named 'num'
num = 100; // 2. Assigns the value 100 to 'num'

System.out.println("This is num: " + num); // 3. Prints


the text and the value of num

num = num * 2; // 4. 'num' now becomes 200


System.out.print("The value of num * 2 is "); // 5.
'print' doesn't add a new line
System.out.println(num); // 6. Prints 200 on the same
line
}
}

Output:
This is num: 100
The value of num * 2 is 200

• int num;: Declares a variable named num that will hold whole numbers (integers).
• num = 100;: Assigns the value 100 to num. The = is the assignment operator.
• "This is num: " + num: The + sign here joins the text string with the value
of num (which is converted to text) before printing.
• System.out.print(): Similar to println(), but it doesn't move to a new line after
printing.

5. Two Control Statements - Making Decisions and Repeating Things

• The if Statement - Making Choices:


o if (condition) statement;
o If the condition is true, the statement is done. Otherwise, it's skipped.
o Example: if (x < 100) System.out.println("x is small");
o Relational operators: < (less than), > (greater than), == (equal to - note
the double equals!).
• The for Loop - Repeating Actions:
o for (initialization; condition; iteration) statement;
o Initialization: Done once at the start (e.g., int x = 0;).
o Condition: Checked before each repetition. If true, loop continues. If
false, loop stops (e.g., x < 10;).
o Iteration: Done after each repetition (e.g., x = x + 1; or the shorter x++;).
o Example:
o for (int x = 0; x < 5; x++) {
o System.out.println("This is x: " + x);
}

This will print:


This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
o x++ is a shortcut for x = x + 1 (increment).
o x-- is a shortcut for x = x - 1 (decrement).

6. Using Blocks of Code - Grouping Statements

You can group multiple statements together using curly braces { }. This "block" is then
treated as a single unit.
This is useful for if statements or for loops that need to do more than one thing.
if (x < y) { // If x is less than y...
System.out.println("x is smaller"); // ...do this
x = y; // ...and then do this
} // End of block

7. Lexical Issues - The Basic Building Blocks of Java Code

These are the fundamental pieces that make up your Java program:

• Whitespace: Spaces, tabs, newlines. Java mostly uses them to separate things
and make code readable. Extra whitespace is usually ignored.
• Identifiers: Names you give to things like classes, methods, and variables
(e.g., Example, main, num).
o Rules: Can use letters, numbers, _, $.
o Cannot start with a number.
o Java is case-sensitive (myVariable is different from MyVariable).
• Literals: The actual values you write in your code.
o 100 (integer literal)
o 98.6 (floating-point literal)
o 'X' (character literal - single quotes)
o "This is a string" (string literal - double quotes)
• Comments:
o // Single-line comment
o /* Multi-line comment */
o /** Documentation comment (special type for generating help files) */
• Separators: Characters that help structure the code.
o (): For method parameters, expressions.
o {}: For code blocks.
o []: For arrays.
o ;: Terminates statements.
o ,: Separates items in a list (like variable declarations).
o .: Used to access members of a class or package.
• Keywords: Special reserved words that have specific meanings in Java
(e.g., class, public, static, void, int, if, for). You cannot use these as names for
your variables or methods. (The text shows a table of these).
o true, false, null are also reserved.
8. The Java Class Libraries - Java's Built-in Toolkit

Java comes with a huge collection of pre-written code called class libraries (or APIs).
These libraries provide tons of useful tools and functions for things like:

• Input/Output (like System.out.println())


• Working with text (Strings)
• Networking
• Graphics and User Interfaces
• And much more!

A big part of learning Java is learning how to use these built-in libraries. You don't have
to reinvent the wheel for common tasks.

In a Nutshell:
Chapter 2 gives you a bird's-eye view of Java. It emphasizes that Java is all about
"objects" (OOP), introduces the core OOP ideas (Encapsulation, Inheritance,
Polymorphism), shows you how to write, compile, and run simple programs, and
touches on the basic syntax elements and the existence of powerful built-in libraries.

Chapter 9
Packages and Interfaces

What's in a Java Source File?

A single .java file can have:

1. package statement (Optional): Like a folder name for your classes.


2. import statements (Optional): Tells Java where to find classes you want to use
from other packages.
3. One public class declaration (Required, usually): The main class, its name
must match the file name.
4. Other classes (Optional, not public): Helper classes for the public class in the
same file, only usable within the same package.

1. Packages: Organizing Your Code

• Think of it like: Folders on your computer. You put related files (classes) into a
folder (package) to keep things organized and avoid having two files with the
same name in the same place.
• Why use them?
o Organization: Keeps your project tidy, especially large ones.
o Avoid Name Clashes: You can have a class named List in your package,
and Java can have its own List class in its java.util package, and they
won't get confused.
o Control Access: You can decide which classes or methods are visible
only within the package, and which can be used by code outside the
package.
• How to Define a Package:
o Put package packageName; as the very first line in your Java file.
o Example: package com.mycompany.projectname;
o The .class files must be stored in a directory structure that matches the
package name. So, for com.mycompany.projectname.MyClass,
the MyClass.class file would be in a folder path
like com/mycompany/projectname/.
• The "Default Package": If you don't write a package statement, your class goes
into an unnamed "default" package. This is okay for small examples, but not for
real projects.
• How Java Finds Packages:
1. Current Directory: It looks in the current folder and its subfolders.
2. CLASSPATH: An environment variable that tells Java other places to look
for packages. (Don't worry too much about this for simple examples).
• Access Control with Packages:
o public: Anyone, anywhere can access it.
o private: Only accessible within the same class.
o protected: Accessible within the same package, AND by subclasses (even
if those subclasses are in different packages).
o No keyword (default/package-private): Accessible only by other classes
in the same package.

Simple Package Example:

Let's create two files.

File 1: MyHelper.java (put this inside a folder named mytools)

// File: mytools/MyHelper.java
package mytools; // This class is in the 'mytools' package

public class MyHelper {


public void sayHello(String name) {
System.out.println("Hello, " + name + " from
MyHelper!");
}

// This method is package-private (no public, private, or


protected)
void internalStuff() {
System.out.println("This is internal to mytools
package.");
}
}

File 2: App.java (put this in the folder above mytools)

// File: App.java (in the directory *above* the 'mytools'


folder)
import mytools.MyHelper; // We want to use MyHelper from the
mytools package

// App is in the default package because no 'package' statement


public class App {
public static void main(String[] args) {
MyHelper helper = new MyHelper();
helper.sayHello("World");

// The following line would cause an error because


internalStuff()
// is not public and App is not in the 'mytools'
package.
// helper.internalStuff();
}
}

To Compile and Run (from the folder containing App.java and the mytools folder):

1. javac mytools/MyHelper.java
2. javac App.java
3. java App

Output:
Hello, World from MyHelper!

2. Interfaces: Defining a Contract

• Think of it like: A contract or a job description. It specifies what a class must be


able to do, but not how it does it. It's a list of methods that a class promises to
provide.
• Why use them?
o Abstraction: Focus on what methods are available, not the nitty-gritty
details of how they work.
o Multiple "Personalities": A class can implement multiple interfaces,
meaning it can fulfill multiple "contracts" or roles. (A class can only inherit
from one parent class, but it can implement many interfaces).
o Polymorphism: Allows you to treat different objects in a uniform way if
they implement the same interface. For example, anything that is
"Drawable" can be told to draw(), regardless of whether it's a Circle,
Square, or Triangle.
• How to Define an Interface:
o Use the interface keyword.
o Methods in an interface have no body (just the signature, ending with a
semicolon). They are automatically public and abstract (you don't need to
write these keywords).
o Variables in an interface are automatically public, static,
and final (constants).
• How a Class Uses an Interface ("Implements"):
o A class uses the implements keyword to say it will follow an interface's
contract.
o The class must provide an implementation (a body) for all methods
defined in the interface. These implementing methods must be
declared public.

Simple Interface Example:

File 1: Playable.java

// File: Playable.java
interface Playable {
void playSound(); // This is the "contract" - any Playable
must have this
// String getInstrumentType(); // You could add more methods
to the contract
}

File 2: Guitar.java

// File: Guitar.java
class Guitar implements Playable {
// This class "implements" the Playable interface,
// so it MUST provide the playSound() method.
@Override // Good practice to use @Override
public void playSound() { // Must be public
System.out.println("Strumming guitar chords!");
}
}

File 3: Piano.java

// File: Piano.java
class Piano implements Playable {
@Override
public void playSound() { // Must be public
System.out.println("Playing a beautiful piano melody.");
}
}
File 4: MusicPlayer.java (The main application)

// File: MusicPlayer.java
public class MusicPlayer {
public static void main(String[] args) {
Playable myGuitar = new Guitar(); // A Guitar IS-A
Playable
Playable myPiano = new Piano(); // A Piano IS-A
Playable

myGuitar.playSound(); // Calls Guitar's playSound


myPiano.playSound(); // Calls Piano's playSound

System.out.println("\nLet's play them using a generic


function:");
playAnInstrument(myGuitar);
playAnInstrument(myPiano);

// We can even make an array of Playable things


Playable[] band = {new Guitar(), new Piano(), new
Guitar()};
System.out.println("\nBand practice:");
for (Playable instrument : band) {
instrument.playSound();
}
}

// This method can work with ANY object that implements


Playable
public static void playAnInstrument(Playable instrument) {
instrument.playSound();
}
}

To Compile and Run (if all files are in the same directory):

1. javac Playable.java Guitar.java Piano.java MusicPlayer.java


2. java MusicPlayer

Output:
Strumming guitar chords!
Playing a beautiful piano melody.

Let's play them using a generic function:


Strumming guitar chords!
Playing a beautiful piano melody.

Band practice:
Strumming guitar chords!
Playing a beautiful piano melody.
Strumming guitar chords!

Key Takeaways for Interfaces:

• "Can Do" Relationship: An interface defines capabilities (what an object can


do).
• Flexibility: You can write code that works with any object implementing a certain
interface, without needing to know the object's specific class. This is super
powerful for making flexible and extendable programs.
• Constants: Interfaces can also be used to define a set of shared constants. Any
class implementing that interface gets access to those constants.

Summary in Super Simple Terms:

• Packages: Like folders to keep your Java classes organized and avoid name
fights.
• Interfaces: Like a checklist of tasks (methods) a class promises to do. If a class
says "I implement this interface," it must do all those tasks. This lets different
types of classes be treated in a similar way if they promise to do the same tasks.

Chapter 10

Exception Handling
What is an Exception?
An "exception" is like an unexpected problem that happens while you're baking. For
example:

• You run out of eggs (a resource is missing).


• The oven breaks down (a system error).
• You try to cut the cake into zero slices (an impossible operation).

These are "run-time errors" – problems that occur when the program is actually running.

Why do we need Exception Handling?


Without a plan for these problems:

• Your cake-baking (program) might just stop abruptly, leaving a mess.


• You'd have to manually check for every possible problem at every step (e.g., "Do
I have eggs? Yes. Do I have flour? Yes..."). This is messy and hard to manage.

Java's exception handling is a clean way to manage these unexpected problems.

The 5 Magic Keywords

1. try: "I'm going to try doing something that might go wrong."


o You put the risky code (like dividing numbers, or working with files) inside
a try block.
2. catch: "If something does go wrong (an exception is 'thrown') in the try block,
I'll catch it here and deal with it."
o You can have specific catch blocks for different types of problems (like
one for "ran out of eggs" and another for "oven broke").
3. finally: "No matter what happens (whether the try was successful or
a catch block ran), I finally want to do this."
o This block always runs. It's good for cleanup, like washing the dishes even
if the cake burned.
4. throw: "I've detected a problem myself, and I'm going to throw an 'exception
ball' to signal it."
o You can manually create and throw an exception if your code finds a
situation it can't handle.
5. throws: (Used in method signatures) "Hey, whoever calls this method, be aware
that this method throws (might cause) these specific types of exceptions, and I'm
not handling them myself."
o It's a warning to other parts of the code.

How it Works: The Basic try-catch

Think of it like a safety net.

// Basic Try-Catch Example


public class SimpleCatch {
public static void main(String[] args) {
try {
// Risky code: Trying to divide by zero
System.out.println("Trying to divide...");
int result = 10 / 0; // This will cause an
ArithmeticException
System.out.println("This line will NOT be
printed."); // Program flow jumps to catch

} catch (ArithmeticException e) {
// What to do if the specific "ArithmeticException"
happens
System.out.println("Oops! You can't divide by
zero.");
System.out.println("Error was: " + e.getMessage());
// Get a short description
}

System.out.println("Program continues after the try-


catch block.");
}
}

Output:

Trying to divide...
Oops! You can't divide by zero.
Error was: / by zero
Program continues after the try-catch block.

Without try-catch, the program would crash. With try-catch, we handled the error
gracefully.

What if you DON'T catch an exception? (Uncaught Exceptions)


If an exception happens and there's no catch block for it (or no try block at all),
Java's "default handler" takes over.
It will:

1. Print a message about the exception.


2. Print a "stack trace" (a list of method calls that led to the error – useful for
debugging).
3. Stop your program.
// Uncaught Exception Example
public class Uncaught {
public static void main(String[] args) {
System.out.println("Before division.");
int result = 10 / 0; // This will cause an
ArithmeticException
System.out.println("This will not be printed."); //
Program crashes before this
}
}

Output (will look something like this):

Before division.
Exception in thread "main" java.lang.ArithmeticException: / by
zero
at Uncaught.main(Uncaught.java:4)

The program stops.

The finally Block: Always Runs

// Finally Example
public class FinallyDemoSimple {
public static void main(String[] args) {
try {
System.out.println("Inside try block.");
int riskyValue = 10 / 2; // Change to 10 / 0 to see
it with an exception
System.out.println("Result: " + riskyValue);
} catch (ArithmeticException e) {
System.out.println("Caught an arithmetic error!");
} finally {
System.out.println("This finally block always runs,
error or not!");
}
System.out.println("After try-catch-finally.");
}
}

If 10 / 2:

Inside try block.


Result: 5
This finally block always runs, error or not!
After try-catch-finally.

If 10 / 0:

Inside try block.


Caught an arithmetic error!
This finally block always runs, error or not!
After try-catch-finally.

throw: Manually Signaling a Problem

Sometimes, your logic dictates that something is an error.

// Throw Example
public class ThrowDemoSimple {
static void checkAge(int age) {
if (age < 18) {
// We decide this is an error condition
throw new ArithmeticException("Access denied - You
must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old
enough.");
}
}

public static void main(String[] args) {


try {
checkAge(15); // This will throw the exception
// checkAge(20); // This would be fine
} catch (ArithmeticException e) {
System.out.println("Caught exception: " +
e.getMessage());
}
}
}

Output:

Caught exception: Access denied - You must be at least 18 years


old.

throws: Warning Others About Potential Exceptions

If a method might cause an exception that it doesn't handle itself, it must declare it
using throws. This mainly applies to "checked exceptions" (more serious ones like file
errors, network errors). ArithmeticException is "unchecked," so you don't have to
declare it, but it's good practice if a method is designed to throw it.

Let's use a common checked exception, IOException (for Input/Output problems),


even if we just pretend.

// Throws Example (using a dummy checked exception concept)


import java.io.IOException; // Need to import for IOException

public class ThrowsDemoSimple {

// This method MIGHT throw an IOException, and it's NOT


handling it.
// So, it must declare it with "throws IOException".
static void readFile(String fileName) throws IOException {
if (fileName.equals("badfile.txt")) {
throw new IOException("Could not read the bad
file!");
}
System.out.println("Successfully 'read' file: " +
fileName);
}

public static void main(String[] args) {


try {
readFile("goodfile.txt");
readFile("badfile.txt"); // This call will trigger
the exception
System.out.println("This won't be printed if
badfile.txt is called before.");
} catch (IOException e) {
System.out.println("Main caught an IO Exception: " +
e.getMessage());
}
}
}

Output:

Successfully 'read' file: goodfile.txt


Main caught an IO Exception: Could not read the bad file!

If main didn't try-catch the readFile call that throws IOException, the
compiler would give an error.

Types of Exceptions
All exceptions are objects. They come from a main class Throwable.

• Error: Very serious problems, usually outside your program's control (like
running out of memory). You typically don't try to catch these.
• Exception: Problems that your program can often recover from (bad user input,
file not found, etc.). These are the ones you usually catch.
o RuntimeException: A special kind
of Exception (like ArithmeticException, NullPointerExceptio
n, ArrayIndexOutOfBoundsException). These are "unchecked" –
the compiler doesn't force you to use try-catch or throws for them,
though you often should handle them.
o Other Exceptions (like IOException): These are "checked" – the
compiler forces you to either handle them with try-catch or declare
them with throws.

Creating Your Own Exception Types


You can make your own specific error types.

// Custom Exception Example


class MyCustomException extends Exception { // It's a type of
Exception
public MyCustomException(String message) {
super(message); // Pass the message to the Exception
class constructor
}
}

public class CustomExceptionDemo {


static void validateInput(String input) throws
MyCustomException {
if (input.equalsIgnoreCase("invalid")) {
throw new MyCustomException("The input '" + input +
"' is not allowed!");
}
System.out.println("Input '" + input + "' is valid.");
}

public static void main(String[] args) {


try {
validateInput("valid_data");
validateInput("invalid");
} catch (MyCustomException e) {
System.out.println("Caught a custom error: " +
e.getMessage());
}
}
}

Output:

Input 'valid_data' is valid.


Caught a custom error: The input 'invalid' is not allowed!

Chained Exceptions (Newer Feature)


Sometimes, one error happens because of another, earlier error. Chained exceptions let
you link these.
Imagine an IOException (can't read file) happens because your network connection
(NetworkDownException) failed first.

// Chained Exception Simple Example


public class ChainedExceptionDemoSimple {

static void performOuterTask() throws Exception {


try {
// Simulate an inner task that fails
performInnerTask();
} catch (ArithmeticException cause) {
// The ArithmeticException was the 'cause'
// We wrap it in a new, more general exception
throw new Exception("Outer task failed due to an
issue.", cause);
}
}

static void performInnerTask() throws ArithmeticException {


// This is the original problem
throw new ArithmeticException("Inner task: division by
zero problem");
}

public static void main(String[] args) {


try {
performOuterTask();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
// Get the original (underlying) cause
if (e.getCause() != null) {
System.out.println("Caused by: " +
e.getCause().getMessage());
}
}
}
}

Output:

Error: Outer task failed due to an issue.


Caused by: Inner task: division by zero problem.

This helps you trace back to the root cause of a problem.


Key Takeaways:

• Exceptions are for unexpected runtime errors.


• try monitors code for errors.
• catch handles errors if they occur.
• finally runs code no matter what (good for cleanup).
• throw lets you manually signal an error.
• throws declares that a method might cause an error it doesn't handle.
• Handling exceptions makes your programs more robust and prevents them from
crashing unexpectedly.

Chapter 13

String Handling

Core Idea: Two Types of Text Holders

1. String (The "Written in Pen" Text): Immutable


o What it is: A sequence of characters (like "hello").
o Key Feature: Once you create a String object, you cannot change the
actual characters inside it.
o Analogy: Think of it like writing something down with a permanent pen. If
you want to change it, you have to take a new piece of paper and write the
corrected version. The original is still there, unchanged.
o Why? This makes String objects safe to share and efficient for Java to
manage behind the scenes.
2. StringBuffer (The "Written in Pencil" Text): Mutable
o What it is: Also a sequence of characters, but designed to be changed.
o Key Feature: You can change the characters inside
a StringBuffer object after it's created – add more, delete some,
change existing ones.
o Analogy: Think of it like writing something down with a pencil. You can
erase, add, and modify it directly on the same paper.
o Why? Useful when you need to build up a string piece by piece, or make
many modifications.
o Modern Note: StringBuilder is generally preferred
over StringBuffer now. It does the same thing but is faster in most
common scenarios (single-threaded applications). StringBuffer is
"thread-safe," which means it's safer if multiple parts of your program
might try to change it at the exact same time, but this adds a bit of
performance overhead. For simplicity, we'll focus on the concepts, which
apply to both.

Let's dive into String first:

String - The Unchangeable Text

1. Creating Strings:
o The easiest way:
o String greeting = "Hello, World!"; // This is a string
literal
String name = "Alice";

o From an array of characters:


o char[] letters = {'J', 'a', 'v', 'a'};
o String language = new String(letters); // language
becomes "Java"
System.out.println(language);
o Copying another string (less common for simple initialization):
o String original = "Test";
o String copy = new String(original); // copy also
becomes "Test"
System.out.println(copy);
2. Getting Information about a String:
o length(): How many characters are in it?
o String message = "Hi there";
o int len = message.length(); // len will be 8 (space
counts!)
System.out.println("Length: " + len);
ocharAt(index): Get the character at a specific position (positions start
from 0).
o String word = "Java";
o char firstChar = word.charAt(0); // firstChar will be
'J'
o char thirdChar = word.charAt(2); // thirdChar will be
'v'
o System.out.println("First character: " + firstChar);
System.out.println("Third character: " + thirdChar);
3. Comparing Strings:
o equals(anotherString): Checks if two strings have the exact same
characters in the same order (case-sensitive). This is the right way to
compare string content.
o String s1 = "Hello";
o String s2 = "Hello";
o String s3 = "hello";
o String s4 = "Goodbye";
o
o System.out.println(s1.equals(s2)); // true
o System.out.println(s1.equals(s3)); // false (case
matters)
System.out.println(s1.equals(s4)); // false
o equalsIgnoreCase(anotherString): Same as equals(), but
ignores if letters are uppercase or lowercase.
o String s1 = "Hello";
o String s3 = "hello";
System.out.println(s1.equalsIgnoreCase(s3)); // true
o IMPORTANT: == vs equals()
▪ == checks if two string variables point to the exact same object in
memory.
▪ equals() checks if the content (characters) of the strings are the
same.
▪ Always use equals() to compare string content.
o String strA = "test";
o String strB = "test";
o String strC = new String("test"); // Forces creation
of a new object
o
o System.out.println("strA == strB: " + (strA == strB));
// Often true (Java optimizes literals)
o System.out.println("strA == strC: " + (strA == strC));
// False (strC is a new object)
System.out.println("strA.equals(strC): " +
strA.equals(strC)); // True (content is the same)
4. "Changing" Strings (Remember, you're actually creating NEW strings):
o Concatenation (+ operator): Joining strings together.
o String firstName = "John";
o String lastName = "Doe";
o String fullName = firstName + " " + lastName; //
fullName becomes "John Doe"
o System.out.println(fullName);
o
o int age = 30;
o String info = "Age: " + age; // age (int) is converted
to "30"
System.out.println(info); // "Age: 30"
o substring(startIndex): Get a part of the string from startIndex to
the end.
o substring(startIndex, endIndex): Get a part of the string
from startIndex up to (but not including) endIndex.
o String sentence = "This is a sample sentence.";
o String part1 = sentence.substring(10); // "sample
sentence."
o String part2 = sentence.substring(5, 7); // "is" (from
index 5 up to 7)
o System.out.println(part1);
System.out.println(part2);
o replace(oldChar, newChar) or replace(oldSequence,
newSequence): Get a new string with replacements.
o String originalText = "Hello, color!";
o String newText1 = originalText.replace('o', 'a');
// "Hella, calar!"
o String newText2 = originalText.replace("color",
"world"); // "Hello, world!"
o System.out.println(newText1);
System.out.println(newText2);
o toLowerCase() / toUpperCase(): Get a new string in all lowercase or
all uppercase.
o String mixedCase = "TeStInG";
o String lower = mixedCase.toLowerCase(); // "testing"
o String upper = mixedCase.toUpperCase(); // "TESTING"
o System.out.println(lower);
System.out.println(upper);
o trim(): Get a new string with spaces at the beginning and end removed.
o String padded = " lots of spaces ";
o String trimmed = padded.trim(); // "lots of spaces"
System.out.println("'" + trimmed + "'");
5. Searching within Strings:
o indexOf(charOrString): Find the first position of a character or
substring. Returns -1 if not found.
o lastIndexOf(charOrString): Find the last position.
o String data = "The quick brown fox jumps over the lazy
dog.";
o int firstThe = data.indexOf("the"); // 0 (if case-
sensitive, otherwise finds "the" at 31)
o // (The example text
actually has "The" at start)
o int firstTheIgnoreCase =
data.toLowerCase().indexOf("the"); // 0
o int lastThe = data.lastIndexOf("the"); // 31
o int indexOfX = data.indexOf('x'); // 16
o int indexOfZzz = data.indexOf("zzz"); // -1 (not
found)
o
o System.out.println("First 'the' (case ignored): " +
firstTheIgnoreCase);
o System.out.println("Last 'the': " + lastThe);
o System.out.println("Index of 'x': " + indexOfX);
System.out.println("Index of 'zzz': " + indexOfZzz);
6. Converting Other Types to String:
o String.valueOf(someValue): A universal way to convert numbers,
booleans, etc., to strings.
o int number = 123;
o double price = 19.99;
o boolean isActive = true;
o
o String numStr = String.valueOf(number); // "123"
o String priceStr = String.valueOf(price); // "19.99"
o String boolStr = String.valueOf(isActive); // "true"
o
o System.out.println(numStr);
o System.out.println(priceStr);
System.out.println(boolStr);

StringBuffer (and StringBuilder) - The Changeable Text

Use this when you know you'll be modifying a string many times, like building it up in a
loop.

1. Creating StringBuffer:
2. StringBuffer sb1 = new StringBuffer(); // Starts empty,
default capacity
3. StringBuffer sb2 = new StringBuffer("Initial Text"); //
Starts with some text
StringBuffer sb3 = new StringBuffer(50); // Starts empty,
but reserves space for 50 chars

(Replace StringBuffer with StringBuilder for most new


code: StringBuilder sb = new StringBuilder();)
4. Key Methods for Modifying:
o append(data): Adds data (string, number, char, boolean, etc.) to the
end. This is very common.
o StringBuilder report = new StringBuilder();
o report.append("Report Title: Sales\n"); // \n is a
newline character
o report.append("Date: ");
o report.append("2023-10-27\n");
o report.append("Total items: ").append(150); //
Chaining calls
o
o System.out.println(report.toString()); // Need
toString() to get a regular String
o /* Output:
o Report Title: Sales
o Date: 2023-10-27
o Total items: 150
*/
o insert(index, data): Inserts data at a specific position.
o StringBuilder sb = new StringBuilder("Hello World");
o sb.insert(6, "Java "); // Inserts "Java " at index 6
(before "World")
System.out.println(sb.toString()); // "Hello Java
World"
o delete(startIndex, endIndex): Removes characters
from startIndex up to (but not including) endIndex.
o deleteCharAt(index): Removes the character at a specific position.
o StringBuilder sb = new StringBuilder("This is a bad
example.");
o sb.delete(10, 14); // Deletes "bad " (indices 10, 11,
12, 13)
o System.out.println(sb.toString()); // "This is a
example."
o
o sb.deleteCharAt(sb.length() - 1); // Delete the last
character (the '.')
System.out.println(sb.toString()); // "This is a
example"
o replace(startIndex, endIndex, newString): Replaces a part of
the StringBuffer with newString.
o StringBuilder sb = new StringBuilder("I like cats.");
o sb.replace(7, 11, "dogs"); // Replaces "cats" with
"dogs"
System.out.println(sb.toString()); // "I like dogs."
o reverse(): Reverses the characters in the StringBuffer.
o StringBuilder sb = new StringBuilder("desserts");
o sb.reverse();
System.out.println(sb.toString()); // "stressed"
5. Getting Information:
o length(): Current number of characters.
o capacity(): How much space is allocated (can be more than length to
avoid reallocating too often).
o charAt(index) and setCharAt(index, char): Get or set a
character at a position.
o StringBuilder sb = new StringBuilder("Hollo");
o System.out.println("Length: " + sb.length()); // 5
o System.out.println("Character at 1: " + sb.charAt(1));
// 'o'
o sb.setCharAt(1, 'e'); // Change 'o' at index 1 to 'e'
System.out.println(sb.toString()); // "Hello"
6. Converting back to String:
o toString(): When you're done modifying
your StringBuffer (or StringBuilder), you usually convert it back to
a regular String.
o StringBuilder builder = new StringBuilder();
o for (int i = 0; i < 5; i++) {
o builder.append(i).append(" ");
o }
o String result = builder.toString(); // result is "0 1
2 3 4 "
System.out.println(result);

When to Use Which:

• String:
o For text that won't change.
o Most of the time, for simple text representation.
o When passing text around (methods, etc.) because they are inherently
safe from modification.
• StringBuilder (or StringBuffer if thread safety is a must):
o When you need to build a string in a loop.
o When you are performing many modifications (append, insert, delete) on a
sequence of characters.
o String s = ""; for (int i=0; i<1000; i++) { s = s + i;
} <-- BAD performance! This creates 1000 new String objects.
o StringBuilder sb = new StringBuilder(); for (int i=0;
i<1000; i++) { sb.append(i); } String s =
sb.toString(); <-- GOOD performance! Modifies one object.

Chapter 14
Exploring java.lang

java.lang is like the most basic toolbox for any Java programmer. You get it
automatically in every Java program; you don't even need to write import
java.lang.*; because Java does it for you. It contains the essential building blocks.

Here's a simplified look at its key components:

1. Simple Type Wrappers: Giving Superpowers to Basic Types

Java has basic types like int (for whole numbers), double (for decimal
numbers), char (for single characters), and boolean (for true/false). These are fast
but are not "objects." Sometimes, you need them to act like objects (e.g., to store them
in collections like ArrayList). Wrapper classes "wrap" these basic types into objects.

• Number (The Parent): This is an abstract class, like a blueprint for all numeric
wrapper classes. You don't use it directly often.
• Integer (for int):
o Purpose: Wraps an int value into an object. Also provides utility
methods for int.
o Key uses: Converting a String to an int, storing int in collections.
o Example:
o public class IntegerExample {
o public static void main(String[] args) {
o // Convert String to int
o String numStr = "123";
o int number = Integer.parseInt(numStr);
o System.out.println("String to int: " + (number
+ 7)); // Output: 130
o
o // Wrap an int into an Integer object
o Integer myIntObject = Integer.valueOf(42);
o System.out.println("Integer object value: " +
myIntObject.intValue()); // Output: 42
o }
}
• Long (for long): Similar to Integer, but for larger whole numbers (long).
• Short (for short): Similar to Integer, but for smaller whole numbers
(short).
• Byte (for byte): Similar to Integer, but for very small whole numbers (byte).
• Double (for double):
o Purpose: Wraps a double (decimal) value.
o Key uses: Converting String to double, special values like NaN (Not a
Number), POSITIVE_INFINITY.
o Example:
o public class DoubleExample {
o public static void main(String[] args) {
o Double d1 = Double.valueOf("3.14");
o System.out.println("Double from String: " +
d1.doubleValue()); // Output: 3.14
o
o Double infiniteVal = Double.POSITIVE_INFINITY;
o Double nanVal = Double.NaN; // Not a Number
(e.g., 0.0 / 0.0)
o
o System.out.println("Is d1 infinite? " +
d1.isInfinite()); // Output: false
o System.out.println("Is infiniteVal infinite? "
+ infiniteVal.isInfinite()); // Output: true
o System.out.println("Is nanVal NaN? " +
nanVal.isNaN()); // Output: true
o }
}
• Float (for float): Similar to Double, but for float (less precise decimal)
values.
• Character (for char):
o Purpose: Wraps a char value. Provides many utility methods for
characters.
o Key uses: Checking if a character is a digit, letter, uppercase, etc.
o Example:
o public class CharacterExample {
o public static void main(String[] args) {
o char myChar = 'A';
o Character charObj = Character.valueOf(myChar);
o
o System.out.println("Is '" + myChar + "' a
letter? " + Character.isLetter(myChar)); // Output:
true
o System.out.println("Is '7' a digit? " +
Character.isDigit('7')); // Output: true
o System.out.println("Is ' ' whitespace? " +
Character.isWhitespace(' ')); // Output: true
o }
}
• Boolean (for boolean):
o Purpose: Wraps a boolean (true/false) value.
o Example:
o public class BooleanExample {
o public static void main(String[] args) {
o Boolean boolTrue = Boolean.valueOf(true);
o Boolean boolFromString =
Boolean.valueOf("TrUe"); // Case-insensitive "true"
o
o System.out.println("boolTrue: " +
boolTrue.booleanValue()); // Output: true
o System.out.println("boolFromString: " +
boolFromString.booleanValue()); // Output: true
o }
}
• Void: Represents the void keyword as a type. You rarely use this directly.

2. Object: The Grandparent of All Classes

Every class in Java is a descendant of Object, whether you say so or not. It provides
some fundamental methods that all objects have.

• Key Methods:
o equals(Object obj): Checks if two objects are "equal" (you often
override this).
o hashCode(): Returns a number representing the object (used in hash-
based collections).
o toString(): Returns a String representation of the object (you often
override this to make it meaningful).
o getClass(): Tells you what class an object belongs to.
o clone(): Creates a copy of an object (needs Cloneable interface).
• Example (toString, getClass):
• class Person {
• String name;
• Person(String name) { this.name = name; }

• @Override // Overriding toString for better output
• public String toString() {
• return "Person[name=" + name + "]";
• }
• }

• public class ObjectExample {
• public static void main(String[] args) {
• Person p = new Person("Ali");
• System.out.println(p.toString()); // Output:
Person[name=Ali]
• System.out.println("Class of p: " +
p.getClass().getName()); // Output: Person
• }
}

3. String: For Text

• Purpose: Represents sequences of characters (text). Strings are immutable,


meaning once created, their value cannot be changed. Any operation that seems
to modify a string actually creates a new one.
• Example:
• public class StringExample {
• public static void main(String[] args) {
• String greeting = "Hello";
• String name = "World";
• String message = greeting + " " + name + "!"; //
Concatenation creates a new String

• System.out.println(message); // Output: Hello
World!
• System.out.println("Length: " + message.length());
// Output: 12
• System.out.println("Substring: " +
message.substring(0, 5)); // Output: Hello
• }
}

4. StringBuffer and StringBuilder: For Modifiable Text

• Purpose: When you need to change text a lot (e.g., building a long string piece
by piece), String is
inefficient. StringBuffer and StringBuilder are mutable (can be
changed).
o StringBuffer: Thread-safe (slower, use if multiple threads might
change it).
o StringBuilder: Not thread-safe (faster, use if only one thread changes
it - most common case).
• Example (StringBuilder):
• public class StringBuilderExample {
• public static void main(String[] args) {
• StringBuilder sb = new StringBuilder("Hi");
• sb.append(" "); // Add to the end
• sb.append("There");
• sb.insert(0, "Oh, "); // Insert at the beginning

• System.out.println(sb.toString()); // Output: Oh,
Hi There
• }
}

5. Math: For Mathematical Operations

• Purpose: Provides common math functions. All its methods are static, so you
call them on the class itself (e.g., Math.sqrt()).
• Key Methods: sqrt() (square root), pow() (power), abs() (absolute
value), max(), min(), random() (random number), sin(), cos(), PI, E.
• Example:
• public class MathExample {
• public static void main(String[] args) {
• System.out.println("Square root of 25: " +
Math.sqrt(25)); // Output: 5.0
• System.out.println("2 to the power of 3: " +
Math.pow(2, 3)); // Output: 8.0
• System.out.println("A random number (0-1): " +
Math.random());
• System.out.println("Value of PI: " + Math.PI);
• }
}
• StrictMath: Similar to Math, but guarantees bit-for-bit identical results across
all Java platforms for its floating-point operations. This might come at a slight
performance cost.

6. System: Access to System Resources

• Purpose: Provides access to system-level things like standard input/output,


system properties, and the garbage collector.
• Key Members/Methods:
o System.out: Standard output stream (usually the console).
o System.in: Standard input stream (usually the keyboard).
o System.err: Standard error stream (usually the console).
o System.exit(int status): Terminates the program.
o System.currentTimeMillis(): Gets current time in milliseconds.
o System.getProperty(String key): Gets system properties (like
Java version, OS name).
o System.gc(): Suggests to the JVM to run garbage collection.
• Example:
• public class SystemExample {
• public static void main(String[] args) {
• System.out.println("Hello from System.out!"); //
Prints to console

• long startTime = System.currentTimeMillis();
• // Do some work...
• for(int i = 0; i < 100000; i++);
• long endTime = System.currentTimeMillis();
• System.out.println("Time taken: " + (endTime -
startTime) + " ms");

• System.out.println("Java Version: " +
System.getProperty("java.version"));
• System.out.println("OS Name: " +
System.getProperty("os.name"));

• // System.exit(0); // This would stop the program
here
• }
}

7. Classes for Multithreading

These help you run multiple parts of your program simultaneously.

• Thread: Represents a thread of execution (a single path of code running).


• Runnable (Interface): An interface you implement to define what code a thread
should run. It has one method: run().
• ThreadGroup: A way to manage a collection of threads as a single unit.
• ThreadLocal / InheritableThreadLocal: Variables that have a separate
copy for each thread.
• Example (Thread and Runnable):
• class MyTask implements Runnable {
• private String taskName;
• public MyTask(String name) { this.taskName = name; }

• @Override
• public void run() { // This is what the thread will do
• for (int i = 1; i <= 3; i++) {
• System.out.println(taskName + " - Count: " + i
+ " (Thread: " + Thread.currentThread().getName() + ")");
• try {
• Thread.sleep(500); // Pause for 0.5 seconds
• } catch (InterruptedException e) {
• System.out.println(taskName + "
interrupted.");
• }
• }
• }
• }

• public class ThreadExample {
• public static void main(String[] args) {
• System.out.println("Main thread started: " +
Thread.currentThread().getName());

• Thread thread1 = new Thread(new MyTask("TaskA"),
"WorkerThread-1");
• Thread thread2 = new Thread(new MyTask("TaskB"),
"WorkerThread-2");

• thread1.start(); // Starts the thread, which calls
MyTask's run() method
• thread2.start();

• System.out.println("Main thread finished initiating
other threads.");
• }
• }
// Output will be interleaved as threads run concurrently.

8. Runtime: Interacting with the Java Runtime Environment

• Purpose: Allows your program to interface with the environment in which it's
running.
• Key Methods:
o Runtime.getRuntime(): Gets the current Runtime object.
o freeMemory(), totalMemory(): Get information about memory.
o gc(): Suggests garbage collection (like System.gc()).
o exec(String command): Executes an external program/command (can
be risky and platform-dependent).
• Example:
• public class RuntimeExample {
• public static void main(String[] args) {
• Runtime runtime = Runtime.getRuntime();

• System.out.println("Total Memory: " +
runtime.totalMemory() + " bytes");
• System.out.println("Free Memory: " +
runtime.freeMemory() + " bytes");

• runtime.gc(); // Suggest garbage collection
• System.out.println("Free Memory after GC
suggestion: " + runtime.freeMemory() + " bytes");

• /*
• // Example of running an external command (e.g.,
'notepad' on Windows)
• // Be careful with exec(), it can have security
implications.
• try {
• // Process p = runtime.exec("notepad.exe"); //
For Windows
• // Process p = runtime.exec("gedit"); // For
some Linux
• // p.waitFor(); // Wait for the process to
finish
• // System.out.println("External program
finished.");
• } catch (Exception e) {
• System.err.println("Error executing external
program: " + e.getMessage());
• }
• */
• }
}

9. Process: Represents an External Program

• Purpose: When you use Runtime.exec(), it returns a Process object. This


object lets you control and get information from the external program (e.g., its
output, exit code).

10. Class: Information About Classes at Runtime

• Purpose: Represents a class or interface in a running Java application. You can


get metadata (data about data) like the class name, its methods, fields,
superclass, etc. This is a core part of "reflection."
• Example:
• public class ClassExample {
• public static void main(String[] args) {
• String myString = "Hello";
• Class<?> stringClassInfo = myString.getClass(); //
Get Class object for String

• System.out.println("Class Name: " +
stringClassInfo.getName()); // Output: java.lang.String
• System.out.println("Simple Name: " +
stringClassInfo.getSimpleName()); // Output: String
• System.out.println("Is it an interface? " +
stringClassInfo.isInterface()); // Output: false

• Class<?> mathClassInfo = Math.class; // Another way
to get Class object
• System.out.println("Superclass of Math: " +
mathClassInfo.getSuperclass().getName()); // Output:
java.lang.Object
• }
}

11. Other Important Classes & Interfaces

• ClassLoader: Responsible for loading class files into the JVM. Advanced topic.
• Compiler: Provides access to the Java compiler. Rarely used directly in typical
applications.
• SecurityManager: Used to define and enforce security policies. Advanced
topic.
• Throwable: The parent class for all errors and exceptions in Java. If something
goes wrong, an object of a class derived from Throwable is "thrown."
o Example (conceptual, exceptions are covered in more detail
elsewhere):
o public class ThrowableExample {
o public static void main(String[] args) {
o try {
o int result = 10 / 0; // This will cause an
ArithmeticException
o System.out.println(result);
o } catch (ArithmeticException e) { //
ArithmeticException is a subclass of Throwable
o System.err.println("Oops, an error: " +
e.getMessage());
o // e.printStackTrace(); // Prints detailed
error info
o }
o }
}
• Package: Represents package information (like version details).
• StackTraceElement: Represents a single "stack frame" in an error's stack
trace (tells you where in the code an error happened).
• RuntimePermission: Related to Java's security model for runtime operations.

Interfaces in java.lang:

• Cloneable: A "marker" interface. If a class implements Cloneable, it indicates


that it's okay to make copies (clones) of its objects using
the Object.clone() method. It has no methods to implement.
• Comparable<T>:
o Purpose: Allows objects of a class to be compared to each other, defining
a "natural ordering." Useful for sorting.
o Method to implement: int compareTo(T otherObject)
▪ Returns a negative integer if this object is less
than otherObject.
▪ Returns zero if this object is equal to otherObject.
▪ Returns a positive integer if this object is greater
than otherObject.
o Example:
o class Book implements Comparable<Book> {
o String title;
o int pages;
o
o public Book(String title, int pages) {
o this.title = title;
o this.pages = pages;
o }
o
o @Override
o public int compareTo(Book otherBook) {
o // Natural order by number of pages
o return Integer.compare(this.pages,
otherBook.pages);
o // To sort by title: return
this.title.compareTo(otherBook.title);
o }
o
o @Override
o public String toString() {
o return title + " (" + pages + " pages)";
o }
o }
o
o public class ComparableExample {
o public static void main(String[] args) {
o Book b1 = new Book("Java Basics", 200);
o Book b2 = new Book("Advanced Java", 500);
o
o if (b1.compareTo(b2) < 0) {
o System.out.println(b1.title + " comes
before " + b2.title + " in natural order.");
o } else {
o System.out.println(b2.title + " comes
before " + b1.title + " in natural order.");
o }
o // Output: Java Basics comes before Advanced
Java in natural order.
o }
}
• Runnable: (Already covered under Multithreading) Defines the run() method
for threads.
• CharSequence:
o Purpose: Represents a read-only sequence of
characters. String, StringBuffer, and StringBuilder all
implement this.
o Key methods: length(), charAt(int index), subSequence(int
start, int end).
o Example:
o public class CharSequenceExample {
o public static void
printCharSequenceInfo(CharSequence cs) {
o System.out.println("Content: " +
cs.toString());
o System.out.println("Length: " + cs.length());
o if (cs.length() > 0) {
o System.out.println("First char: " +
cs.charAt(0));
o }
o }
o
o public static void main(String[] args) {
o String str = "Hello";
o StringBuilder sb = new StringBuilder("World");
o
o printCharSequenceInfo(str);
o System.out.println("----");
o printCharSequenceInfo(sb);
o }
}

Sub-packages of java.lang:

• java.lang.ref: Provides more control over garbage collection using


"reference objects" (like SoftReference, WeakReference). Advanced.
• java.lang.reflect: Contains classes for "reflection," which is the ability of a
program to examine or modify its own structure and behavior at runtime (e.g.,
discover methods of a class, call them dynamically). Advanced.

Create a form in java oop and connect it with the database:

Let's create a simple Java Swing Student Form with CRUD (Create, Read, Update,
Delete) operations connected to a MySQL database.

Complete Procedure:

Part 1: Setup MySQL Database


1. Install MySQL: If you haven't already, download and install MySQL Community
Server from the official website. During installation, remember the root password
you set.
2. Install MySQL Workbench (Optional but Recommended): This is a GUI tool
to manage your database.
3. Create Database and Table:
o Open MySQL Workbench or the MySQL command-line client.
o Execute the following SQL commands:
4. CREATE DATABASE studentdb;
5.
6. USE studentdb;
7.
8. CREATE TABLE students (
9. id INT AUTO_INCREMENT PRIMARY KEY,
10. name VARCHAR(100) NOT NULL,
11. roll_number VARCHAR(20) NOT NULL UNIQUE,
12. department VARCHAR(50)
13. );
14.
15. -- You can add a sample student if you want:
INSERT INTO students (name, roll_number, department) VALUES
('Aarav Sharma', 'S101', 'Computer Science');

Part 2: Setup VS Code Project

1. Install Java Development Kit (JDK): Make sure you have JDK installed.
2. Install VS Code: Download and install Visual Studio Code.
3. Install Java Extensions for VS Code:
o Open VS Code.
o Go to the Extensions view (Ctrl+Shift+X).
o Search for "Extension Pack for Java" by Microsoft and install it. This will
install several useful Java extensions.
4. Download MySQL Connector/J:
o Go to the MySQL Connector/J download
page: https://dev.mysql.com/downloads/connector/j/
o Select "Platform Independent" and download the ZIP or TAR archive.
o Extract the archive. You will find a .jar file like mysql-connector-j-
X.X.XX.jar (e.g., mysql-connector-j-8.0.33.jar).
5. Create a New Java Project in VS Code:
o Open the Command Palette (Ctrl+Shift+P).
o Type "Java: Create Java Project".
o Select "No build tools".
o Choose a location for your project (e.g., StudentFormApp).
o Enter a project name (e.g., StudentFormApp).
6. Add MySQL Connector/J to Project:
o Inside your project folder (e.g., StudentFormApp), create a folder
named lib.
o Copy the mysql-connector-j-X.X.XX.jar file into this lib folder.
o In VS Code's Explorer, right-click on the .jar file under the lib folder
and select "Add to Classpath".
o Alternatively, VS Code might prompt you or you can manually edit
the .classpath file (if it exists) or configure it via the Java Projects view.
A simpler way is often:
▪ Open the Command Palette (Ctrl+Shift+P).
▪ Type "Java: Configure Classpath".
▪ Go to "Referenced Libraries" and click the "+" icon.
▪ Navigate to your lib folder and select the mysql-connector-j-
X.X.XX.jar file.

Part 3: Java Code

Create two Java files in your src folder:

1. DBConnection.java (for database connection logic)


2. StudentForm.java (for the GUI and application logic)

1. DBConnection.java

// src/DBConnection.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {


// --- IMPORTANT: Change these details to match your MySQL
setup ---
private static final String DB_URL =
"jdbc:mysql://localhost:3306/studentdb"; // Replace studentdb if
your DB name is different
private static final String USER = "root"; // Replace
with your MySQL username
private static final String PASS = "your_password"; //
Replace with your MySQL password
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- -
-- ---

public static Connection getConnection() {


Connection conn = null;
try {
// 1. Register the JDBC driver (Optional for modern
JDBC versions, but good practice)
Class.forName("com.mysql.cj.jdbc.Driver");

// 2. Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
System.out.println("Connected database
successfully...");
} catch (SQLException se) {
System.err.println("SQL Exception: " +
se.getMessage());
se.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("MySQL JDBC Driver not found: " +
e.getMessage());
e.printStackTrace();
}
return conn;
}

public static void main(String[] args) {


// Test connection
Connection conn = getConnection();
if (conn != null) {
System.out.println("Test connection successful!");
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("Test connection failed.");
}
}
}

Important:

• Modify DB_URL, USER, and PASS in DBConnection.java to match your


MySQL server's details.
• The main method in DBConnection.java is just for testing the connection
independently.

2. StudentForm.java

// src/StudentForm.java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;

public class StudentForm extends JFrame {

// GUI Components
private JTextField txtName, txtRollNumber, txtDepartment;
private JButton btnAdd, btnView, btnUpdate, btnDelete,
btnClear;
private JTable studentTable;
private DefaultTableModel tableModel;
private JScrollPane scrollPane;

// Database Connection
private Connection conn;
public StudentForm() {
// Initialize Database Connection
conn = DBConnection.getConnection();
if (conn == null) {
JOptionPane.showMessageDialog(this, "Failed to
connect to database. Exiting.", "Database Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1); // Exit if DB connection fails
}

// Frame Setup
setTitle("Student Management System");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window
setLayout(new BorderLayout(10, 10)); // Main layout

// --- Input Panel ---


JPanel inputPanel = new JPanel(new GridLayout(4, 2, 5,
5)); // Rows, Cols, HGap, VGap
inputPanel.setBorder(BorderFactory.createEmptyBorder(10,
10, 10, 10)); // Padding

inputPanel.add(new JLabel("Name:"));
txtName = new JTextField();
inputPanel.add(txtName);

inputPanel.add(new JLabel("Roll Number:"));


txtRollNumber = new JTextField();
inputPanel.add(txtRollNumber);

inputPanel.add(new JLabel("Department:"));
txtDepartment = new JTextField();
inputPanel.add(txtDepartment);

add(inputPanel, BorderLayout.NORTH);

// --- Button Panel ---


JPanel buttonPanel = new JPanel(new
FlowLayout(FlowLayout.CENTER, 10, 10));
btnAdd = new JButton("Add Student");
btnView = new JButton("View Students");
btnUpdate = new JButton("Update Student");
btnDelete = new JButton("Delete Student");
btnClear = new JButton("Clear Fields");

buttonPanel.add(btnAdd);
buttonPanel.add(btnView);
buttonPanel.add(btnUpdate);
buttonPanel.add(btnDelete);
buttonPanel.add(btnClear);

add(buttonPanel, BorderLayout.SOUTH);

// --- Table Panel ---


String[] columnNames = {"ID", "Name", "Roll Number",
"Department"};
tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // Make table cells non-editable
}
};
studentTable = new JTable(tableModel);
scrollPane = new JScrollPane(studentTable);
add(scrollPane, BorderLayout.CENTER);

// --- Action Listeners ---


btnAdd.addActionListener(e -> addStudent());
btnView.addActionListener(e -> viewStudents());
btnUpdate.addActionListener(e -> updateStudent());
btnDelete.addActionListener(e -> deleteStudent());
btnClear.addActionListener(e -> clearFields());

// Mouse listener for table row selection


studentTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int selectedRow = studentTable.getSelectedRow();
if (selectedRow >= 0) {
// ID is not directly editable, but useful
for update/delete
//
txtId.setText(tableModel.getValueAt(selectedRow, 0).toString());

txtName.setText(tableModel.getValueAt(selectedRow,
1).toString());

txtRollNumber.setText(tableModel.getValueAt(selectedRow,
2).toString());

txtDepartment.setText(tableModel.getValueAt(selectedRow,
3).toString());
txtRollNumber.setEditable(false); // Don't
allow editing roll number when updating via selection
}
}
});

// Load initial data


viewStudents();
}

private void addStudent() {


String name = txtName.getText();
String rollNumber = txtRollNumber.getText();
String department = txtDepartment.getText();

if (name.isEmpty() || rollNumber.isEmpty()) {
JOptionPane.showMessageDialog(this, "Name and Roll
Number are required!", "Input Error",
JOptionPane.ERROR_MESSAGE);
return;
}

String sql = "INSERT INTO students (name, roll_number,


department) VALUES (?, ?, ?)";
try (PreparedStatement pstmt =
conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setString(2, rollNumber);
pstmt.setString(3, department);
int affectedRows = pstmt.executeUpdate();
if (affectedRows > 0) {
JOptionPane.showMessageDialog(this, "Student
added successfully!");
clearFields();
viewStudents(); // Refresh table
} else {
JOptionPane.showMessageDialog(this, "Failed to
add student.", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
if (ex.getSQLState().equals("23000")) { // Integrity
constraint violation (e.g., duplicate roll_number)
JOptionPane.showMessageDialog(this, "Error:
Roll Number already exists!\n" + ex.getMessage(), "Database
Error", JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Database
error: " + ex.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
}
ex.printStackTrace();
}
}

private void viewStudents() {


// Clear existing rows
tableModel.setRowCount(0);

String sql = "SELECT id, name, roll_number, department


FROM students";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {

while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String rollNumber = rs.getString("roll_number");
String department = rs.getString("department");
tableModel.addRow(new Object[]{id, name,
rollNumber, department});
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error fetching
students: " + ex.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}

private void updateStudent() {


String name = txtName.getText();
String rollNumber = txtRollNumber.getText(); // This
should be the key for update
String department = txtDepartment.getText();

if (rollNumber.isEmpty()) {
JOptionPane.showMessageDialog(this, "Select a
student or enter Roll Number to update.", "Input Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (name.isEmpty()) {
JOptionPane.showMessageDialog(this, "Name cannot be
empty for update.", "Input Error", JOptionPane.ERROR_MESSAGE);
return;
}

String sql = "UPDATE students SET name = ?, department =


? WHERE roll_number = ?";
try (PreparedStatement pstmt =
conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setString(2, department);
pstmt.setString(3, rollNumber); // Use roll number
in WHERE clause

int affectedRows = pstmt.executeUpdate();


if (affectedRows > 0) {
JOptionPane.showMessageDialog(this, "Student
updated successfully!");
clearFields();
viewStudents(); // Refresh table
} else {
JOptionPane.showMessageDialog(this, "Student
with Roll Number '" + rollNumber + "' not found or no changes
made.", "Update Info", JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Database error:
" + ex.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}

private void deleteStudent() {


String rollNumber = txtRollNumber.getText(); // Get roll
number from text field (populated by selection or manual input)

if (rollNumber.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please select a
student from the table or enter their Roll Number to delete.",
"Input Error", JOptionPane.ERROR_MESSAGE);
return;
}

int confirm = JOptionPane.showConfirmDialog(this,


"Are you sure you want to delete student with
Roll Number: " + rollNumber + "?",
"Confirm Deletion", JOptionPane.YES_NO_OPTION);

if (confirm == JOptionPane.YES_OPTION) {
String sql = "DELETE FROM students WHERE roll_number
= ?";
try (PreparedStatement pstmt =
conn.prepareStatement(sql)) {
pstmt.setString(1, rollNumber);
int affectedRows = pstmt.executeUpdate();

if (affectedRows > 0) {
JOptionPane.showMessageDialog(this, "Student
deleted successfully!");
clearFields();
viewStudents(); // Refresh table
} else {
JOptionPane.showMessageDialog(this, "Student
with Roll Number '" + rollNumber + "' not found.", "Delete
Error", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Database
error: " + ex.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}

private void clearFields() {


txtName.setText("");
txtRollNumber.setText("");
txtDepartment.setText("");
txtRollNumber.setEditable(true); // Make roll number
editable again after clearing
studentTable.clearSelection(); // Deselect any selected
row in the table
}

// Main method to launch the application


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // Ensures GUI
updates are on the Event Dispatch Thread
StudentForm form = new StudentForm();
form.setVisible(true);
});
}
}

Part 4: Compile and Run

1. Open StudentForm.java in VS Code.


2. Ensure mysql-connector-j-X.X.XX.jar is in your lib folder and added
to the classpath.
3. Right-click inside the StudentForm.java editor window.
4. Select "Run Java".

Alternatively, VS Code might show a "Run" link above the main method.

Explanation of the Code:

• DBConnection.java:
o Handles creating a connection to your MySQL database.
o Crucially, update DB_URL, USER, and PASS with your actual MySQL
credentials.
• StudentForm.java:
o GUI Components: JTextField for inputs, JButton for
actions, JTable to display data, DefaultTableModel to manage table
data.
o Layouts: BorderLayout for the main frame, GridLayout for the input
form, FlowLayout for buttons.
o Constructor (StudentForm()):
▪ Sets up the JFrame.
▪ Initializes DBConnection.getConnection().
▪ Creates and arranges all GUI components.
▪ Attaches ActionListeners to buttons to trigger methods when
clicked.
▪ Attaches a MouseAdapter to the JTable so when you click a
row, its data populates the input fields.
▪ Calls viewStudents() initially to load data.
o addStudent():
▪ Gets data from text fields.
▪ Constructs an SQL INSERT statement
using PreparedStatement (good for preventing SQL injection).
▪ Executes the statement.
▪ Shows a message and refreshes the table.
o viewStudents():
▪ Clears the current table.
▪ Executes an SQL SELECT query.

▪ Iterates through the ResultSet and adds each student record as


a new row in the JTable.
o updateStudent():
▪ Gets data from text fields. The roll_number is used as the key to
find the student to update.
▪ Constructs an SQL UPDATE statement.
▪ Executes and refreshes.
o deleteStudent():
▪ Gets the roll_number (usually from the selected row
via txtRollNumber).
▪ Asks for confirmation.
▪ Constructs an SQL DELETE statement.
▪ Executes and refreshes.
o clearFields(): Clears all input fields and deselects any table row.
o main(): The entry point of the application. It
uses SwingUtilities.invokeLater to ensure GUI creation and
updates happen on the Event Dispatch Thread (EDT), which is a best
practice for Swing applications.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy