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
sb.append(" World!");
sb.append(" How are you?");
System.out.println(sb);
}}
StringBuilder: insert()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java Programming");
// Insert text at index 4
sb.insert(4, " is fun");
System.out.println(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)
sb.delete(4, 7);
System.out.println(sb);
}
}
StringBuilder: replace()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java is fun!");
sb.replace(8, 11, "awesome");
System.out.println(sb);
}}
StringBuilder: reverse()
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
// Reverse the string
sb.reverse();
System.out.println(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 = text.replaceAll("[^a-zA-Z ]", "").split(" ");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) longest = word;
}
System.out.println(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 = text.toLowerCase().split("\\s+");
// Count occurrences of the specific word
for (String word : words) {
if (word.equals(wordToFind.toLowerCase())) {
count++;
}}
System.out.println("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 (text.toLowerCase().contains(wordToFind.toLowerCase())) {
System.out.println("The word '" + wordToFind + "' exists in the sentence.");
} else {
System.out.println("The word '" + wordToFind + "' does not exist in the
sentence.");
} }}
Example: Currency Converter
public class CurrencyConverter { if (targetCurrency.equals("EUR")) {
public static void main(String[] args) { convertedAmount = amountInUsd * usdToEur;
} else if (targetCurrency.equals("GBP")) {
double usdToEur = 0.85; // 1 USD = 0.85 EUR convertedAmount = amountInUsd * usdToGbp;
double usdToGbp = 0.75; // 1 USD = 0.75 GBP } else if (targetCurrency.equals("INR")) {
convertedAmount = amountInUsd * usdToInr;
double usdToInr = 74.50; // 1 USD = 74.50 INR } else {
double amountInUsd = 100; // Amount in USD System.out.println("Invalid currency!");
return;
String targetCurrency = "INR"; // Target currency (hardcoded)
}
// Convert based on target currency // Display the result
double convertedAmount = 0; System.out.printf("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 < database.length; i++) {
String[] database = { if (database[i].contains(query)) {
"The quick brown fox jumps over the lazy dog", System.out.println("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",
System.out.println("No results found for the query: " +
"Java is used for web and mobile applications" query);
}; } }}
String query = "Java";
Simple Billing System
import java.util.Scanner; double total = price * quantity;
double tax = total * 0.05; // 5% tax
public class SimpleBillingSystem {
double grandTotal = total + tax;
public static void main(String[] args) { System.out.println("\n------ BILL ------");
Scanner scanner = new Scanner(System.in); System.out.println("Item: " + item);
System.out.println("Price: $" + price);
System.out.print("Enter item name: "); System.out.println("Quantity: " + quantity);
String item = scanner.nextLine(); System.out.println("Total: $" + total);
System.out.println("Tax (5%): $" + tax);
System.out.print("Enter price of " + item + ": $"); System.out.println("Grand Total: $" + grandTotal);
double price = scanner.nextDouble(); scanner.close();
}}
System.out.print("Enter quantity of " + item + ": ");
int quantity = scanner.nextInt();
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) {
System.out.println("x is greater than y");
}
}
}
Java If ... Else
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("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) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Real-Life Example
public class Main {
public static void main(String[] args) {
int doorCode = 1337;
if (doorCode == 1337) {
System.out.println("Correct code. The door is now open.");
} else {
System.out.println("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) {
System.out.println("The value is a positive number.");
} else if (myNum < 0) {
System.out.println("The value is a negative number.");
} else {
System.out.println("The value is 0.");
}
}
}
Student Grading System
import java.util.Scanner; } else if (marks >= 60) {
public class StudentGradingSystem { grade = "C";
public static void main(String[] args) { } else if (marks >= 50) {
Scanner scanner = new Scanner(System.in); grade = "D";
} else {
System.out.print("Enter the marks obtained by the student: ");
grade = "F";
double marks = scanner.nextDouble(); }
String grade = ""; System.out.println("Grade: " + grade);
if (marks >= 90) { scanner.close();
grade = "A+"; }
} else if (marks >= 80) { }
grade = "A";
} else if (marks >= 70) {
grade = "B";
Age Categorization Program
import java.util.Scanner; } else if (age >= 20 && age <= 64) {
public class AgeCategorization { System.out.println("You are an Adult.");
} else if (age >= 65) {
public static void main(String[] args) { System.out.println("You are a Senior.");
Scanner scanner = new Scanner(System.in); } else {
System.out.print("Enter your age: "); System.out.println("Invalid age entered.");
}
int age = scanner.nextInt(); scanner.close();
if (age >= 0 && age <= 12) { }}
System.out.println("You are a Child.");
} else if (age >= 13 && age <= 19) {
System.out.println("You are a Teenager.");
Basic Calculator Program
import java.util.Scanner; System.out.println("Addition: " + sum);
public class BasicCalculator { System.out.println("Subtraction: " + difference);
public static void main(String[] args) { System.out.println("Multiplication: " + product);
System.out.println("Division: " + quotient);
Scanner scanner = new Scanner(System.in); scanner.close();
System.out.print("Enter the first number: "); }}
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;
Simple ChatBot Program
import java.util.Scanner;
public class SimpleChatBot {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hello! I am your chatbot. Type 'bye' to exit.");
System.out.print("You: ");
String userInput = scanner.nextLine();
if (userInput.equalsIgnoreCase("hi") || userInput.equalsIgnoreCase("hello")) {
System.out.println("ChatBot: Hello! How can I assist you?");
} else if (userInput.equalsIgnoreCase("bye")) {
System.out.println("ChatBot: Goodbye!");
} else {
System.out.println("ChatBot: Sorry, I don't understand that.");
}
scanner.close();
}}