Week 2 - Strings, Variables, and User Input
Working with strings, variables, and getting user input in Java
Working with Strings
In Java, a String is a sequence of characters. Unlike primitive data types, String is a class in Java, making it a reference type with additional capabilities.
String Declaration and Initialization
There are multiple ways to create strings in Java:
// Using string literal (most common)
String name = "John Doe";
// Using the new keyword
String city = new String("DeLand");
Strings in Java are immutable, meaning once created, they cannot be changed. Any operation that seems to modify a string actually creates a new string.
String Concatenation
Concatenation means joining strings together. In Java, the +
operator is used for this purpose:
String firstName = "Augustus";
String lastName = "Scarlato";
String fullName = firstName + " " + lastName; // "Augustus Scarlato"
You can also concatenate strings with other data types:
int age = 21;
String message = "My name is " + firstName + " and I am " + age + " years old.";
Common String Methods
Java’s String class provides many useful methods:
String text = "Hello, World!";
// Get string length
int length = text.length(); // 13
// Convert to uppercase/lowercase
String upperCase = text.toUpperCase(); // "HELLO, WORLD!"
String lowerCase = text.toLowerCase(); // "hello, world!"
// Get character at specific position (zero-based indexing)
char letter = text.charAt(0); // 'H'
// Check if string contains specific text
boolean contains = text.contains("World"); // true
// Replace parts of a string
String replaced = text.replace("World", "Java"); // "Hello, Java!"
// Extract substring
String sub = text.substring(0, 5); // "Hello"
// Remove whitespace from beginning and end
String trimmed = " Spaces ".trim(); // "Spaces"
Escape Sequences
Sometimes you need to include special characters in strings, like quotes or backslashes. Escape sequences let you do this:
Escape Sequence | Description |
---|---|
\n | Newline |
\t | Tab |
\b | Backspace |
\r | Carriage return |
\f | Form feed |
\' | Single quote |
\" | Double quote |
\\ | Backslash |
Examples:
// Printing quotes
System.out.println("She said, \"Hello!\""); // She said, "Hello!"
// Printing backslashes (common in file paths)
System.out.println("C:\\Program Files\\Java"); // C:\Program Files\Java
// Printing multiple lines with a single statement
System.out.println("Line 1\nLine 2\nLine 3");
/* Output:
Line 1
Line 2
Line 3
*/
Working with Variables and Data Types
Variable Declaration
Variables store data that can be used and manipulated in a program:
// Syntax: dataType variableName = value;
// Primitive data types
int myAge = 21;
char middleInitial = 'J';
double temperature = 98.6;
boolean isStudent = true;
// Reference types
String myDOB = "March 23, 2003";
String streetAddress = "3244 Stetson Lane";
Variable Naming Conventions
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter, underscore, or dollar sign
- Names are case-sensitive (
age
andAge
are different variables) - Names cannot be Java keywords (like
int
orclass
) - Use camelCase for variable names (e.g.,
firstName
,lastVisitDate
)
The char Data Type
The char
data type stores a single character and uses single quotes:
char grade = 'A';
char symbol = '#';
char digit = '5'; // This is different from the integer 5
You can also use Unicode values:
char copyrightSymbol = '\u00A9'; // ©
Print vs println
Java provides two main methods for displaying output:
-
System.out.print()
- Prints text without moving to a new line -
System.out.println()
- Prints text and then moves to a new line
Example:
System.out.print("Hello ");
System.out.print("World");
System.out.println("!");
System.out.println("Next line starts here.");
/* Output:
Hello World!
Next line starts here.
*/
Getting User Input with Scanner
The Scanner
class allows your program to read input from various sources, including the keyboard:
import java.util.Scanner; // Import at the top of your file
public class UserInputExample {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner input = new Scanner(System.in);
// Prompt the user
System.out.print("Enter your name: ");
// Read the input as a String
String name = input.nextLine();
System.out.println("Hello, " + name + "!");
// Prompt for and read numeric input
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.println("In 5 years, you will be " + (age + 5) + " years old.");
// Close the scanner when done
input.close();
}
}
Common Scanner Methods
-
nextLine()
- Reads a line of text (until Enter is pressed) -
next()
- Reads the next token (word) -
nextInt()
- Reads the next input as an integer -
nextDouble()
- Reads the next input as a double -
nextBoolean()
- Reads the next input as a boolean
Important Notes About Scanner
- Always
import java.util.Scanner;
at the top of your file - Create a Scanner object with
Scanner input = new Scanner(System.in);
- Call the appropriate method based on the type of input you expect
- Close the Scanner when you’re done with
input.close();
Self-Assessment Questions
What is the difference between primitive data types and reference types like String?
Primitive data types (like
int
, char
, boolean
) store actual values in memory and are not objects. They don't have methods and use less memory. Reference types like String
are objects that store references to data rather than the actual data. They have methods that can be called and typically use more memory than primitives. How would you concatenate the string "Hello" with the integer 42?
You can use the
+
operator: String result = "Hello" + 42; // "Hello42"
Java automatically converts the integer to a string during concatenation. What happens if you try to print a backslash in a string without using an escape sequence?
You'll get a compilation error. The backslash is an escape character in Java, so it needs to be escaped with another backslash (
\\
) to be displayed correctly. Incorrect:
System.out.println("C:\Program Files\Java");
- This will cause a compilation error Correct:
System.out.println("C:\\Program Files\\Java");
- This will print "C:\Program Files\Java" How would you write code to get a double value as input from the user?
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
double value = input.nextDouble();
Write code to convert a Fahrenheit temperature to Celsius.
// Formula: C = (F - 32) × 5/9
double fahrenheit = 98.6;
double celsius = (fahrenheit - 32) * 5 / 9;
System.out.println(fahrenheit + "°F is equal to " + celsius + "°C");
What will be the output of the following code?
String str1 = "Hello";
String str2 = "World";
int num = 2023;
System.out.print(str1 + " ");
System.out.println(str2 + "! " + num);
Output:
Hello World! 2023
The first
print
statement outputs "Hello " without a newline, then the println
statement outputs "World! 2023" and moves to a new line. The space after "Hello" comes from the literal space character in the first print
statement. How can you find the length of a string in Java?
You can use the
length()
method: String text = "Hello, World!";
int length = text.length(); // Returns 13
Note that length()
is a method for strings (called with parentheses), while length
is a property for arrays (used without parentheses).