Java Beginner Basics: Numbers, Strings, Lists, and Maps
Java Beginner Basics: Numbers, Strings, Lists, and Maps
This section contains beginner-friendly Java code examples focused on working with basic data types: numbers, strings, collections (Lists), and Maps. These examples emphasize fundamental operations and common patterns.
Learning Approach: Each example builds on previous concepts. Read the code first, then check the explanations, and finally try the suggested modifications.
How to Use These Examples
Start with basic operations - Understand how Java handles numbers and strings Follow data manipulation - See how to process and transform data Notice Java syntax patterns - Learn Java’s explicit typing and method calls Practice reading collections - Understand Lists and Maps operations Trace through examples - Follow the step-by-step execution
Example 1: Number Operations and Math
Code to Read:
1public class NumberProcessor {
2
3 public static void processNumberData() {
4 // Basic number types and operations
5 int totalItems = 45;
6 double price = 12.99;
7 float discount = 0.15f;
8 long bigNumber = 1000000L;
9
10 System.out.println("=== Basic Number Operations ===");
11 System.out.println("Items: " + totalItems);
12 System.out.println("Price: $" + price);
13 System.out.println("Discount: " + (discount * 100) + "%");
14
15 // Mathematical calculations
16 double discountAmount = price * discount;
17 double finalPrice = price - discountAmount;
18 double totalCost = finalPrice * totalItems;
19
20 // Rounding and formatting
21 double roundedPrice = Math.round(finalPrice * 100.0) / 100.0;
22 int wholeDollars = (int) finalPrice; // Type casting
23 double cents = finalPrice - wholeDollars;
24
25 System.out.println("\n=== Calculations ===");
26 System.out.println("Discount amount: $" + String.format("%.2f", discountAmount));
27 System.out.println("Final price: $" + String.format("%.2f", finalPrice));
28 System.out.println("Total cost: $" + String.format("%.2f", totalCost));
29 System.out.println("Rounded price: $" + roundedPrice);
30 System.out.println("Whole dollars: $" + wholeDollars);
31 System.out.println("Cents portion: " + String.format("%.2f", cents));
32
33 // Number comparisons and conditions
34 if (totalCost > 500.0) {
35 System.out.println("Eligible for free shipping!");
36 } else {
37 double needed = 500.0 - totalCost;
38 System.out.println("Need $" + String.format("%.2f", needed) + " more for free shipping");
39 }
40 }
41
42 public static void main(String[] args) {
43 processNumberData();
44 }
45}
What to Notice:
- Type Declarations: Each number has an explicit type (
int
,double
,float
,long
) - Type Casting:
(int) finalPrice
converts double to int, losing decimal precision - String Formatting:
String.format("%.2f", value)
controls decimal places - Math Library:
Math.round()
for calculations - Arithmetic Operations: Standard operators
+
,-
,*
,/
work with numbers
Trace Through Example:
1int totalItems = 45;
2double price = 12.99;
3float discount = 0.15f;
4
5// Calculations:
6double discountAmount = 12.99 * 0.15 = 1.9485
7double finalPrice = 12.99 - 1.9485 = 11.0415
8double totalCost = 11.0415 * 45 = 496.8675
9
10// Formatting:
11String.format("%.2f", discountAmount) = "1.95"
12String.format("%.2f", finalPrice) = "11.04"
Example 2: String Processing and Text Analysis
Code to Read:
1public class TextProcessor {
2
3 public static void processCustomerData() {
4 // Basic string operations
5 String customerName = "John Smith";
6 String email = "john.smith@email.com";
7 String phone = "(555) 123-4567";
8
9 System.out.println("=== Customer Information ===");
10 System.out.println("Name: " + customerName);
11 System.out.println("Email: " + email);
12 System.out.println("Phone: " + phone);
13
14 // String analysis
15 int nameLength = customerName.length();
16 boolean hasLongName = nameLength > 10;
17 String upperName = customerName.toUpperCase();
18 String lowerEmail = email.toLowerCase();
19
20 System.out.println("\n=== String Analysis ===");
21 System.out.println("Name length: " + nameLength + " characters");
22 System.out.println("Has long name: " + hasLongName);
23 System.out.println("Uppercase name: " + upperName);
24 System.out.println("Lowercase email: " + lowerEmail);
25
26 // String parsing and extraction
27 String[] nameParts = customerName.split(" ");
28 String firstName = nameParts[0];
29 String lastName = nameParts[1];
30
31 // Extract domain from email
32 int atIndex = email.indexOf("@");
33 String username = email.substring(0, atIndex);
34 String domain = email.substring(atIndex + 1);
35
36 System.out.println("\n=== String Parsing ===");
37 System.out.println("First name: " + firstName);
38 System.out.println("Last name: " + lastName);
39 System.out.println("Username: " + username);
40 System.out.println("Domain: " + domain);
41
42 // String validation
43 boolean validEmail = email.contains("@") && email.contains(".");
44 boolean validPhone = phone.length() == 14; // Format: (xxx) xxx-xxxx
45 boolean nameContainsNumbers = !customerName.matches("[a-zA-Z ]+");
46
47 System.out.println("\n=== Validation ===");
48 System.out.println("Valid email format: " + validEmail);
49 System.out.println("Valid phone format: " + validPhone);
50 System.out.println("Name contains numbers: " + nameContainsNumbers);
51 }
52
53 public static void main(String[] args) {
54 processCustomerData();
55 }
56}
What to Notice:
- String Immutability: Operations like
.toUpperCase()
return new strings - Method Chaining: Can call multiple string methods in sequence
- Array Access:
split()
returns an array, accessed with[index]
- Index-based Operations:
substring(start, end)
extracts portions of strings - Boolean Logic: String validation using multiple conditions
- Regular Expressions:
.matches()
checks if string follows a pattern
Trace Through Example:
1String customerName = "John Smith";
2String email = "john.smith@email.com";
3
4// String operations:
5int nameLength = "John Smith".length() = 10
6String[] nameParts = {"John", "Smith"} // from split(" ")
7String firstName = nameParts[0] = "John"
8String lastName = nameParts[1] = "Smith"
9
10// Email parsing:
11int atIndex = email.indexOf("@") = 10
12String username = email.substring(0, 10) = "john.smith"
13String domain = email.substring(11) = "email.com"
Example: Variables, Primitive Types, and String Operations
Code to Read:
1public class StudentInfoProcessor {
2
3 public static void processStudentInfo() {
4 // Primitive data types - must be explicitly declared
5 String studentName = "Alice Johnson"; // Reference type
6 int age = 20; // int primitive
7 double gpa = 3.85; // double primitive
8 boolean isEnrolled = true; // boolean primitive
9 char gradeLevel = 'S'; // char primitive (S for Senior)
10
11 // Working with strings
12 String firstName = studentName.split(" ")[0]; // Get first part
13 String lastName = studentName.split(" ")[1]; // Get second part
14 char lastInitial = lastName.charAt(0); // Get first character
15
16 // String formatting and concatenation
17 String displayName = firstName + " " + lastInitial + ".";
18 String email = firstName.toLowerCase() + "." + lastName.toLowerCase() + "@university.edu";
19
20 // Working with numbers and type casting
21 int totalCredits = 15; // Current semester credits
22 int nextYearAge = age + 1;
23 double gpaPercentage = (gpa / 4.0) * 100; // Convert to percentage
24 int roundedGpa = (int) Math.round(gpaPercentage); // Explicit casting
25
26 // Boolean operations
27 boolean isHonorStudent = (gpa >= 3.5) && isEnrolled;
28 boolean needsAdvising = (gpa < 2.0) || (totalCredits < 12);
29 boolean isSenior = (age >= 21) && (totalCredits > 90);
30
31 // String operations
32 int nameLength = studentName.length();
33 boolean hasLongName = nameLength > 15;
34 String upperName = studentName.toUpperCase();
35 boolean containsJohnson = studentName.contains("Johnson");
36
37 // Conditional (ternary) operator
38 String enrollmentStatus = isEnrolled ? "Enrolled" : "Not Enrolled";
39 String honorStatus = isHonorStudent ? "Honor Student" : "Regular Student";
40
41 // Print information using different formatting methods
42 System.out.println("=== Student Information ===");
43 System.out.println("Name: " + displayName);
44 System.out.println("Age: " + age + " (will be " + nextYearAge + " next year)");
45 System.out.println("Email: " + email);
46 System.out.println("GPA: " + gpa + " (" + String.format("%.1f", gpaPercentage) + "%)");
47 System.out.println("Status: " + enrollmentStatus);
48 System.out.println("Grade Level: " + gradeLevel);
49
50 System.out.println("\n=== Academic Status ===");
51 System.out.println("Total Credits: " + totalCredits);
52 System.out.println("Honor Student: " + (isHonorStudent ? "Yes" : "No"));
53 System.out.println("Needs Advising: " + (needsAdvising ? "Yes" : "No"));
54 System.out.println("Is Senior: " + (isSenior ? "Yes" : "No"));
55
56 System.out.println("\n=== String Analysis ===");
57 System.out.println("Name length: " + nameLength + " characters");
58 System.out.println("Has long name: " + hasLongName);
59 System.out.println("Uppercase name: " + upperName);
60 System.out.println("Contains 'Johnson': " + containsJohnson);
61
62 // Demonstrate variable scope within method
63 if (gpa >= 3.0) {
64 String message = "Good academic standing"; // Local to this block
65 System.out.println("Academic note: " + message);
66 }
67 // message is not accessible here - would cause compilation error
68 }
69
70 public static void main(String[] args) {
71 processStudentInfo();
72 }
73}
What to Notice:
Java Type System in Action
- Explicit type declarations: Every variable must declare its type (
int age
,String name
) - Primitive vs. Reference types:
int
,double
,boolean
,char
are primitives;String
is a reference type - Type casting:
(int) Math.round(gpaPercentage)
explicitly converts double to int - String immutability: String operations create new String objects, don’t modify existing ones
String Operations and Methods
- Method chaining:
firstName.toLowerCase()
calls method on String object - Array access:
studentName.split(" ")[0]
splits string and accesses first element - String formatting: Multiple ways to format output (
+
concatenation,String.format()
) - Boolean methods:
contains()
,length()
return boolean or int values
Boolean Logic and Operators
- Logical operators:
&&
(and),||
(or) for combining boolean expressions - Comparison operators:
>=
,<
,==
for comparing values - Ternary operator:
condition ? valueIfTrue : valueIfFalse
for concise conditionals - Parentheses: Used to control evaluation order in complex expressions
Variable Scope and Lifecycle
- Method scope: Variables declared in method are accessible throughout method
- Block scope: Variables in
if
blocks only accessible within that block - Compilation errors: Java prevents access to out-of-scope variables at compile time
- Initialization: All variables must be initialized before use
Trace Through Example:
1// Starting values:
2String studentName = "Alice Johnson"; // → "Alice Johnson"
3int age = 20; // → 20
4double gpa = 3.85; // → 3.85
5
6// String processing:
7firstName = "Alice Johnson".split(" ")[0] // → "Alice"
8lastName = "Alice Johnson".split(" ")[1] // → "Johnson"
9lastInitial = "Johnson".charAt(0) // → 'J'
10
11// Boolean calculations:
12isHonorStudent = (3.85 >= 3.5) && true // → true && true → true
13needsAdvising = (3.85 < 2.0) || (15 < 12) // → false || false → false