Week 6: Java – Strings & 2D Arrays
Q1. Username Encryption (Reverse + Uppercase)
Objective: Read a username, reverse it, convert to uppercase, and display the “encrypted” username.
import java.util.Scanner;
class UsernameEncryptor {
static void userpass() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter username: ");
String user = sc.nextLine();
System.out.println("Original Username: " + user);
// Reverse and convert to uppercase
String encrypted = new StringBuilder(user)
.reverse()
.toString()
.toUpperCase();
System.out.println("Encrypted Username: " + encrypted);
}
public static void main(String args[]) {
UsernameEncryptor.userpass();
}
}
Key Points:
StringBuilderallows reversing strings efficiently.- Chaining
.reverse()and.toUpperCase()is convenient. - No explicit loop is needed for character manipulation.
Q2. Image Rotation / Transpose of 2D Array
Objective: Input a 2D matrix representing an image and display its transpose (rows ↔ columns).
import java.util.Scanner;
class ImageRotation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();
System.out.print("Enter number of columns: ");
int cols = sc.nextInt();
int[][] image = new int[rows][cols];
// Input pixel values
System.out.println("Enter pixel values:");
for (int i = 0; i < rows; i++) {
System.out.print("Row " + (i + 1) + ": ");
for (int j = 0; j < cols; j++) {
image[i][j] = sc.nextInt();
}
}
// Transpose the matrix
int[][] transposed = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = image[i][j];
}
}
// Print the transposed matrix
System.out.println("\nTransposed Image Matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transposed[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}
Key Points:
- Transpose swaps rows and columns:
transposed[j][i] = original[i][j]. - Useful for image processing or matrix operations.
- Always allocate the new array with dimensions
[cols][rows].
Week 6 Notes:
StringBuilderis efficient for reversing strings.toUpperCase()converts all letters to uppercase.- 2D arrays are stored in row-major order in Java.
- Transposing a matrix is a fundamental operation for image rotation or mathematical computations.