Java Practice Guide
Arrays, Lists, Maps & File Handling — Code + Explanation + Output
40 Examples (10 per topic). Each example includes a simple explanation, code, and expected output
notes.
Colored, easy-to-read formatting. No author name on cover.
Arrays — 10 Examples
Arrays are fixed-size boxes. You decide how many boxes first (like 5). Each box holds one item.
Example 1: Read and Print 5 Numbers
Explanation: User enters 5 numbers; program stores them in an array and prints them back.
import [Link];
public class Ex1 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] numbers = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
numbers[i] = [Link]();
}
[Link]("You entered:");
for (int i = 0; i < 5; i++) {
[Link](numbers[i]);
}
[Link]();
}
}
Expected Output / Notes:
If user types: 1 2 3 4 5 → Program prints each number on a new line.
Example 2: Sum of Array Elements
Explanation: Add all numbers the user enters and print the sum.
import [Link];
public class Ex2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
int sum = 0;
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = [Link]();
sum += arr[i];
}
[Link]("Sum = " + sum);
[Link]();
}
}
Expected Output / Notes:
If user enters 10 20 30 40 50 → Sum = 150.
Example 3: Find Maximum
Explanation: Find the biggest number in the array.
import [Link];
public class Ex3 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = [Link]();
}
int max = arr[0];
for (int i = 1; i < [Link]; i++) {
if (arr[i] > max) max = arr[i];
}
[Link]("Max = " + max);
[Link]();
}
}
Expected Output / Notes:
For input 3 7 2 9 5 → Max = 9.
Example 4: Find Minimum
Explanation: Find the smallest number in the array.
import [Link];
public class Ex4 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) arr[i] = [Link]();
int min = arr[0];
for (int i = 1; i < [Link]; i++) if (arr[i] < min) min = arr[i];
[Link]("Min = " + min);
[Link]();
}
}
Expected Output / Notes:
For input 6 2 8 1 4 → Min = 1.
Example 5: Reverse Array
Explanation: Print the elements of the array in reverse order.
import [Link];
public class Ex5 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) arr[i] = [Link]();
[Link]("Reversed:");
for (int i = [Link] - 1; i >= 0; i--) [Link](arr[i]);
[Link]();
}
}
Expected Output / Notes:
Input: 1 2 3 4 5 → Reversed: 5 4 3 2 1 (each on new line).
Example 6: Count Even and Odd
Explanation: Count how many entered numbers are even and how many are odd.
import [Link];
public class Ex6 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
int even = 0, odd = 0;
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = [Link]();
if (arr[i] % 2 == 0) even++; else odd++;
}
[Link]("Even: " + even + ", Odd: " + odd);
[Link]();
}
}
Expected Output / Notes:
Input 2 3 4 5 6 → Even: 3, Odd: 2.
Example 7: Average of Array
Explanation: Calculate average (mean) of numbers in the array.
import [Link];
public class Ex7 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
int sum = 0;
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) { arr[i] = [Link](); sum += arr[i]; }
double avg = (double) sum / [Link];
[Link]("Average = " + avg);
[Link]();
}
}
Expected Output / Notes:
For 10 20 30 40 50 → Average = 30.0.
Example 8: Search in Array
Explanation: Look for a number the user asks and say if it's found.
import [Link];
public class Ex8 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) arr[i] = [Link]();
[Link]("Enter number to search:");
int key = [Link]();
boolean found = false;
for (int i = 0; i < [Link]; i++) if (arr[i] == key) { found = true; break; }
[Link](found ? "Found" : "Not found");
[Link]();
}
}
Expected Output / Notes:
If key present → prints Found, otherwise Not found.
Example 9: Copy Array
Explanation: Copy all elements from one array into another and print copied array.
import [Link];
import [Link];
public class Ex9 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] a = new int[5];
int[] b = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) { a[i] = [Link](); b[i] = a[i]; }
[Link]("Copied: " + [Link](b));
[Link]();
}
}
Expected Output / Notes:
Input 1 2 3 4 5 → Copied: [1, 2, 3, 4, 5]
Example 10: Count Positive and Negative
Explanation: Count how many numbers are positive (>=0) and negative (<0).
import [Link];
public class Ex10 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = new int[5];
int pos = 0, neg = 0;
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = [Link]();
if (arr[i] >= 0) pos++; else neg++;
}
[Link]("Positive: " + pos + ", Negative: " + neg);
[Link]();
}
}
Expected Output / Notes:
Input 1 -2 3 -4 5 → Positive: 3, Negative: 2.
Lists (ArrayList) — 10 Examples
Lists can grow and shrink. Use ArrayList for flexible storage.
Example 1: Add and Print Names
Explanation: User adds 5 names to a List and program prints them.
import [Link];
import [Link];
import [Link];
public class ListEx1 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> names = new ArrayList<>();
[Link]("Enter 5 names:");
for (int i = 0; i < 5; i++) [Link]([Link]());
[Link]("Names:");
for (String n : names) [Link](n);
[Link]();
}
}
Expected Output / Notes:
User types names → Program prints the same names, each on a new line.
Example 2: Remove an Item
Explanation: Remove a name the user types from the list (if present).
import [Link].*;
public class ListEx2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> list = new ArrayList<>([Link]("Apple","Mango","Banana","Grapes","Orange"));
[Link]("Current: " + list);
[Link]("Enter name to remove:");
String r = [Link]();
if ([Link](r)) [Link](r + " removed.");
else [Link](r + " not found.");
[Link]("Now: " + list);
[Link]();
}
}
Expected Output / Notes:
If user enters Mango → Mango removed. If not present → not found.
Example 3: Get by Index
Explanation: User asks index and program shows the item at that index.
import [Link].*;
public class ListEx3 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> colors = new ArrayList<>([Link]("Red","Blue","Green","Yellow"));
[Link]("Enter index (0..3):");
int idx = [Link]();
if (idx >= 0 && idx < [Link]()) [Link]("At " + idx + ": " + [Link](idx));
else [Link]("Invalid index");
[Link]();
}
}
Expected Output / Notes:
If user enters 2 → prints Green.
Example 4: Sort Numbers
Explanation: User types numbers, program sorts and prints them.
import [Link].*;
public class ListEx4 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<Integer> nums = new ArrayList<>();
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) [Link]([Link]());
[Link](nums);
[Link]("Sorted: " + nums);
[Link]();
}
}
Expected Output / Notes:
Input 3 1 4 2 5 → Sorted: [1, 2, 3, 4, 5]
Example 5: Contains Check
Explanation: Check if the list contains the item the user asks for.
import [Link].*;
public class ListEx5 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> items = new ArrayList<>([Link]("Pen","Pencil","Eraser"));
[Link]("Enter item to check:");
String it = [Link]();
[Link]([Link](it) ? "Yes present" : "No");
[Link]();
}
}
Expected Output / Notes:
If user types Pen → Yes present.
Example 6: Insert at Position
Explanation: Insert a value at a specific index (shifts others).
import [Link].*;
public class ListEx6 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> list = new ArrayList<>([Link]("A","B","C","D"));
[Link]("Enter index to insert (0..4):");
int idx = [Link]();
[Link]();
[Link]("Enter value to insert:");
String v = [Link]();
if (idx >= 0 && idx <= [Link]()) [Link](idx, v);
[Link]("Now: " + list);
[Link]();
}
}
Expected Output / Notes:
Insert X at index 2 → A, B, X, C, D.
Example 7: Remove by Index
Explanation: Remove element at user-given index.
import [Link].*;
public class ListEx7 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> list = new ArrayList<>([Link]("One","Two","Three","Four"));
[Link]("Enter index to remove (0..3):");
int idx = [Link]();
if (idx >= 0 && idx < [Link]()) {
String removed = [Link](idx);
[Link]("Removed: " + removed);
} else [Link]("Invalid index");
[Link]("Now: " + list);
[Link]();
}
}
Expected Output / Notes:
Removing index 1 removes 'Two'.
Example 8: Replace Value
Explanation: Replace element at an index with user-provided value.
import [Link].*;
public class ListEx8 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> list = new ArrayList<>([Link]("Red","Green","Blue"));
[Link]("Enter index to replace (0..2):");
int idx = [Link]();
[Link]();
[Link]("Enter new value:");
String nv = [Link]();
if (idx >= 0 && idx < [Link]()) [Link](idx, nv);
[Link]("Now: " + list);
[Link]();
}
}
Expected Output / Notes:
Replace index 0 with Pink → [Pink, Green, Blue]
Example 9: Convert Array to List
Explanation: Read array from user, then convert to List and print.
import [Link].*;
public class ListEx9 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter 5 words:");
String[] arr = new String[5];
for (int i = 0; i < 5; i++) arr[i] = [Link]();
List<String> list = new ArrayList<>([Link](arr));
[Link]("As list: " + list);
[Link]();
}
}
Expected Output / Notes:
Input words → prints list representation.
Example 10: Count Items with Prefix
Explanation: Count how many strings start with a certain letter the user gives.
import [Link].*;
public class ListEx10 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> names = new ArrayList<>([Link]("Ravi","Ramu","Teja","Rakesh","Hema"));
[Link]("Enter starting letter:");
String ch = [Link]();
int count = 0;
for (String n : names) if ([Link](ch)) count++;
[Link]("Count starting with " + ch + " = " + count);
[Link]();
}
}
Expected Output / Notes:
If user enters R → Count = 3 (Ravi, Ramu, Rakesh).
Maps (HashMap) — 10 Examples
Maps store key-value pairs. Use HashMap for fast lookup.
Example 1: Simple Key-Value (Names -> Age)
Explanation: User enters 3 name-age pairs; lookup age by name.
import [Link].*;
public class MapEx1 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<String,Integer> ages = new HashMap<>();
[Link]("Enter 3 name and age pairs:");
for (int i = 0; i < 3; i++) {
[Link]("Name: ");
String name = [Link]();
[Link]("Age: ");
int age = [Link]();
[Link](name, age);
}
[Link]("Enter name to lookup:");
String q = [Link]();
[Link]([Link](q) ? q + "'s age = " + [Link](q) : "Not found");
[Link]();
}
}
Expected Output / Notes:
Store pairs like (Ravi,22). Lookup prints the age or Not found.
Example 2: Country -> Capital
Explanation: Store countries and capitals, then print all pairs.
import [Link].*;
public class MapEx2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<String,String> map = new HashMap<>();
[Link]("Enter 3 country and capital pairs:");
for (int i = 0; i < 3; i++) {
[Link]("Country: ");
String country = [Link]();
[Link]("Capital: ");
String cap = [Link]();
[Link](country, cap);
}
for (String c : [Link]()) [Link](c + " -> " + [Link](c));
[Link]();
}
}
Expected Output / Notes:
Prints all country -> capital lines.
Example 3: Update Value
Explanation: Change an existing value (e.g., update a player's score).
import [Link].*;
public class MapEx3 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<String,Integer> scores = new HashMap<>();
[Link]("A", 10);
[Link]("B", 15);
[Link]("Enter name to add points:");
String name = [Link]();
[Link]("Enter points to add:");
int p = [Link]();
[Link](name, [Link](name, 0) + p);
[Link]("Now: " + scores);
[Link]();
}
}
Expected Output / Notes:
If name not present it's added with given points; otherwise updated.
Example 4: Remove a Key
Explanation: Remove an entry by key provided by the user.
import [Link].*;
public class MapEx4 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<String,String> m = new HashMap<>();
[Link]("k1","v1"); [Link]("k2","v2"); [Link]("k3","v3");
[Link]("Map before: " + m);
[Link]("Enter key to remove:");
String k = [Link]();
[Link](k);
[Link]("After: " + m);
[Link]();
}
}
Expected Output / Notes:
Removing key k2 removes that pair from the map.
Example 5: Count Frequency of Words
Explanation: Read 5 words and count how many times each word appears.
import [Link].*;
public class MapEx5 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<String,Integer> freq = new HashMap<>();
[Link]("Enter 5 words:");
for (int i = 0; i < 5; i++) {
String w = [Link]();
[Link](w, [Link](w, 0) + 1);
}
[Link]("Frequencies: " + freq);
[Link]();
}
}
Expected Output / Notes:
Input: a b a c b → Frequencies: {a=2, b=2, c=1}
Example 6: Map of Lists (Grouping)
Explanation: Group names by starter letter into a map of lists.
import [Link].*;
public class MapEx6 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<Character, List<String>> groups = new HashMap<>();
[Link]("Enter 5 names:");
for (int i = 0; i < 5; i++) {
String s = [Link]();
char k = [Link](0);
[Link](k, new ArrayList<>());
[Link](k).add(s);
}
for (Character c : [Link]()) [Link](c + " -> " + [Link](c));
[Link]();
}
}
Expected Output / Notes:
Groups names by first letter, e.g., R -> [Ravi, Ramu]
Example 7: Find Key with Max Value
Explanation: Find the key that has the highest integer value (e.g., top scorer).
import [Link].*;
public class MapEx7 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Map<String,Integer> m = new HashMap<>();
[Link]("Enter 3 name-score pairs:");
for (int i=0;i<3;i++){ String n=[Link](); int s=[Link](); [Link](n,s); }
String top = null; int max = Integer.MIN_VALUE;
for ([Link]<String,Integer> e : [Link]()) {
if ([Link]() > max) { max = [Link](); top = [Link](); }
}
[Link]("Top: " + top + " with " + max);
[Link]();
}
}
Expected Output / Notes:
Finds the name with largest score.
Example 8: Merge Two Maps
Explanation: Combine two maps (second overrides duplicate keys).
import [Link].*;
public class MapEx8 {
public static void main(String[] args) {
Map<String,Integer> a = new HashMap<>();
[Link]("x",1); [Link]("y",2);
Map<String,Integer> b = new HashMap<>();
[Link]("y",20); [Link]("z",3);
[Link](b);
[Link]("Merged: " + a);
}
}
Expected Output / Notes:
Result: {x=1, y=20, z=3}
Example 9: Check Empty and Size
Explanation: Show how to check if map is empty and its size.
import [Link].*;
public class MapEx9 {
public static void main(String[] args) {
Map<String,String> m = new HashMap<>();
[Link]("Is empty? " + [Link]());
[Link]("a","b");
[Link]("Size: " + [Link]());
}
}
Expected Output / Notes:
Initially empty true, after add size 1.
Example 10: Iterate Entries
Explanation: Iterate through entries and print key -> value lines.
import [Link].*;
public class MapEx10 {
public static void main(String[] args) {
Map<String,Integer> m = new HashMap<>();
[Link]("A",10); [Link]("B",20);
for ([Link]<String,Integer> e : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}
}
}
Expected Output / Notes:
Prints A -> 10 and B -> 20 (order may vary).
File Handling — 10 Examples
File handling allows you to read from and write to files like notebooks on your computer.
Example 1: Write 3 lines to a file
Explanation: User inputs 3 lines; program writes them to [Link].
import [Link];
import [Link];
import [Link];
public class FileEx1 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Enter 3 lines:");
for (int i = 0; i < 3; i++) {
[Link]([Link]() + [Link]());
}
[Link]("Written to [Link]");
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
[Link]();
}
}
Expected Output / Notes:
Creates/overwrites [Link] with 3 user lines.
Example 2: Read a file line by line
Explanation: Read and print all lines from [Link].
import [Link];
import [Link];
import [Link];
public class FileEx2 {
public static void main(String[] args) {
try {
File f = new File("[Link]");
Scanner sc = new Scanner(f);
while ([Link]()) {
[Link]([Link]());
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found");
}
}
}
Expected Output / Notes:
Prints each line contained in [Link].
Example 3: Append to existing file
Explanation: Add a new line at the end of an existing file without erasing it.
import [Link];
import [Link];
import [Link];
public class FileEx3 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try (FileWriter fw = new FileWriter("[Link]", true)) {
[Link]("Enter line to append:");
[Link]([Link]() + [Link]());
[Link]("Appended.");
} catch (IOException e) {
[Link]("Error");
}
[Link]();
}
}
Expected Output / Notes:
Adds the new line at the end of [Link].
Example 4: Create and delete a file
Explanation: Create if not exists, then delete the file (demo).
import [Link];
import [Link];
public class FileEx4 {
public static void main(String[] args) {
try {
File f = new File("[Link]");
if ([Link]()) [Link]("Created [Link]");
else [Link]("[Link] already exists");
if ([Link]()) [Link]("Deleted [Link]");
} catch (IOException e) {
[Link]("Error");
}
}
}
Expected Output / Notes:
Shows create and delete messages.
Example 5: Count lines in a file
Explanation: Count how many lines exist in a given text file.
import [Link];
import [Link];
import [Link];
public class FileEx5 {
public static void main(String[] args) {
try {
File f = new File("[Link]");
Scanner sc = new Scanner(f);
int count = 0;
while ([Link]()) { [Link](); count++; }
[Link]("Line count = " + count);
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found");
}
}
}
Expected Output / Notes:
Counts lines present in [Link].
Example 6: Copy file contents to another file
Explanation: Read a source file and write its contents into target file.
import [Link].*;
public class FileEx6 {
public static void main(String[] args) {
try (FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]")) {
int c;
while ((c = [Link]()) != -1) [Link](c);
[Link]("Copied to [Link]");
} catch (IOException e) { [Link]("Error"); }
}
}
Expected Output / Notes:
Creates [Link] with the same contents as [Link].
Example 7: Write CSV-like data
Explanation: Write comma separated student name and marks lines to [Link].
import [Link];
import [Link];
import [Link];
public class FileEx7 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Enter 3 student name and marks:");
for (int i = 0; i < 3; i++) {
String name = [Link]();
int marks = [Link]();
[Link](name + "," + marks + [Link]());
}
[Link]("Saved [Link]");
} catch (IOException e) { [Link]("Error"); }
[Link]();
}
}
Expected Output / Notes:
[Link] will have lines like: Ravi,85
Example 8: Read CSV and compute average marks
Explanation: Read [Link] and compute average marks.
import [Link];
import [Link];
import [Link];
public class FileEx8 {
public static void main(String[] args) {
try {
File f = new File("[Link]");
Scanner sc = new Scanner(f);
int sum = 0, count = 0;
while ([Link]()) {
String line = [Link]();
String[] parts = [Link](",");
int marks = [Link](parts[1]);
sum += marks; count++;
}
[Link]();
if (count > 0) [Link]("Average = " + ((double)sum/count));
else [Link]("No data");
} catch (FileNotFoundException e) { [Link]("[Link] not found"); }
}
}
Expected Output / Notes:
Computes average of marks stored in [Link].
Example 9: Search a word in file
Explanation: Ask user a word and check if it appears in [Link].
import [Link];
import [Link];
import [Link];
public class FileEx9 {
public static void main(String[] args) {
Scanner scn = new Scanner([Link]);
[Link]("Enter word to search:");
String key = [Link]();
try {
File f = new File("[Link]");
Scanner sc = new Scanner(f);
boolean found = false;
while ([Link]()) {
if ([Link]().contains(key)) { found = true; break; }
}
[Link]();
[Link](found ? "Found" : "Not Found");
} catch (FileNotFoundException e) { [Link]("File not found"); }
[Link]();
}
}
Expected Output / Notes:
Prints Found if key appears in any line.
Example 10: Safe file write with try-with-resources
Explanation: Show using try-with-resources to auto-close writer.
import [Link];
import [Link];
public class FileEx10 {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("This uses try-with-resources\n");
[Link]("Wrote [Link]");
} catch (IOException e) {
[Link]("Error");
}
}
}
Expected Output / Notes:
Creates [Link] and ensures writer is closed automatically.