In this module, you'll learn about working with strings, gathering user input through the console, and documenting your code with comments in Java.
Strings are sequences of characters and are one of the most commonly used data types in Java. The String
class provides many useful methods for manipulating text.
// String literal - most common way
String greeting = "Hello, World!";
// Using the String constructor
String message = new String("Welcome to Java");
// Empty string
String empty = "";
Strings in Java are immutable, which means once a String object is created, it cannot be changed. When you perform operations on a String, a new String object is created.
String name = "John";
name = name + " Smith"; // Creates a new String object "John Smith"
// The original "John" string remains unchanged in memory
length()
- Returns the number of characters in the stringcharAt(int index)
- Returns the character at the specified index (0-based)substring(int beginIndex)
- Returns a new string starting from the specified index to the endsubstring(int beginIndex, int endIndex)
- Returns a new string from beginIndex (inclusive) to endIndex (exclusive)indexOf(String str)
- Returns the index of the first occurrence of the specified substringlastIndexOf(String str)
- Returns the index of the last occurrence of the specified substringtoLowerCase()
- Returns a new string with all characters converted to lowercasetoUpperCase()
- Returns a new string with all characters converted to uppercasetrim()
- Returns a new string with leading and trailing whitespace removedreplace(char oldChar, char newChar)
- Returns a new string with all occurrences of oldChar replaced with newCharcontains(CharSequence s)
- Returns true if the string contains the specified sequencestartsWith(String prefix)
- Checks if the string starts with the specified prefixendsWith(String suffix)
- Checks if the string ends with the specified suffixequals(Object obj)
- Compares this string to another objectequalsIgnoreCase(String anotherString)
- Compares strings, ignoring case differencesString text = "Java Programming";
// Basic information
int length = text.length(); // 16
char firstChar = text.charAt(0); // 'J'
boolean containsJava = text.contains("Java"); // true
// Extracting substrings
String sub1 = text.substring(5); // "Programming"
String sub2 = text.substring(0, 4); // "Java"
// Finding positions
int indexOfP = text.indexOf("P"); // 5
int indexOfr = text.indexOf("r"); // 7
int lastIndexOfr = text.lastIndexOf("r"); // 9
// Transforming
String upper = text.toUpperCase(); // "JAVA PROGRAMMING"
String lower = text.toLowerCase(); // "java programming"
String replaced = text.replace('a', 'A'); // "JAvA ProgrAmming"
There are multiple ways to concatenate (join) strings in Java:
// Using the + operator
String firstName = "John";
String lastName = "Smith";
String fullName = firstName + " " + lastName; // "John Smith"
// Using concat() method
String greeting = "Hello, ";
String message = greeting.concat(firstName); // "Hello, John"
// When concatenating with non-String values, Java automatically converts them to strings
int age = 30;
String info = "Age: " + age; // "Age: 30"
double price = 19.99;
String priceTag = "Price: $" + price; // "Price: $19.99"
When you need to concatenate many strings (especially in a loop), using the +
operator can be inefficient. StringBuilder
provides a more efficient way:
// Inefficient way for many concatenations
String result = "";
for (int i = 0; i < 10; i++) {
result = result + i; // Creates a new String object each time
}
// Efficient way using StringBuilder
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++) {
builder.append(i); // Modifies the same StringBuilder object
}
String result = builder.toString(); // Convert to String when finished
Java provides powerful string formatting capabilities:
// Using String.format()
String name = "Alice";
int age = 25;
double height = 5.75;
String formatted = String.format("Name: %s, Age: %d, Height: %.2f feet", name, age, height);
// Result: "Name: Alice, Age: 25, Height: 5.75 feet"
// Common format specifiers
// %s - String
// %d - Decimal integer
// %f - Floating point
// %.2f - Floating point with 2 decimal places
// %n - Platform-specific line separator
// You can also use printf for direct output
System.out.printf("Name: %s, Age: %d%n", name, age);
The Scanner
class is the most common way to read user input from the console in Java.
// Import the Scanner class
import java.util.Scanner;
// Create a Scanner object to read from System.in (keyboard)
Scanner scanner = new Scanner(System.in);
// Reading a string (whole line)
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Reads the entire line
// Reading a word (reads until whitespace)
System.out.print("Enter a word: ");
String word = scanner.next();
// Reading numbers
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads an integer
System.out.print("Enter your height: ");
double height = scanner.nextDouble(); // Reads a double
// Reading a boolean
System.out.print("Are you a student? (true/false): ");
boolean isStudent = scanner.nextBoolean(); // Reads a boolean
When mixing calls to nextLine()
with other methods like nextInt()
, be aware of this common issue:
// This can cause problems
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads the number but leaves the newline character
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // This immediately reads the leftover newline character!
// The solution: add an extra nextLine() call after nextInt()
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume the leftover newline
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Now this works as expected
When reading user input, it's important to handle potential errors. For example, if the user enters text when you're expecting a number:
// Basic error handling with try-catch
Scanner scanner = new Scanner(System.in);
int number = 0;
try {
System.out.print("Enter a number: ");
number = scanner.nextInt();
System.out.println("You entered: " + number);
} catch (Exception e) {
System.out.println("That's not a valid number!");
}
Scanner can also be used to read from files:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
try {
File file = new File("data.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
It's good practice to close the Scanner when you're done with it to free up resources:
scanner.close();
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
scanner.nextLine(); // Consume newline
char operator = scanner.nextLine().charAt(0);
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero");
scanner.close();
return;
}
break;
default:
System.out.println("Error: Invalid operator");
scanner.close();
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
scanner.close();
}
}
Comments are used to explain code, make it more readable, and provide additional information that might not be immediately evident from the code itself. They are ignored by the compiler.
Java supports three types of comments:
Used for brief explanations. Everything after //
to the end of the line is a comment.
// This is a single-line comment
int count = 10; // Initialize count to 10
Used for longer explanations that span multiple lines. Everything between /*
and */
is a comment.
/* This is a multi-line comment
that spans multiple lines
and can provide detailed explanations */
int result = calculateTotal();
Special documentation comments that can be used to generate API documentation. They start with /**
and end with */
.
/**
* Calculates the sum of two integers.
*
* @param a The first integer
* @param b The second integer
* @return The sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
@param
- Describes a method parameter@return
- Describes what a method returns@throws
or @exception
- Describes exceptions that might be thrown@see
- Provides a reference to another class or method@since
- Specifies when this feature was added@deprecated
- Indicates that a method is deprecated and should no longer be usedComments can be used to "comment out" code, temporarily disabling it without deleting it:
// This code is currently disabled
// System.out.println("This won't be executed");
/* Multiple lines of code can be disabled this way
int a = 5;
int b = 10;
System.out.println(a + b);
*/
/**
* A simple Student class to represent student information.
*
* @author Your Name
* @version 1.0
* @since 2023-04-15
*/
public class Student {
// Student's name
private String name;
// Student's ID (unique identifier)
private int id;
// GPA on a 4.0 scale
private double gpa;
/**
* Constructs a new Student with the specified name, ID, and GPA.
*
* @param name The name of the student
* @param id The unique ID of the student
* @param gpa The GPA of the student on a 4.0 scale
*/
public Student(String name, int id, double gpa) {
this.name = name;
this.id = id;
// Ensure GPA is within valid range
if (gpa < 0.0 || gpa > 4.0) {
throw new IllegalArgumentException("GPA must be between 0.0 and 4.0");
}
this.gpa = gpa;
}
/**
* Returns whether the student is on the honor roll.
* A student is on the honor roll if their GPA is 3.5 or higher.
*
* @return true if the student is on the honor roll, false otherwise
*/
public boolean isOnHonorRoll() {
return gpa >= 3.5; // Honor roll threshold is 3.5
}
/* This method was replaced with a more efficient implementation
public String getFullInfo() {
return "Name: " + name + ", ID: " + id + ", GPA: " + gpa;
}
*/
/**
* Returns a string representation of the student.
*
* @return A string containing the student's name, ID, and GPA
*/
@Override
public String toString() {
return String.format("Student[name=%s, id=%d, gpa=%.2f]", name, id, gpa);
}
}
In this guided project, you'll apply your knowledge of strings, user input, and comments to create interactive programs:
This project focuses on string manipulation and involves:
This project demonstrates practical applications of strings in a chess game context:
By completing these projects, you'll gain practical experience with the core concepts of this module and see how they can be applied to solve real problems.