0% found this document useful (0 votes)
30 views43 pages

Unit I OOJP

The document provides an overview of Java programming, including its history, key features, and modern updates. It details the environmental setup for Java development, including installation of the JDK and IDEs, as well as fundamental concepts such as data types, variables, modifiers, keywords, operators, and control structures. Additionally, it outlines Java's versatility, security, and extensive standard library, making it suitable for various applications.

Uploaded by

ferbi4127
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)
30 views43 pages

Unit I OOJP

The document provides an overview of Java programming, including its history, key features, and modern updates. It details the environmental setup for Java development, including installation of the JDK and IDEs, as well as fundamental concepts such as data types, variables, modifiers, keywords, operators, and control structures. Additionally, it outlines Java's versatility, security, and extensive standard library, making it suitable for various applications.

Uploaded by

ferbi4127
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/ 43

CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

UNIT - I
INTRODUCTION TO JAVA

History of Java:

Java is one of the most popular programming languages, known for its versatility,
platform independence, and robustness. Here is a brief history of Java:

1. Creation and Early Development (1991–1995)

- Origin: Java was developed by a team at Sun Microsystems, led by James Gosling, Mike
Sheridan, and Patrick Naughton. The project was initially called "Green."
- Purpose: The primary goal was to create a platform-independent language for embedded
systems like television set-top boxes.
- Original Name: Java was initially named *Oak* after an oak tree outside Gosling's office. The
name was later changed to *Java* because "Oak" was already trademarked.
- First Public Release: In 1995, Sun Microsystems officially released Java 1.0, emphasizing its
"Write Once, Run Anywhere" (WORA) capability.

2. Key Features and Philosophy

Java's design was guided by several key principles:


1. Platform Independence: Java programs are compiled into bytecode, which can run on any
device with a Java Virtual Machine (JVM).
2. Object-Oriented: Java is fully object-oriented, enabling code reuse and modular design.
3. Security: It introduced a secure execution environment, important for networked applications.
4. Simplicity: Java was designed to be easy to learn, drawing inspiration from C++ but
simplifying complex features.

3. Major Milestones

- 1996: Java Development Kit (JDK) 1.0 was released, marking Java's rapid adoption.
- 1997: The Java Community Process (JCP) was introduced to standardize and improve Java.
- 1999: Java 2 (J2SE 1.2) introduced significant enhancements, including Swing for GUIs and
the Collections Framework.
- 2004: Java 5 introduced generics, annotations, and the enhanced for-loop, making it more
developer-friendly.
- 2009: Oracle acquired Sun Microsystems, gaining control over Java.

1
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

- 2011: Oracle released Java 7, introducing features like try-with-resources and the fork/join
framework.
- 2014: Java 8 brought major changes, including lambdas, the Stream API, and a new date-time
API.

4. Modern Java
- Frequent Updates: Starting with Java 9 (2017), Oracle shifted to a six-month release cycle.
- Modularization: Java 9 introduced the Java Platform Module System (Project Jigsaw).
- Improved Performance: Modern Java versions (11, 17, 21) focus on performance, cloud
readiness, and new language features like records and sealed classes.
- Open Source: OpenJDK became the reference implementation of Java, ensuring its availability
as an open-source project.

5. Current Status
Java remains a leading language for various domains, including:
- Enterprise Applications: With frameworks like Spring and Jakarta EE.
- Mobile Development: As the base for Android applications.
- Big Data and Cloud Computing: Thanks to tools like Hadoop and Java-based cloud platforms.

Environmental Setup:

Setting up the environment for Java development involves installing the necessary tools
and configuring your system to compile and run Java programs. Here’s a step-by-step guide:

1. Install the Java Development Kit (JDK)


The JDK includes tools to compile, run, and debug Java applications.

1. Download the JDK:


- Visit the official Oracle website or [OpenJDK](https://openjdk.org/) to download the latest
JDK version.
- Choose the correct version for your operating system (Windows, macOS, or Linux).

2. Install the JDK:


- Run the installer and follow the prompts.
- Note the installation directory (e.g., `C:\Program Files\Java\jdk-<version>` on Windows).

3. Set the JAVA_HOME Environment Variable:


- Windows:
1. Right-click "This PC" > Properties > Advanced System Settings > Environment Variables.

2
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

2. Under "System variables," click New and set:


- Variable name: `JAVA_HOME`
- Variable value: Path to the JDK installation directory.
3. Add `%JAVA_HOME%\bin` to the `Path` variable.
- macOS/Linux:
Add the following to your shell configuration file (e.g., `.bashrc`, `.zshrc`):

export JAVA_HOME=/path/to/jdk
export PATH=$JAVA_HOME/bin:$PATH

4. Verify Installation:
Open a terminal or command prompt and type:

java -version

This should display the installed Java version.

2. Install an Integrated Development Environment (IDE)


While Java programs can be written in any text editor, using an IDE improves
productivity.

1. Popular IDEs:
- IntelliJ IDEA: Highly recommended for Java development.
- Eclipse: A robust and widely-used IDE.
- NetBeans: Another good option for beginners.
- VS Code: Lightweight and extensible, with Java extensions.

2. Install and Configure the IDE:


- Download the IDE from its official website.
- During installation, configure the IDE to use your installed JDK.

3. (Optional) Install Build Tools


Build tools simplify the process of managing dependencies and building Java projects.

1. Maven:
- Download from [Apache Maven](https://maven.apache.org/download.cgi).
- Configure `MAVEN_HOME` and add it to the system `Path`.

3
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

2. Gradle:
- Download from [Gradle](https://gradle.org/releases/).
- Configure `GRADLE_HOME` and add it to the system `Path`.

4. Set Up a Java Project


1. Create a Directory:

mkdir MyJavaProject
cd MyJavaProject

2. Write a Simple Java Program:


Create a file named `HelloWorld.java`:
Code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

3. Compile and Run the Program:


- Compile:

javac HelloWorld.java

This creates a `HelloWorld.class` file.


- Run:

java HelloWorld

5. Install Additional Tools


Depending on your use case, you may want to install:
- Version Control: Git for managing code repositories.
- Database Tools: MySQL, PostgreSQL, or Oracle DB for database integration.
- Testing Frameworks: JUnit or TestNG for unit testing.

6. Test Your Setup

4
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Create a small Java program or use an IDE's project templates to ensure everything works as
expected.

Features of Java:
Java is a versatile, powerful, and widely-used programming language. Its popularity
stems from a rich set of features designed to make development easier, more efficient, and
secure. Here are the key features of Java:

1. Platform Independence
- Java follows the "Write Once, Run Anywhere" (WORA) principle.
- Programs are compiled into bytecode by the Java compiler. This bytecode is executed by the
Java Virtual Machine (JVM), making Java applications platform-independent.

2. Object-Oriented
- Java is fully object-oriented, which helps developers model real-world scenarios.
- Key OOP concepts in Java:
- Encapsulation: Wrapping data and methods into a single unit (class).
- Inheritance: Reusing code from one class in another.
- Polymorphism: Using one interface to represent multiple forms.
- Abstraction: Hiding implementation details and showing only essential features.

3. Simple
- Java is designed to be easy to learn, especially for developers familiar with C or C++.
- It eliminates complex features like pointers, multiple inheritance, and operator overloading.

4. Secure
- Java provides a robust security model, making it suitable for web and enterprise applications.
- Security features include:
- Bytecode verification by the JVM.
- A built-in Security Manager for application sandboxing.
- No explicit use of pointers, reducing vulnerabilities.

5. Robust
- Java emphasizes reliability and error handling.
- Features contributing to robustness:
- Strong memory management (automatic garbage collection).
- Exception handling for runtime errors.
- Type-checking to detect errors early in the code.

5
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

6. Multithreaded
- Java supports multithreaded programming, allowing simultaneous execution of multiple threads
for better performance.
- It has built-in classes like `Thread` and `Runnable` and a synchronized mechanism for safe
thread interactions.

7. High Performance
- While Java is not as fast as languages like C++, its performance is optimized using techniques
like:
- Just-In-Time (JIT) Compiler: Converts bytecode to native machine code during execution for
faster performance.
- Efficient garbage collection algorithms.

8. Distributed
- Java simplifies the development of distributed systems.
- Features like Remote Method Invocation (RMI) and support for frameworks like Java EE make
Java ideal for distributed computing.

9. Dynamic
- Java programs can adapt to evolving environments.
- It supports dynamic class loading and runtime reflection, allowing applications to discover and
use new classes during execution.

10. Extensive Standard Library


- Java provides a rich set of APIs and libraries, categorized into packages such as:
- java.lang: Core language classes.
- java.util: Data structures and utilities.
- java.io: Input/output operations.
- java.net: Networking support.
- java.sql: Database connectivity.

11. Scalability
- Java is highly scalable, making it suitable for small applications as well as large-scale
enterprise systems.

12. Portability
- Java programs are portable due to:
- The platform-independent nature of bytecode.
- A consistent runtime environment across platforms.

6
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

13. Automatic Garbage Collection


- Java handles memory management automatically.
- The garbage collector identifies and removes unused objects, reducing the chances of memory
leaks.

14. Open Source


- Java is free and open source (through OpenJDK), allowing developers to contribute to its
evolution and use it without licensing fees.

15. Rich Ecosystem


- Java has a vast ecosystem of frameworks and tools, including:
- Spring, Hibernate, and Struts for web development.
- JUnit and TestNG for testing.
- Maven and Gradle for build automation.

Data Types:

1. Data Types in Java

Data types specify the type of data that variables can hold. They are broadly classified into two
categories:

Primitive Data Types


- Numeric Types:
- `byte` (1 byte): Stores integers from -128 to 127.
- `short` (2 bytes): Stores integers from -32,768 to 32,767.
- `int` (4 bytes): Stores integers from -2^31 to 2^31-1.
- `long` (8 bytes): Stores integers from -2^63 to 2^63-1.
- `float` (4 bytes): Stores single-precision decimal numbers.
- `double` (8 bytes): Stores double-precision decimal numbers.

- Character Type:
- `char` (2 bytes): Stores a single Unicode character (e.g., `'A'`, `'@'`).

- Boolean Type:
- `boolean` (1 bit): Stores `true` or `false`.

Reference Data Types


- Examples: Arrays, Classes, Interfaces, Enums.

7
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

- Used to refer to objects and support additional functionalities.

2. Variables in Java

Variables are containers for storing data values. Each variable has a type and a name.

Types of Variables:
1. Local Variables:
- Declared inside a method or block.
- Must be initialized before use.
Code:
void example() {
int localVar = 10;
}

2. Instance Variables:
- Declared inside a class but outside any method.
- Each object of the class has its copy.
Code:
class MyClass {
int instanceVar = 20;
}

3. Static Variables:
- Declared using the `static` keyword.
- Shared among all objects of the class.
Code:
static int staticVar = 30;

3. Modifiers

Modifiers define the scope, behavior, or properties of a class, method, or variable.

Access Modifiers:
1. `public`: Accessible from anywhere.
2. `protected`: Accessible within the package and subclasses.
3. `default` (no modifier): Accessible within the package.

8
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

4. `private`: Accessible only within the class.

Non-Access Modifiers:
- Class-level:
- `abstract`: Declares an abstract class.
- `final`: Prevents inheritance.
- `static`: Makes the class nested and non-instantiable.

- Variable-level:
- `final`: Prevents modification of the variable's value.
- `static`: Makes the variable shared among all instances.
- `volatile`: Indicates that the variable can be modified asynchronously.

- Method-level:
- `synchronized`: Ensures thread-safe execution.
- `final`: Prevents method overriding.
- `abstract`: Declares a method without implementation.

4. Keywords in Java

Java has 50+ reserved keywords with special meanings. Examples include:
- Control Flow: `if`, `else`, `for`, `while`, `do`, `switch`, `case`, `break`, `continue`.
- Modifiers: `public`, `private`, `protected`, `final`, `abstract`, `static`.
- Data Types: `int`, `double`, `char`, `boolean`, `void`.
- Exception Handling: `try`, `catch`, `finally`, `throw`, `throws`.
- Class-related: `class`, `interface`, `extends`, `implements`, `new`.
- Others: `return`, `this`, `super`, `import`, `package`.

5. Operators in Java

Operators perform operations on variables and values.

Types of Operators:
1. Arithmetic: `+`, `-`, `*`, `/`, `%`.
2. Relational (Comparison): `==`, `!=`, `<`, `>`, `<=`, `>=`.
3. Logical: `&&`, `||`, `!`.
4. Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>`, `>>>`.
5. Assignment: `=`, `+=`, `-=`, `*=`, `/=`, `%=`.
6. Unary: `+`, `-`, `++`, `--`.
7. Ternary: `? :` (e.g., `condition ? value1 : value2`).

9
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

6. Iterative Control Structures (Loops)

Java provides the following loops for iteration:

1. `for` Loop:
- Executes a block of code a fixed number of times.
Code:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}

2. Enhanced `for` Loop:


- Simplifies iteration over arrays or collections.
Code:
int[] nums = {1, 2, 3};
for (int num : nums) {
System.out.println(num);
}

3. `while` Loop:
- Repeats as long as the condition is `true`.
Code:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

4. `do-while` Loop:
- Executes at least once, then checks the condition.
Code:
int i = 0;
do {
System.out.println(i);

10
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

i++;
} while (i < 5);

Conditional and Control Statements:

Control statements in Java allow the program to make decisions, execute code based on
conditions, and control the flow of execution. They are broadly categorized into conditional
statements and control flow statements.

1. Conditional Statements
Conditional statements allow code execution based on whether a condition evaluates to `true` or
`false`.

a) if Statement
- Executes a block of code if the condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}

Example:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}

b) if-else Statement
- Executes one block of code if the condition is true, and another block if it is false.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Example:
int num = 10;
if (num % 2 == 0) {
System.out.println("Even number");

11
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

} else {
System.out.println("Odd number");
}

c) if-else-if Ladder
- Used when multiple conditions need to be checked sequentially.
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}

Example:
int marks = 85;
if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 75) {
System.out.println("Grade: A");
} else {
System.out.println("Grade: B");
}

d) switch Statement
- Simplifies checking multiple conditions by evaluating an expression and executing the
corresponding case.
Syntax:
switch (expression) {
case value1:
// Code for case value1
break;
case value2:
// Code for case value2
break;
default:
// Code if no cases match
}

12
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}

2. Control Flow Statements


Control flow statements manage the sequence of execution in a program.

a) Looping Statements
1. for Loop:
Syntax:
for (initialization; condition; update) {
// Code to execute
}

Example:

for (int i = 0; i < 5; i++) {


System.out.println(i);
}

2. while Loop:
Syntax:
while (condition) {
// Code to execute
}

Example:

13
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

3. do-while Loop:
Syntax:
do {
// Code to execute
} while (condition);

Example:

int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);

b) Jump Statements
1. break:
- Terminates the loop or switch statement.
Code:
for (int i = 0; i < 5; i++) {
if (i == 3) break;
System.out.println(i);
}

2. continue:
- Skips the rest of the current iteration and proceeds to the next iteration.
Code:
for (int i = 0; i < 5; i++) {
if (i == 3) continue;
System.out.println(i);
}

14
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

3. return:
- Exits from the current method and optionally returns a value.
Code:
int add(int a, int b) {
return a + b;
}

c) Exception Handling Control


- Use `try`, `catch`, `finally`, `throw`, and `throws` for handling errors gracefully.
Code:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle exception
} finally {
// Code that always executes
}

Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero is not allowed.");
} finally {
System.out.println("Execution completed.");
}

Command-Line Arguments:

Command-line arguments in Java allow users to pass information to a program during its
execution by providing inputs when starting the application from the command line.

How Command-Line Arguments Work

1. Accessing Arguments:
- Command-line arguments are passed to the `main` method as a string array (`String[] args`).
- Each argument is a string, and the arguments are separated by spaces when entered in the
command line.

15
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Syntax of `main` Method:


Code:
public static void main(String[] args) {
// args is an array of strings
}

2. Passing Arguments:
- When executing a Java program, arguments are passed after the class name.
- Example Command:

java MyProgram arg1 arg2 arg3

- `arg1`, `arg2`, and `arg3` are command-line arguments.

3. Reading Arguments:
- Use the array index to access individual arguments.
- The number of arguments can be determined using `args.length`.

Example Program

Code:
public class CommandLineExample {
public static void main(String[] args) {
// Check if arguments are provided
if (args.length == 0) {
System.out.println("No command-line arguments were passed.");
} else {
System.out.println("Command-line arguments are:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}

Steps to Run:
1. Compile the program:

16
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

javac CommandLineExample.java

2. Run the program with arguments:

java CommandLineExample Hello World 123


Output:

Command-line arguments are:


Argument 1: Hello
Argument 2: World
Argument 3: 123

Points to Remember
1. All Arguments Are Strings:
- Arguments are always passed as strings. You may need to convert them to the required data
types using parsing methods like `Integer.parseInt()`, `Double.parseDouble()`, etc.
- Example:
Code:
int num = Integer.parseInt(args[0]); // Converts first argument to an integer

2. Handling No Arguments:
- Always check if `args.length > 0` before accessing the arguments to avoid
`ArrayIndexOutOfBoundsException`.

3. Spaces in Arguments:
- To pass an argument containing spaces, enclose it in quotes.
- Example:

java MyProgram "Hello World"

4. Example Use Case:


- A simple calculator program:
Code:
public class Calculator {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: java Calculator <num1> <operator> <num2>");
return;

17
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

double num1 = Double.parseDouble(args[0]);


String operator = args[1];
double num2 = Double.parseDouble(args[2]);
double result = 0;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
System.out.println("Invalid operator!");
return;
}

System.out.println("Result: " + result);


}
}

Run:

java Calculator 10 + 20

Output:

Result: 30.0

18
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Strings:

In Java, a String is a sequence of characters. It is one of the most widely used data types
for text processing. Strings in Java are immutable, meaning their values cannot be changed once
created.
1. String Class
- The `String` class is part of the `java.lang` package.
- Strings are created as objects of the `String` class.

Example:

String str = "Hello, World!";


System.out.println(str);

2. Creating Strings
Strings can be created in two ways:

1. Using String Literals:


- Strings created with double quotes are stored in the String Constant Pool for memory
optimization.

String str1 = "Hello";


String str2 = "Hello"; // Points to the same object as str1

2. Using the `new` Keyword:


- Strings created with `new` are stored in the heap memory.

String str3 = new String("Hello"); // Creates a new object

3. Commonly Used Methods in the String Class

Method ​ ​ ​ ​ Description
`length()` ​ ​ ​ | Returns the length of the string.
`charAt(index)` ​ ​ ​ | Returns the character at the specified index.
`substring(beginIndex, endIndex)` ​ ​ | Extracts a substring from the string.
`equals(str)` ​ ​ ​ | Checks if two strings are equal (case-sensitive).

19
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

`equalsIgnoreCase(str)` ​​ ​ | Compares two strings, ignoring case differences.


`compareTo(str)` ​ ​ ​ | Compares two strings lexicographically.
`toLowerCase()` ​ ​ ​ | Converts all characters in the string to lowercase.
`toUpperCase()` ​ ​ ​ | Converts all characters in the string to uppercase.
`trim()` ​ ​ ​ | Removes leading and trailing whitespace.
`replace(oldChar, newChar)` ​ ​ | Replaces occurrences of a character in the string.
`contains(CharSequence)` ​ ​ | Checks if the string contains a specific sequence of
characters.
`startsWith(prefix)` ​ ​ ​ | Checks if the string starts with the specified prefix.
`endsWith(suffix)` ​ ​ ​ | Checks if the string ends with the specified suffix.
`split(regex)` ​ ​ ​ | Splits the string into an array of substrings based
on a regex.
`concat(str)` ​ ​ ​ | Concatenates the specified string to the end of the
current one.
`isEmpty()` ​ ​ ​ | Checks if the string is empty (`length() == 0`).

4. String Immutability
- Strings in Java are immutable, meaning any modification creates a new string object.
- Example:
String str = "Java";
str = str + " Programming"; // Creates a new string object
System.out.println(str); // Output: Java Programming

5. String Comparison
- Using `equals()`: Compares the content of two strings.
- Example:
String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1.equals(str2)); // true

- Using `==`: Compares the memory references.


- Example:
String str3 = new String("Hello");
System.out.println(str1 == str3); // false

- Using `compareTo()`: Compares strings lexicographically.

20
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

- Example:
String str4 = "Apple";
String str5 = "Banana";
System.out.println(str4.compareTo(str5)); // Negative value

6. String Operations

Concatenation
- Using `+` operator:
Ex:
String str1 = "Java";
String str2 = "Programming";
String result = str1 + " " + str2;
System.out.println(result); // Output: Java Programming

- Using `concat()` method:


Ex:
String result = str1.concat(" ").concat(str2);

Substring
Ex:
String str = "Hello, World!";
String sub = str.substring(7, 12);
System.out.println(sub); // Output: World

Splitting Strings
Ex:
String str = "Java,Python,C++";
String[] languages = str.split(",");
for (String lang : languages) {
System.out.println(lang);
}

Output:
Java
Python

21
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

C++

7. StringBuilder and StringBuffer


- StringBuilder and StringBuffer are mutable alternatives to `String`.
- They allow modifications (e.g., append, insert, delete) without creating new objects.

StringBuilder:
- Non-thread-safe but faster.
Ex:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World!");
System.out.println(sb.toString()); // Output: Hello World!

StringBuffer:
- Thread-safe but slower.
Ex:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World!");
System.out.println(sb.toString()); // Output: Hello World!

8. String Examples

Reverse a String
Ex:
String str = "Java";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: avaJ

Count Occurrences of a Character


Ex:
String str = "programming";
char target = 'm';
int count = 0;

for (char c : str.toCharArray()) {


if (c == target) count++;
}

System.out.println("Occurrences of 'm': " + count); // Output: 2

22
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

StringBuffer:

The `StringBuffer` class in Java is a mutable sequence of characters. Unlike `String`,


which is immutable, `StringBuffer` allows for the modification of strings without creating new
objects. It is thread-safe, meaning it is synchronized and can be safely used in multi-threaded
environments.

Key Features of StringBuffer


1. Mutability: The contents of a `StringBuffer` object can be modified after its creation.
2. Thread-Safe: Methods in `StringBuffer` are synchronized, making it suitable for use in
multi-threaded programs.
3. Performance: Slower than `StringBuilder` due to synchronization overhead but faster than
creating multiple `String` objects.

Creating a StringBuffer
1. Default Constructor: Creates an empty `StringBuffer` with a default capacity of 16
characters.
java
StringBuffer sb = new StringBuffer();

2. With Initial Capacity: Creates a `StringBuffer` with a specified capacity.


java
StringBuffer sb = new StringBuffer(50);

3. From a String: Creates a `StringBuffer` initialized with a given string.


java
StringBuffer sb = new StringBuffer("Hello");

Common Methods of StringBuffer

Method ​ ​ ​ Description
| `append(String)` ​ ​ | Appends the specified string to the end of the current
sequence.
| `insert(int offset, String)` ​ ​ | Inserts the specified string at the given offset.
| `replace(int start, int end, String)` ​ | Replaces characters in the specified range with a new
string.
| `delete(int start, int end)` ​ ​ | Deletes characters in the specified range.
|`deleteCharAt(int index)` ​ | Deletes the character at the specified index.

23
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

| `reverse()` ​ ​ | Reverses the sequence of characters.


| `length()` ​ ​ | Returns the current length of the sequence.
| `capacity()` ​ ​ | Returns the current capacity of the buffer.
| `ensureCapacity
(int minimumCapacity)` ​ ​ | Ensures the capacity is at least the specified minimum.
| `setLength(int newLength)` ​ | Sets the length of the sequence (truncates or pads as
needed).
| `charAt(int index)` ​ ​ | Returns the character at the specified index.
| `substring(int start, int end)` ​ | Returns a substring of the sequence.

Examples:

Appending Strings
Ex:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World

Inserting Characters
Ex:
StringBuffer sb = new StringBuffer("Java");
sb.insert(4, " Programming");
System.out.println(sb); // Output: Java Programming

Replacing a Substring
Ex:
StringBuffer sb = new StringBuffer("I like Java");
sb.replace(7, 11, "Python");
System.out.println(sb); // Output: I like Python

Deleting Characters
Ex:
StringBuffer sb = new StringBuffer("Hello World!");
sb.delete(5, 11);
System.out.println(sb); // Output: Hello!

24
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Reversing the String


Ex:
StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
Output: avaJ

Capacity Management
Ex:
StringBuffer sb = new StringBuffer();
System.out.println("Initial Capacity: " + sb.capacity()); // Output: 16

sb.append("Hello");
System.out.println("Capacity after append: " + sb.capacity()); // Output: 16

sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity: " + sb.capacity()); // Output: 50

Getting Substring
Ex:
StringBuffer sb = new StringBuffer("Programming");
String sub = sb.substring(0, 7);
System.out.println(sub); // Output: Program

Simple Java Program:

Here’s a simple Java program to demonstrate the basics

Example: Hello, World!

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

How It Works:
1. Class Declaration:

25
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

- `public class HelloWorld` declares the class. The class name must match the file name
(`HelloWorld.java`).

2. Main Method:
- The entry point of the program is the `main` method:
Ex:
public static void main(String[] args)

- `public`: Accessible from anywhere.


- `static`: No need to create an object to invoke the method.
- `void`: The method does not return any value.
- `String[] args`: Used to accept command-line arguments.

3. Printing to Console:
- `System.out.println("Hello, World!");` prints the message to the console.

Steps to Run the Program

1. Save the Code:


Save the program in a file named `HelloWorld.java`.

2. Compile the Program:


Open a terminal or command prompt, navigate to the file's location, and run:

javac HelloWorld.java

3. Run the Program:


Execute the compiled program:

java HelloWorld

4. Output:

Hello, World!

Example Programs:

Addition of Two Numbers

26
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Ex:
import java.util.Scanner;

public class AddNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = scanner.nextInt();

System.out.print("Enter second number: ");


int num2 = scanner.nextInt();

int sum = num1 + num2;


System.out.println("The sum is: " + sum);

scanner.close();
}
}

Check Even or Odd


Ex:
import java.util.Scanner;

public class EvenOdd {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = scanner.nextInt();

if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}

scanner.close();
}
}

27
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Find the Factorial of a Number


Ex:
import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = scanner.nextInt();

int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}

System.out.println("The factorial of " + num + " is " + factorial);

scanner.close();
}
}

Enumerators:
In Java, an enum (short for enumerator) is a special data type that represents a collection
of constants. It is often used when a variable can only take a predefined set of values, such as
days of the week, directions, or states.

Key Features of Enums:


1. Constants Only: Enums are primarily used to define a fixed set of constants.
2. Type-Safe: Enums provide compile-time type safety, ensuring that invalid values cannot be
assigned.
3. Methods and Fields: Enums can have fields, methods, and constructors.
4. Switch Compatibility: Enums work seamlessly with `switch` statements.

Defining an Enum
Enums are defined using the `enum` keyword.

Syntax:

28
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}

Basic Example: Days of the Week

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

public class EnumExample {


public static void main(String[] args) {
Day today = Day.FRIDAY;
System.out.println("Today is: " + today);

// Loop through all enum constants


System.out.println("Days of the week:");
for (Day day : Day.values()) {
System.out.println(day);
}
}
}

Output:

Today is: FRIDAY


Days of the week:
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

29
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Using Enums in Switch Statements

enum TrafficLight {
RED, YELLOW, GREEN;
}

public class TrafficLightExample {


public static void main(String[] args) {
TrafficLight signal = TrafficLight.RED;

switch (signal) {
case RED:
System.out.println("Stop!");
break;
case YELLOW:
System.out.println("Get Ready!");
break;
case GREEN:
System.out.println("Go!");
break;
}
}
}

Output:

Stop!

Enums with Fields and Methods


Enums can have fields, constructors, and methods, making them more powerful.

Example: Enum with Additional Information

enum Planet {
MERCURY(3.3011e23, 2.4397e6),
VENUS(4.8675e24, 6.0518e6),
EARTH(5.9723e24, 6.371e6),
MARS(6.4171e23, 3.3895e6);

private double mass; // in kilograms

30
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

private double radius; // in meters

// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}

// Method to calculate surface gravity


public double surfaceGravity() {
double G = 6.67430e-11; // Gravitational constant
return G * mass / (radius * radius);
}

public double getMass() {


return mass;
}

public double getRadius() {


return radius;
}
}

public class PlanetExample {


public static void main(String[] args) {
for (Planet planet : Planet.values()) {
System.out.println("Planet: " + planet);
System.out.println("Mass: " + planet.getMass() + " kg");
System.out.println("Radius: " + planet.getRadius() + " m");
System.out.println("Surface Gravity: " + planet.surfaceGravity() + " m/s²");
System.out.println();
}
}
}

Points to Remember
1. Enum Values:
- Use `EnumName.values()` to get an array of all enum constants.
- Use `EnumName.valueOf("CONSTANT")` to convert a string to its corresponding enum
constant.

31
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

2. Comparison:
- Enums can be compared using `==` because each constant is a singleton.
- Example:

if (Day.MONDAY == Day.MONDAY) {
System.out.println("Equal");
}

3. Custom Methods:
- You can define custom methods for enums, but all constants must implement the methods if
the enum is abstract.

4. Constructors in Enums:
- Enum constructors are implicitly `private`. You cannot create new instances of an enum.

Arrays:
An array in Java is a data structure that stores a fixed-size sequence of elements of the
same type. Arrays are used to store multiple values in a single variable, rather than declaring
separate variables for each value.

Key Characteristics of Arrays in Java:


1. Fixed Size: Once an array is created, its size cannot be changed.
2. Homogeneous: All elements in an array must be of the same data type (e.g., all `int`, all
`String`).
3. Indexed Access: Each element in an array is accessed by an index, starting from `0` to `n-1`
(where `n` is the length of the array).

Creating an Array:

There are two common ways to declare and initialize arrays in Java:

1. Array Declaration and Initialization:


java
int[] arr = new int[5]; // Declares an array of 5 integers

2. Array Declaration with Values:

32
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

java
int[] arr = {1, 2, 3, 4, 5}; // Declares and initializes an array with values

Accessing Array Elements:

Array elements are accessed using their index.

int[] arr = {10, 20, 30, 40, 50};


System.out.println(arr[0]); // Output: 10 (First element)
System.out.println(arr[4]); // Output: 50 (Last element)

Array Operations:

1. Length of an Array
The length of an array is given by the `length` property.

Ex:
int[] arr = {10, 20, 30};
System.out.println(arr.length); // Output: 3

2. Looping Through an Array

- Using a for loop:


Ex:
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]); // Output: 1, 2, 3, 4, 5
}

- Using an enhanced for loop (for-each loop):


Ex:
for (int num : arr) {
System.out.println(num); // Output: 1, 2, 3, 4, 5
}

3. Modifying Array Elements


You can modify an element in the array using its index.
Ex:

33
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

arr[1] = 50; // Changes the second element (index 1) to 50


System.out.println(arr[1]); // Output: 50

Multi-Dimensional Arrays
Java supports arrays with more than one dimension (i.e., matrices or tables).

Two-Dimensional Array:
A two-dimensional array is an array of arrays, often referred to as a matrix.

Ex:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing elements
System.out.println(matrix[0][0]); // Output: 1
System.out.println(matrix[2][2]); // Output: 9

Example: Looping through a 2D array


Ex:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

34
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Output:

123
456
789

Array Manipulation:

Copying Arrays:
- Using `System.arraycopy()`
java
int[] source = {1, 2, 3};
int[] destination = new int[3];
System.arraycopy(source, 0, destination, 0, 3);

- Using `Arrays.copyOf()` (from `java.util.Arrays` package):


java
int[] arr = {1, 2, 3};
int[] newArr = Arrays.copyOf(arr, 5); // Copy and resize the array
System.out.println(Arrays.toString(newArr)); // Output: [1, 2, 3, 0, 0]

Sorting Arrays:
- Using `Arrays.sort()` (from `java.util.Arrays` package):
java
int[] arr = {5, 3, 8, 1, 2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // Output: [1, 2, 3, 5, 8]

Jagged Arrays (Array of Arrays)


A jagged array is an array of arrays where each "sub-array" can have a different length.

Ex:
int[][] jaggedArr = new int[3][];
jaggedArr[0] = new int[2]; // First row with 2 elements
jaggedArr[1] = new int[3]; // Second row with 3 elements

35
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

jaggedArr[2] = new int[1]; // Third row with 1 element

jaggedArr[0][0] = 1;
jaggedArr[0][1] = 2;
jaggedArr[1][0] = 3;
jaggedArr[1][1] = 4;
jaggedArr[1][2] = 5;
jaggedArr[2][0] = 6;

for (int i = 0; i < jaggedArr.length; i++) {


for (int j = 0; j < jaggedArr[i].length; j++) {
System.out.print(jaggedArr[i][j] + " ");
}
System.out.println();
}

Output:

12
345
6

Common Array Operations:


1. Reversing an Array
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
System.out.println(Arrays.toString(arr)); // Output: [5, 4, 3, 2, 1]

2. Finding the Maximum/Minimum Value in an Array


int[] arr = {12, 4, 5, 7, 2};
int max = arr[0];
int min = arr[0];

for (int i = 1; i < arr.length; i++) {


if (arr[i] > max) {

36
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
System.out.println("Max: " + max); // Output: Max: 12
System.out.println("Min: " + min); // Output: Min: 2
Array of Objects
You can also create arrays that store objects of a class.

Ex:
class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}
}

public class ArrayOfObjects {


public static void main(String[] args) {
Person[] people = new Person[2];
people[0] = new Person("John", 25);
people[1] = new Person("Alice", 30);

for (Person p : people) {


System.out.println("Name: " + p.name + ", Age: " + p.age);
}
}
}

Output:

Name: John, Age: 25


Name: Alice, Age: 30

37
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Formatting Output:

In Java, you can format output to control how text and numbers are displayed in the
console. This is useful for aligning data, displaying numbers with a fixed number of decimal
places, or formatting strings in a certain way.

Java provides several ways to format output, including `System.out.printf()`, `String.format()`,


and the `Formatter` class.

1. Using `System.out.printf()`

The `printf()` method provides a way to format output similarly to the `printf` function in C. You
can specify format specifiers to define the structure of the output.

Syntax:
Ex:
System.out.printf(formatString, arguments);

- `formatString`: A string that contains format specifiers, such as `%d`, `%f`, `%s`, etc.
- `arguments`: Values to be formatted and displayed.

Common Format Specifiers

Specifier ​ ​ Description ​​ Example


`%d` ​ Integer (decimal) `System.out.printf("%d", 123);`
`%f` ​ Floating-point number `System.out.printf("%f", 3.14159);`
`%s` ​ String ​ `System.out.printf("%s", "Hello");`
`%x` ​ Integer in hexadecimal `System.out.printf("%x", 255);`
`%c` ​ Character ​ `System.out.printf("%c", 'A');`
`%e` ​ Scientific notation for
floating point numbers ​ `System.out.printf("%e", 12345.6789);`

Example 1: Formatting Integers

public class FormatExample {


public static void main(String[] args) {
int num1 = 150;

38
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

int num2 = 250;

// Using %d to print integers


System.out.printf("First number: %d\n", num1);
System.out.printf("Second number: %d\n", num2);
}
}

Output:

First number: 150


Second number: 250

Example 2: Formatting Floating-Point Numbers

public class FormatExample {


public static void main(String[] args) {
double pi = 3.14159265359;

// Using %f to print floating-point numbers


System.out.printf("Pi: %.2f\n", pi); // Prints only 2 decimal places
System.out.printf("Pi: %.4f\n", pi); // Prints 4 decimal places
}
}

Output:

Pi: 3.14
Pi: 3.1416

Example 3: Formatting Strings

public class FormatExample {


public static void main(String[] args) {
String name = "Alice";

// Using %s to print strings

39
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

System.out.printf("Name: %s\n", name);


}
}

Output:

Name: Alice
2. Using `String.format()`

The `String.format()` method works similarly to `printf()` but returns the formatted string instead
of printing it directly.

Syntax:

String formattedString = String.format(formatString, arguments);

Example:

public class FormatExample {


public static void main(String[] args) {
double pi = 3.14159;

// Using String.format() to format the string


String formatted = String.format("Pi value is: %.2f", pi);
System.out.println(formatted);
}
}

Output:

Pi value is: 3.14

3. Using `Formatter` Class

The `Formatter` class provides more control over formatting output. It works similarly to
`printf()` but allows you to write formatted output to various destinations like files or strings.

40
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Example:

import java.util.Formatter;

public class FormatExample {


public static void main(String[] args) {
Formatter formatter = new Formatter();

int number = 42;


String text = "Hello, World!";

// Formatting output using Formatter


formatter.format("Number: %d\n", number);
formatter.format("Text: %s\n", text);

// Print the formatted output


System.out.println(formatter);

// Close the formatter


formatter.close();
}
}

Output:

Number: 42
Text: Hello, World!

4. Formatting with Width, Precision, and Alignment

You can specify the width and precision of numbers and strings.

Width:
The width specifier ensures that the output occupies a certain number of characters.

- Example:

41
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

System.out.printf("|%10d|\n", 123); // Output: "| 123|"

Precision (for Floating-Point Numbers):


You can control the number of digits after the decimal point.

- Example:

System.out.printf("%.3f\n", 3.14159); // Output: "3.142"

Alignment:
By default, numbers are right-aligned and strings are left-aligned. You can change this by using
the `-` sign.

- Right-alignment (default for numbers):

System.out.printf("|%10d|\n", 123); // Output: "| 123|"

- Left-alignment (for strings):

System.out.printf("|%-10s|\n", "Java"); // Output: "|Java |"

Example 4: Combining Width, Precision, and Alignment

public class FormatExample {


public static void main(String[] args) {
double price = 19.99;
String item = "Java Book";

// Formatting with width, precision, and alignment


System.out.printf("|%-15s|%10.2f|\n", item, price);
}
}

Output:

42
CS1209 ​ ​ ​ ​ OBJECT-ORIENTED JAVA PROGRAMMING

Java Book 19.99

5. Using `DecimalFormat` for Number Formatting


Java provides the `DecimalFormat` class for more advanced control over number formatting.

Example:

import java.text.DecimalFormat;

public class FormatExample {


public static void main(String[] args) {
double value = 1234567.89;

// Creating a DecimalFormat instance


DecimalFormat formatter = new DecimalFormat("#,.");

// Formatting the number


String formattedValue = formatter.format(value);
System.out.println(formattedValue); // Output: 1,234,567.89
}
}

Summary of Formatting Output Techniques:


1. `printf()`: Used for formatting and printing directly to the console.
2. `String.format()`: Used for creating formatted strings.
3. `Formatter` class: Provides more flexibility and control over formatted output.
4. `DecimalFormat`: Used for advanced number formatting.

43

You might also like