Java Fundamentals: Mastering Flow Control and String Manipulation
Logic Control Exercises
To reinforce flow control concepts, consider the following implementtaions for common algorithmic tasks.
Parity Check
Determining whether an integer is even or odd using modular arithmetic:
int value = 7;
if (value % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
Rendering a Diamond Pattern
Constructing a symmetrical shape using nested loops requires managing spaces and symbols relative to the row index:
int height = 5;
int midpoint = height / 2 + 1;
// Upper section
for (int row = 1; row <= midpoint; row++) {
for (int spaces = 0; spaces < midpoint - row; spaces++) System.out.print(" ");
for (int stars = 0; stars < 2 * row - 1; stars++) System.out.print("*");
System.out.println();
}
// Lower section
for (int row = midpoint - 1; row >= 1; row--) {
for (int spaces = 0; spaces < midpoint - row; spaces++) System.out.print(" ");
for (int stars = 0; stars < 2 * row - 1; stars++) System.out.print("*");
System.out.println();
}
Series Summation
Calculating the sum of factorials (1 + 1/2! + 1/3! + ... + 1/20!) efficiently using a single loop:
double totalSum = 0;
double currentFactorial = 1;
for (int i = 1; i <= 20; i++) {
currentFactorial *= i;
totalSum += 1.0 / currentFactorial;
}
System.out.println(totalSum);
Working with Strings
In Java, String is a class rather than a primitive type. While you can instantiate strings using various constructors, literal assignment is the standard practice.
Initialization Methods
// Using character arrays
char[] data = {'j', 'a', 'v', 'a'};
String str1 = new String(data);
// Sub-segment extraction
String str2 = new String(data, 0, 2); // Result: "ja"
// Literal assignment (preferred for memory efficiency via the String Pool)
String str3 = "Java Programming";
String Concatenation
Java supports simple concatenation using the + operator. When mixing non-string types with strings, Java automatically converts the primitive values into their string representations. Operator precedence is critical when performing arithmetic within a concatanation statement:
int pages = 50;
double hours = 2.5;
// Implicit conversion
System.out.println("Read " + pages + " pages in " + hours + " hours.");
// Explicit grouping for arithmetic
System.out.println("Total work units: " + (pages + hours));