Java Fundamentals: Control Structures, Built-in Types, and Variables

Java Fundamentals: Control Structures, Built-in Types, and Variables

This file contains beginner-friendly Java code examples focused on fundamental concepts: control structures, primitive types, and variables. These examples are designed to help you practice reading and understanding basic Java syntax and logic flow.

How to Scan this Code

  1. Start with variables and types - Understand how Java handles different data types
  2. Follow control flow - Trace through if statements, loops, and logical operations
  3. Notice Java patterns - See how Java’s type system and syntax work
  4. Practice mental execution - Try to predict what each code block will output
  5. Focus on patterns - Recognize common Java programming patterns

Example 1: 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        // Show variable types
74        System.out.println("\n=== Variable Types Demo ===");
75        int intVar = 42;
76        double doubleVar = 3.14159;
77        boolean boolVar = true;
78        char charVar = 'A';
79        String stringVar = "Hello";
80        
81        System.out.println("int: " + intVar + " (type: int)");
82        System.out.println("double: " + doubleVar + " (type: double)");
83        System.out.println("boolean: " + boolVar + " (type: boolean)");
84        System.out.println("char: " + charVar + " (type: char)");
85        System.out.println("String: " + stringVar + " (type: String)");
86    }
87}

What to Notice:

  • Explicit Type Declaration: Every variable must have a declared type (int age, String name)
  • Primitive vs Reference Types: int, double, boolean, char are primitives; String is a reference type
  • String Immutability: String operations like .toLowerCase() return new strings
  • Type Casting: (int) Math.round() explicitly converts double to int
  • Array Access: split(" ")[0] accesses array elements by index
  • Method Chaining: Can chain methods like studentName.split(" ")[0]
  • Boolean Operators: && (and), || (or) for logical operations
  • Ternary Operator: condition ? valueIfTrue : valueIfFalse
  • String Concatenation: Using + operator to combine strings
  • Block Scope: Variables declared inside if blocks are only accessible within that block

Trace Through Example:

 1String studentName = "Alice Johnson";
 2String firstName = "Alice";          // studentName.split(" ")[0]
 3String lastName = "Johnson";         // studentName.split(" ")[1]
 4char lastInitial = 'J';             // lastName.charAt(0)
 5String displayName = "Alice J.";    // firstName + " " + lastInitial + "."
 6
 7double gpa = 3.85;
 8boolean isEnrolled = true;
 9boolean isHonorStudent = true;       // (3.85 >= 3.5) && true → true && true
10boolean needsAdvising = false;       // (3.85 < 2.0) || (15 < 12)  false || false

Example 2: Control Structures and Conditional Logic

Code to Read:

  1import java.util.Scanner;
  2
  3public class GradeCalculator {
  4    
  5    public static void calculateGrades(int[] scores) {
  6        // Check for null or empty array
  7        if (scores == null || scores.length == 0) {
  8            System.out.println("No scores provided");
  9            return;  // Early return - exit method
 10        }
 11        
 12        // Initialize counters and accumulators
 13        int totalPoints = 0;
 14        int[] gradeCounts = new int[5];  // A, B, C, D, F counts (indices 0-4)
 15        int failedTestCount = 0;
 16        int bonusPoints = 0;
 17        
 18        System.out.println("Processing individual scores:");
 19        
 20        // Process each score with different conditional logic
 21        for (int i = 0; i < scores.length; i++) {
 22            int score = scores[i];
 23            char letterGrade;
 24            String feedback;
 25            
 26            System.out.print("Test " + (i + 1) + ": " + score + " points → ");
 27            
 28            // Nested if-else chain for grade assignment
 29            if (score >= 90) {
 30                letterGrade = 'A';
 31                feedback = "Excellent!";
 32                gradeCounts[0]++;  // Increment A count
 33            } else if (score >= 80) {
 34                letterGrade = 'B';
 35                feedback = "Good work!";
 36                gradeCounts[1]++;  // Increment B count
 37            } else if (score >= 70) {
 38                letterGrade = 'C';
 39                feedback = "Satisfactory";
 40                gradeCounts[2]++;  // Increment C count
 41            } else if (score >= 60) {
 42                letterGrade = 'D';
 43                feedback = "Needs improvement";
 44                gradeCounts[3]++;  // Increment D count
 45            } else {
 46                letterGrade = 'F';
 47                feedback = "Failed - needs retake";
 48                gradeCounts[4]++;  // Increment F count
 49                failedTestCount++;
 50            }
 51            
 52            System.out.println(letterGrade + " - " + feedback);
 53            
 54            // Add to total
 55            totalPoints += score;
 56            
 57            // Bonus points for exceptional performance
 58            if (score >= 95) {
 59                int bonus = 5;
 60                bonusPoints += bonus;
 61                System.out.println("    Bonus: +" + bonus + " points for excellence!");
 62                
 63                // Extra bonus for perfect score
 64                if (score == 100) {
 65                    int perfectBonus = 5;  // Additional bonus
 66                    bonusPoints += perfectBonus;
 67                    System.out.println("    Perfect score bonus: +" + perfectBonus + " points!");
 68                }
 69            }
 70        }
 71        
 72        // Calculate statistics
 73        double averageScore = (double) totalPoints / scores.length;  // Cast to avoid integer division
 74        double adjustedAverage = (double) (totalPoints + bonusPoints) / scores.length;
 75        
 76        // Determine overall performance using compound conditions
 77        String overallGrade;
 78        String recommendation;
 79        
 80        if (averageScore >= 90 && failedTestCount == 0) {
 81            overallGrade = "Outstanding";
 82            recommendation = "Excellent work! Consider advanced coursework.";
 83        } else if (averageScore >= 80 && failedTestCount <= 1) {
 84            overallGrade = "Strong";
 85            recommendation = "Good performance. Keep up the good work!";
 86        } else if (averageScore >= 70 || (averageScore >= 65 && bonusPoints > 0)) {
 87            overallGrade = "Satisfactory";
 88            recommendation = "Adequate progress. Focus on consistent improvement.";
 89        } else if (failedTestCount > scores.length / 2) {  // More than half failed
 90            overallGrade = "Concerning";
 91            recommendation = "Significant struggles. Recommend tutoring and study group.";
 92        } else {
 93            overallGrade = "Needs Improvement";
 94            recommendation = "Some challenges noted. Additional support recommended.";
 95        }
 96        
 97        // Create detailed report
 98        System.out.println("\n=== Grade Report ===");
 99        System.out.println("Total tests: " + scores.length);
100        System.out.printf("Average score: %.1f%n", averageScore);  // printf formatting
101        
102        if (bonusPoints > 0) {
103            System.out.println("Bonus points earned: " + bonusPoints);
104            System.out.printf("Adjusted average: %.1f%n", adjustedAverage);
105        }
106        
107        System.out.println("Overall grade: " + overallGrade);
108        System.out.println("Recommendation: " + recommendation);
109        
110        // Show grade distribution using loops and conditionals
111        System.out.println("\nGrade Distribution:");
112        String[] gradeLetters = {"A", "B", "C", "D", "F"};
113        String[] symbols = {"✓", "✓", "○", "○", "✗"};  // Different symbols for different grades
114        
115        for (int i = 0; i < gradeCounts.length; i++) {
116            if (gradeCounts[i] > 0) {
117                double percentage = ((double) gradeCounts[i] / scores.length) * 100;
118                System.out.printf("  %s %s: %d tests (%.1f%%)%n", 
119                    symbols[i], gradeLetters[i], gradeCounts[i], percentage);
120            }
121        }
122        
123        // Warning for failed tests using conditional
124        if (failedTestCount > 0) {
125            System.out.println("\n⚠️  Failed " + failedTestCount + " out of " + scores.length + " tests");
126            System.out.println("   Consider retaking these assessments.");
127        }
128    }
129    
130    public static void demonstrateLoopTypes() {
131        System.out.println("\n=== Loop Types Demonstration ===");
132        
133        // Standard for loop
134        System.out.println("1. Standard for loop (counting):");
135        for (int i = 1; i <= 5; i++) {
136            System.out.print(i + " ");
137        }
138        System.out.println();
139        
140        // Enhanced for loop (for-each)
141        System.out.println("2. Enhanced for loop (for-each):");
142        int[] numbers = {10, 20, 30, 40, 50};
143        for (int number : numbers) {
144            System.out.print(number + " ");
145        }
146        System.out.println();
147        
148        // While loop
149        System.out.println("3. While loop:");
150        int count = 1;
151        while (count <= 3) {
152            System.out.print("Round " + count + " ");
153            count++;
154        }
155        System.out.println();
156        
157        // Do-while loop
158        System.out.println("4. Do-while loop (executes at least once):");
159        int value = 1;
160        do {
161            System.out.print("Value: " + value + " ");
162            value++;
163        } while (value <= 2);
164        System.out.println();
165    }
166    
167    public static void main(String[] args) {
168        // Test with different score scenarios
169        System.out.println("=== Scenario 1: Strong Student ===");
170        int[] strongScores = {92, 88, 95, 87, 100, 89};
171        calculateGrades(strongScores);
172        
173        System.out.println("\n" + "=".repeat(50));
174        System.out.println("=== Scenario 2: Struggling Student ===");
175        int[] strugglingScores = {45, 67, 55, 72, 58, 48};
176        calculateGrades(strugglingScores);
177        
178        System.out.println("\n" + "=".repeat(50));
179        System.out.println("=== Scenario 3: Empty Array ===");
180        int[] emptyScores = {};
181        calculateGrades(emptyScores);
182        
183        // Demonstrate different loop types
184        demonstrateLoopTypes();
185    }
186}

What to Notice:

  • Array Declaration: int[] scores declares an array of integers
  • Null Checking: Always check for null before using reference types
  • Array Length: Use .length property (not a method) for arrays
  • Enhanced For Loop: for (int score : scores) iterates over values
  • Type Casting: (double) totalPoints converts int to double for division
  • Printf Formatting: System.out.printf("%.1f%n", value) for formatted output
  • String Repeat: "=".repeat(50) creates a string of 50 equal signs (Java 11+)
  • Compound Conditions: Using && and || with parentheses for clarity
  • Array Initialization: int[] gradeCounts = new int[5] creates array with default values (0)
  • Loop Variable Scope: Variables declared in for loops are scoped to the loop
  • Early Return: return statement exits method immediately

Trace Through Example:

 1int[] scores = {92, 88, 95};
 2// Loop iteration 1: i=0, score=92
 3//   92 >= 90 → letterGrade='A', gradeCounts[0]=1, feedback="Excellent!"
 4//   92 >= 95 → false, no bonus
 5// Loop iteration 2: i=1, score=88
 6//   88 >= 80 → letterGrade='B', gradeCounts[1]=1, feedback="Good work!"
 7// Loop iteration 3: i=2, score=95
 8//   95 >= 90 → letterGrade='A', gradeCounts[0]=2, feedback="Excellent!"
 9//   95 >= 95 → true, bonusPoints=5
10
11// Final: totalPoints=275, averageScore=91.7, failedTestCount=0
12// 91.7 >= 90 && 0 == 0  overallGrade="Outstanding"

Reading Practice Tips

After studying these fundamental examples:

  1. Trace variable changes: Follow how variables get declared, modified, and go out of scope
  2. Understand type rules: Know when explicit casting is needed and why
  3. Practice array patterns: Recognize different ways to iterate and process arrays
  4. Follow method calls: Understand parameter passing and return values
  5. Read control flow carefully: Follow the logic through nested if-else and loops

Remember: These Java fundamentals form the foundation of all Java programs. Understanding how variables, types, arrays, and control structures work will make reading more complex Java code much easier.