Unit I OOJP
Unit I OOJP
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:
- 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.
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:
2
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
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
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.
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`.
mkdir MyJavaProject
cd MyJavaProject
javac HelloWorld.java
java HelloWorld
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.
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
Data Types:
Data types specify the type of data that variables can hold. They are broadly classified into two
categories:
- Character Type:
- `char` (2 bytes): Stores a single Unicode character (e.g., `'A'`, `'@'`).
- Boolean Type:
- `boolean` (1 bit): Stores `true` or `false`.
7
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
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
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
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
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
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);
}
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);
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");
}
a) Looping Statements
1. for Loop:
Syntax:
for (initialization; condition; update) {
// Code to execute
}
Example:
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;
}
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.
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
2. Passing Arguments:
- When executing a Java program, arguments are passed after the class name.
- Example Command:
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
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:
17
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
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;
}
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:
2. Creating Strings
Strings can be created in two ways:
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
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
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
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++
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
22
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
StringBuffer:
Creating a StringBuffer
1. Default Constructor: Creates an empty `StringBuffer` with a default capacity of 16
characters.
java
StringBuffer sb = new 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
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
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
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)
3. Printing to Console:
- `System.out.println("Hello, World!");` prints the message to the console.
javac HelloWorld.java
java HelloWorld
4. Output:
Hello, World!
Example Programs:
26
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
Ex:
import java.util.Scanner;
scanner.close();
}
}
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
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
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.
Defining an Enum
Enums are defined using the `enum` keyword.
Syntax:
28
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
Output:
29
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
enum TrafficLight {
RED, YELLOW, GREEN;
}
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!
enum Planet {
MERCURY(3.3011e23, 2.4397e6),
VENUS(4.8675e24, 6.0518e6),
EARTH(5.9723e24, 6.371e6),
MARS(6.4171e23, 3.3895e6);
30
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
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.
Creating an Array:
There are two common ways to declare and initialize arrays in Java:
32
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
java
int[] arr = {1, 2, 3, 4, 5}; // Declares and initializes an array with values
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
33
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
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
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);
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]
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[0][0] = 1;
jaggedArr[0][1] = 2;
jaggedArr[1][0] = 3;
jaggedArr[1][1] = 4;
jaggedArr[1][2] = 5;
jaggedArr[2][0] = 6;
Output:
12
345
6
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;
Output:
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.
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.
38
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
Output:
Output:
Pi: 3.14
Pi: 3.1416
39
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
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:
Example:
Output:
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;
Output:
Number: 42
Text: Hello, World!
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
- Example:
Alignment:
By default, numbers are right-aligned and strings are left-aligned. You can change this by using
the `-` sign.
Output:
42
CS1209 OBJECT-ORIENTED JAVA PROGRAMMING
Example:
import java.text.DecimalFormat;
43