Java
Programming
Chapter 3
StringBuilder
• StringBuilder is used for building and manipulating strings efficiently when performing a lot of
changes to the string, as it is mutable (can be modified) while String is immutable (cannot be
changed once created).
• StringBuilder avoids creating new string objects in each loop iteration, unlike the String
concatenation approach which creates a new string object every time.
• Type of methods which included:
append(), insert(), replace(), delete(), reverse() , etc.
StringBuilder: append
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
// Append text
[Link](" World!");
[Link](" How are you?");
[Link](sb);
}}
StringBuilder: insert()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java Programming");
// Insert text at index 4
[Link](4, " is fun");
[Link](sb);
}}
StringBuilder: delete()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java is awesome!");
// Remove text from index 4 to 6 (exclusive)
[Link](4, 7);
[Link](sb);
}
}
StringBuilder: replace()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java is fun!");
[Link](8, 11, "awesome");
[Link](sb);
}}
StringBuilder: reverse()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
// Reverse the string
[Link]();
[Link](sb); // Output: dlroW olleH
}
}
Example: Find the Longest Word
public class LongestWord {
public static void main(String[] args) {
String text = "Java is an amazing programming language!";
String[] words = [Link]("[^a-zA-Z ]", "").split(" ");
String longest = "";
for (String word : words) {
if ([Link]() > [Link]()) longest = word;
}
[Link](longest);
}}
Example: Count Occurrences of a Word
public class CountWordOccurrences {
public static void main(String[] args) {
String text = "Java is fun and Java is powerful. Java is everywhere!";
String wordToFind = "Java";
int count = 0;
// Split the sentence into words
String[] words = [Link]().split("\\s+");
// Count occurrences of the specific word
for (String word : words) {
if ([Link]([Link]())) {
count++;
}}
[Link]("The word '" + wordToFind + "' appears " + count + " times.");
}}
Example: Check if a Sentence Contains a Specific Word
public class CheckWordExistence {
public static void main(String[] args) {
String text = "Java is fun and powerful!";
String wordToFind = "fun";
// Convert the sentence to lowercase and check if the word exists
if ([Link]().contains([Link]())) {
[Link]("The word '" + wordToFind + "' exists in the sentence.");
} else {
[Link]("The word '" + wordToFind + "' does not exist in the
sentence.");
} }}
Example: Currency Converter
public class CurrencyConverter { if ([Link]("EUR")) {
public static void main(String[] args) { convertedAmount = amountInUsd * usdToEur;
} else if ([Link]("GBP")) {
double usdToEur = 0.85; // 1 USD = 0.85 EUR convertedAmount = amountInUsd * usdToGbp;
double usdToGbp = 0.75; // 1 USD = 0.75 GBP } else if ([Link]("INR")) {
convertedAmount = amountInUsd * usdToInr;
double usdToInr = 74.50; // 1 USD = 74.50 INR } else {
double amountInUsd = 100; // Amount in USD [Link]("Invalid currency!");
return;
String targetCurrency = "INR"; // Target currency (hardcoded)
}
// Convert based on target currency // Display the result
double convertedAmount = 0; [Link]("Converted Amount: %.2f USD = %.2f
%s\n", amountInUsd, convertedAmount, targetCurrency);
}}
Example: Simple Search Engine
public class SimpleSearchEngine { // Search through the database
public static void main(String[] args) { boolean found = false;
for (int i = 0; i < [Link]; i++) {
String[] database = { if (database[i].contains(query)) {
"The quick brown fox jumps over the lazy dog", [Link]("Found match in: " + database[i]);
found = true;
"Java programming is fun and powerful", }}
"Artificial Intelligence is changing the world", // If no match is found
if (!found) {
"Search engines help you find information online",
[Link]("No results found for the query: " +
"Java is used for web and mobile applications" query);
}; } }}
String query = "Java";
Simple Billing System
import [Link]; double total = price * quantity;
double tax = total * 0.05; // 5% tax
public class SimpleBillingSystem {
double grandTotal = total + tax;
public static void main(String[] args) { [Link]("\n------ BILL ------");
Scanner scanner = new Scanner([Link]); [Link]("Item: " + item);
[Link]("Price: $" + price);
[Link]("Enter item name: "); [Link]("Quantity: " + quantity);
String item = [Link](); [Link]("Total: $" + total);
[Link]("Tax (5%): $" + tax);
[Link]("Enter price of " + item + ": $"); [Link]("Grand Total: $" + grandTotal);
double price = [Link](); [Link]();
}}
[Link]("Enter quantity of " + item + ": ");
int quantity = [Link]();
Java If ... Else
Java If ... Else
• Java Conditions and If Statements:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
Java If ... Else
• Java has the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed
Java If ... Else
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}
}
}
Java If ... Else
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}
}
}
else if Statement
• Use the else if statement to specify a new condition if the first
condition is false.
• Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
else if Statement
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
[Link]("Good morning.");
} else if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}
}
}
Real-Life Example
public class Main {
public static void main(String[] args) {
int doorCode = 1337;
if (doorCode == 1337) {
[Link]("Correct code. The door is now open.");
} else {
[Link]("Wrong code. The door remains closed.");
}
}
}
Real-Life Example
public class Main {
public static void main(String[] args) {
int myNum = -10; // Is this a positive or negative number?
if (myNum > 0) {
[Link]("The value is a positive number.");
} else if (myNum < 0) {
[Link]("The value is a negative number.");
} else {
[Link]("The value is 0.");
}
}
}
Student Grading System
import [Link]; } else if (marks >= 60) {
public class StudentGradingSystem { grade = "C";
public static void main(String[] args) { } else if (marks >= 50) {
Scanner scanner = new Scanner([Link]); grade = "D";
} else {
[Link]("Enter the marks obtained by the student: ");
grade = "F";
double marks = [Link](); }
String grade = ""; [Link]("Grade: " + grade);
if (marks >= 90) { [Link]();
grade = "A+"; }
} else if (marks >= 80) { }
grade = "A";
} else if (marks >= 70) {
grade = "B";
Age Categorization Program
import [Link]; } else if (age >= 20 && age <= 64) {
public class AgeCategorization { [Link]("You are an Adult.");
} else if (age >= 65) {
public static void main(String[] args) { [Link]("You are a Senior.");
Scanner scanner = new Scanner([Link]); } else {
[Link]("Enter your age: "); [Link]("Invalid age entered.");
}
int age = [Link](); [Link]();
if (age >= 0 && age <= 12) { }}
[Link]("You are a Child.");
} else if (age >= 13 && age <= 19) {
[Link]("You are a Teenager.");
Basic Calculator Program
import [Link]; [Link]("Addition: " + sum);
public class BasicCalculator { [Link]("Subtraction: " + difference);
public static void main(String[] args) { [Link]("Multiplication: " + product);
[Link]("Division: " + quotient);
Scanner scanner = new Scanner([Link]); [Link]();
[Link]("Enter the first number: "); }}
double num1 = [Link]();
[Link]("Enter the second number: ");
double num2 = [Link]();
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;
Simple ChatBot Program
import [Link];
public class SimpleChatBot {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Hello! I am your chatbot. Type 'bye' to exit.");
[Link]("You: ");
String userInput = [Link]();
if ([Link]("hi") || [Link]("hello")) {
[Link]("ChatBot: Hello! How can I assist you?");
} else if ([Link]("bye")) {
[Link]("ChatBot: Goodbye!");
} else {
[Link]("ChatBot: Sorry, I don't understand that.");
}
[Link]();
}}