Java Programming Day 3

Day 3: Exploring Strings, Conditionals, and Practical Java Programs
Today, I dove deeper into Java by exploring string manipulation methods, nested conditions, user input parsing, and creating small practical utilities. These exercises helped me strengthen my understanding of core Java features and build interactive console programs.
1. String Methods and Validation — StringMethodDemo
javaCopyEdit// Program demonstrating useful String methods and validations in Java
public class StringMethodDemo {
public static void main(String[] args) {
// Initialize sample strings
String name = "Penelope Eckart";
String name2 = "REYNOLD ECKART";
String name3 = " Callisto Regulus ";
String name4 = "Berry";
// Using String methods to manipulate and get info
int length = name.length();
char letter = name.charAt(7);
int index = name.indexOf("e");
int lastIndex = name.lastIndexOf("e");
// Changing case, trimming spaces, replacing characters
name = name.toUpperCase();
name2 = name2.toLowerCase();
name3 = name3.trim();
name4 = name4.replace("e", "/");
// Print results of string operations
System.out.println("Length of original name: " + length);
System.out.println("Character at index 7: " + letter);
System.out.println("First index of 'e': " + index);
System.out.println("Last index of 'e': " + lastIndex);
System.out.println("Name in uppercase: " + name);
System.out.println("Name2 in lowercase: " + name2);
System.out.println("Trimmed name3: '" + name3 + "'");
System.out.println("Modified name4: " + name4);
// Check if the string is empty or contains spaces
System.out.println("Is name empty? " + name.isEmpty());
if (name.isEmpty()) {
System.out.println("Your name is empty.");
} else {
System.out.println("Hello " + name);
}
if (name.contains(" ")) {
System.out.println("Yes, there is whitespace in your name.");
} else {
System.out.println("Your name doesn't contain any whitespace.");
}
// Check if name equals "password"
if (name.equals("password")) {
System.out.println("Your name can't be 'password'.");
} else {
System.out.println("Hello again, " + name);
}
}
}
What I learned:
This program introduced me to many useful String methods like .length()
, .charAt()
, .indexOf()
, .lastIndexOf()
, .toUpperCase()
, .toLowerCase()
, .trim()
, and .replace()
. These methods help manipulate text in Java, which is crucial for tasks like validating user inputs or processing data. The program also checks for empty strings and whitespace, showing how to apply basic validations.
2. Nested If-Else: Movie Ticket Discount Calculator — TicketDiscountCalculator
javaCopyEdit// Program using nested if-else to calculate ticket discounts
public class TicketDiscountCalculator {
public static void main(String[] args) {
boolean isStudent = true;
boolean isSenior = true;
double price = 9.99;
System.out.println("Welcome to the Movie Ticket Discount Calculator!");
if (isStudent) {
if (isSenior) {
System.out.println("Eligible for senior discount: 20%");
System.out.println("Eligible for student discount: 10%");
price *= 0.7; // Combined 30% discount
} else {
System.out.println("Eligible for student discount: 10%");
price *= 0.9;
}
} else {
if (isSenior) {
System.out.println("Eligible for senior discount: 20%");
price *= 0.8;
} else {
System.out.println("Not eligible for any discounts.");
}
}
System.out.printf("Final ticket price: $%.2f%n", price);
}
}
What I learned:
This exercise helped me understand how to use nested if-else statements to handle complex logic with multiple conditions. It also showed how to apply discounts sequentially and display formatted output using printf
.
3. Email Parsing with Substring — EmailParser
javaCopyEditimport java.util.Scanner;
// Program to extract username and domain from an email
public class EmailParser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your email: ");
String email = scanner.nextLine();
if (email.contains("@")) {
String username = email.substring(0, email.indexOf("@"));
String domain = email.substring(email.indexOf("@") + 1);
System.out.println("Username: " + username);
System.out.println("Domain: " + domain);
} else {
System.out.println("Email must contain '@'");
}
scanner.close();
}
}
What I learned:
This program shows how to use .substring()
and .indexOf()
to split a string at a specific character (@
), a common need when working with email addresses or URLs.
4. Weight Conversion Utility — WeightConverter
javaCopyEditimport java.util.Scanner;
// Program to convert weights between pounds and kilograms
public class WeightConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Weight Conversion Program!");
System.out.println("1: Convert lbs to kgs");
System.out.println("2: Convert kgs to lbs");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
double weight;
double convertedWeight;
if (choice == 1) {
System.out.print("Enter the weight in lbs: ");
weight = scanner.nextDouble();
convertedWeight = weight * 0.453592;
System.out.printf("The weight in kilograms is: %.2f kg%n", convertedWeight);
} else if (choice == 2) {
System.out.print("Enter the weight in kgs: ");
weight = scanner.nextDouble();
convertedWeight = weight * 2.20462;
System.out.printf("The weight in pounds is: %.2f lbs%n", convertedWeight);
} else {
System.out.println("Invalid choice.");
}
scanner.close();
}
}
What I learned:
I practiced handling user input with Scanner and used conditional logic to perform unit conversions. I also used printf
for nicely formatted output.
5. Ternary Operator Examples — TernaryDemo
javaCopyEditimport java.util.Scanner;
// Program to demonstrate ternary operators for concise conditions
public class TernaryDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your score: ");
double score = scanner.nextDouble();
String passOrFail = (score >= 60) ? "PASS" : "FAIL";
System.out.println(passOrFail);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
String evenOrOdd = (number % 2 == 0) ? "EVEN" : "ODD";
System.out.println(evenOrOdd);
scanner.close();
}
}
What I learned:
This program helped me understand how to use the ternary operator to replace simple if-else statements and write shorter, cleaner code.
6. Temperature Converter with Ternary — TemperatureConverter
javaCopyEditimport java.util.Scanner;
// Program to convert temperatures between Fahrenheit and Celsius
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the temperature: ");
double temp = scanner.nextDouble();
System.out.print("Convert to Celsius or Fahrenheit? (C or F): ");
String unit = scanner.next().toUpperCase();
double convertedTemp = (unit.equals("C")) ? (temp - 32) * 5 / 9 : (temp * 9 / 5) + 32;
System.out.printf("Converted temperature: %.1f%n", convertedTemp);
scanner.close();
}
}
What I learned:
I practiced working with user input and string comparison, and applied the ternary operator to choose conversion logic dynamically.
7. Day of the Week Switch Case — DayChecker
javaCopyEditimport java.util.Scanner;
// Program using enhanced switch to identify weekdays and weekends
public class DayChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the day: ");
String day = scanner.nextLine();
switch(day) {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ->
System.out.println("It is a weekday.");
case "Saturday", "Sunday" ->
System.out.println("It is the weekend!");
default ->
System.out.println(day + " is not a valid day.");
}
scanner.close();
}
}
What I learned:
This program demonstrated the enhanced switch statement in Java, allowing cleaner syntax for multiple case matches.
8. Simple Calculator with Switch — Calculator
javaCopyEditimport java.util.Scanner;
// Program to perform basic arithmetic operations
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /, ^): ");
char operator = scanner.next().charAt(0);
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
double result = 0;
boolean validOperation = true;
switch(operator) {
case '+' -> result = num1 + num2;
case '-' -> result = num1 - num2;
case '*' -> result = num1 * num2;
case '/' -> {
if (num2 == 0) {
System.out.println("Cannot divide by zero!");
validOperation = false;
} else {
result = num1 / num2;
}
}
case '^' -> result = Math.pow(num1, num2);
default -> {
System.out.println("Invalid operator.");
validOperation = false;
}
}
if (validOperation) {
System.out.printf("Result: %.2f%n", result);
}
scanner.close();
}
}
What I learned:
This calculator program helped me practice user input, switch statements, operator handling, and basic error checking for division by zero.
Summary
Day 3 was packed with hands-on practice covering strings, conditionals, parsing, conversions, and switch statements. I learned how to:
Manipulate and validate strings
Use nested if-else for complex decision-making
Parse strings using substring and indexOf
Take user input to perform unit conversions
Write concise conditional expressions with ternary operators
Use enhanced switch statements
Build a simple interactive calculator
These programs helped me combine theory with practice, improving my confidence in writing real-world Java applications.
Subscribe to my newsletter
Read articles from Himanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Himanshi
Himanshi
Hi! I'm a curious and self-driven programmer currently pursuing my BCA 🎓 and diving deep into the world of Java ☕ from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. I’m learning Java through Bro Code’s YouTube tutorials, experimenting with code, and documenting everything I understand — from basic syntax to real-world applications — to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. You’ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. 💡 Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge 🛠️ Tools: Java • HTML/CSS • JavaScript • Python (basics) • SQL 🎯 Goal: To become a confident Full Stack Developer & AI Explorer 📍 Based in India | Blogging my dev journey #JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe