0% found this document useful (0 votes)
11 views18 pages

Java Practice Guide

The document is a Java Practice Guide that provides 40 examples across arrays, lists, maps, and file handling, each with code, explanations, and expected outputs. It covers various topics including reading and printing numbers, calculating sums, finding maximum and minimum values, and manipulating lists and maps. The examples are formatted for clarity and are designed to help users practice Java programming concepts effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views18 pages

Java Practice Guide

The document is a Java Practice Guide that provides 40 examples across arrays, lists, maps, and file handling, each with code, explanations, and expected outputs. It covers various topics including reading and printing numbers, calculating sums, finding maximum and minimum values, and manipulating lists and maps. The examples are formatted for clarity and are designed to help users practice Java programming concepts effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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 java.util.Scanner;

public class Ex1 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numbers = new int[5];
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
numbers[i] = sc.nextInt();
}
System.out.println("You entered:");
for (int i = 0; i < 5; i++) {
System.out.println(numbers[i]);
}
sc.close();
}
}

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 java.util.Scanner;

public class Ex2 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
int sum = 0;
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
sum += arr[i];
}
System.out.println("Sum = " + sum);
sc.close();
}
}

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 java.util.Scanner;

public class Ex3 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
System.out.println("Max = " + max);
sc.close();
}
}

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 java.util.Scanner;

public class Ex4 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) arr[i] = sc.nextInt();
int min = arr[0];
for (int i = 1; i < arr.length; i++) if (arr[i] < min) min = arr[i];
System.out.println("Min = " + min);
sc.close();
}
}

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 java.util.Scanner;

public class Ex5 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) arr[i] = sc.nextInt();
System.out.println("Reversed:");
for (int i = arr.length - 1; i >= 0; i--) System.out.println(arr[i]);
sc.close();
}
}
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 java.util.Scanner;

public class Ex6 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
int even = 0, odd = 0;
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
if (arr[i] % 2 == 0) even++; else odd++;
}
System.out.println("Even: " + even + ", Odd: " + odd);
sc.close();
}
}

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 java.util.Scanner;

public class Ex7 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
int sum = 0;
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) { arr[i] = sc.nextInt(); sum += arr[i]; }
double avg = (double) sum / arr.length;
System.out.println("Average = " + avg);
sc.close();
}
}

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 java.util.Scanner;

public class Ex8 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) arr[i] = sc.nextInt();
System.out.println("Enter number to search:");
int key = sc.nextInt();
boolean found = false;
for (int i = 0; i < arr.length; i++) if (arr[i] == key) { found = true; break; }
System.out.println(found ? "Found" : "Not found");
sc.close();
}
}

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 java.util.Scanner;
import java.util.Arrays;

public class Ex9 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[5];
int[] b = new int[5];
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) { a[i] = sc.nextInt(); b[i] = a[i]; }
System.out.println("Copied: " + Arrays.toString(b));
sc.close();
}
}

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 java.util.Scanner;

public class Ex10 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
int pos = 0, neg = 0;
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
if (arr[i] >= 0) pos++; else neg++;
}
System.out.println("Positive: " + pos + ", Negative: " + neg);
sc.close();
}
}

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 java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListEx1 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
System.out.println("Enter 5 names:");
for (int i = 0; i < 5; i++) names.add(sc.nextLine());
System.out.println("Names:");
for (String n : names) System.out.println(n);
sc.close();
}
}

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 java.util.*;
public class ListEx2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<>(Arrays.asList("Apple","Mango","Banana","Grapes","Orange"));
System.out.println("Current: " + list);
System.out.println("Enter name to remove:");
String r = sc.nextLine();
if (list.remove(r)) System.out.println(r + " removed.");
else System.out.println(r + " not found.");
System.out.println("Now: " + list);
sc.close();
}
}

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 java.util.*;
public class ListEx3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> colors = new ArrayList<>(Arrays.asList("Red","Blue","Green","Yellow"));
System.out.println("Enter index (0..3):");
int idx = sc.nextInt();
if (idx >= 0 && idx < colors.size()) System.out.println("At " + idx + ": " + colors.get(idx));
else System.out.println("Invalid index");
sc.close();
}
}

Expected Output / Notes:


If user enters 2 → prints Green.

Example 4: Sort Numbers

Explanation: User types numbers, program sorts and prints them.


import java.util.*;
public class ListEx4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> nums = new ArrayList<>();
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) nums.add(sc.nextInt());
Collections.sort(nums);
System.out.println("Sorted: " + nums);
sc.close();
}
}

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 java.util.*;
public class ListEx5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> items = new ArrayList<>(Arrays.asList("Pen","Pencil","Eraser"));
System.out.println("Enter item to check:");
String it = sc.nextLine();
System.out.println(items.contains(it) ? "Yes present" : "No");
sc.close();
}
}

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 java.util.*;
public class ListEx6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<>(Arrays.asList("A","B","C","D"));
System.out.println("Enter index to insert (0..4):");
int idx = sc.nextInt();
sc.nextLine();
System.out.println("Enter value to insert:");
String v = sc.nextLine();
if (idx >= 0 && idx <= list.size()) list.add(idx, v);
System.out.println("Now: " + list);
sc.close();
}
}

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 java.util.*;
public class ListEx7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<>(Arrays.asList("One","Two","Three","Four"));
System.out.println("Enter index to remove (0..3):");
int idx = sc.nextInt();
if (idx >= 0 && idx < list.size()) {
String removed = list.remove(idx);
System.out.println("Removed: " + removed);
} else System.out.println("Invalid index");
System.out.println("Now: " + list);
sc.close();
}
}

Expected Output / Notes:


Removing index 1 removes 'Two'.

Example 8: Replace Value

Explanation: Replace element at an index with user-provided value.


import java.util.*;
public class ListEx8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<>(Arrays.asList("Red","Green","Blue"));
System.out.println("Enter index to replace (0..2):");
int idx = sc.nextInt();
sc.nextLine();
System.out.println("Enter new value:");
String nv = sc.nextLine();
if (idx >= 0 && idx < list.size()) list.set(idx, nv);
System.out.println("Now: " + list);
sc.close();
}
}

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 java.util.*;
public class ListEx9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 words:");
String[] arr = new String[5];
for (int i = 0; i < 5; i++) arr[i] = sc.nextLine();
List<String> list = new ArrayList<>(Arrays.asList(arr));
System.out.println("As list: " + list);
sc.close();
}
}

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 java.util.*;
public class ListEx10 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>(Arrays.asList("Ravi","Ramu","Teja","Rakesh","Hema"));
System.out.println("Enter starting letter:");
String ch = sc.nextLine();
int count = 0;
for (String n : names) if (n.startsWith(ch)) count++;
System.out.println("Count starting with " + ch + " = " + count);
sc.close();
}
}

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 java.util.*;
public class MapEx1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,Integer> ages = new HashMap<>();
System.out.println("Enter 3 name and age pairs:");
for (int i = 0; i < 3; i++) {
System.out.print("Name: ");
String name = sc.next();
System.out.print("Age: ");
int age = sc.nextInt();
ages.put(name, age);
}
System.out.println("Enter name to lookup:");
String q = sc.next();
System.out.println(ages.containsKey(q) ? q + "'s age = " + ages.get(q) : "Not found");
sc.close();
}
}

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 java.util.*;
public class MapEx2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,String> map = new HashMap<>();
System.out.println("Enter 3 country and capital pairs:");
for (int i = 0; i < 3; i++) {
System.out.print("Country: ");
String country = sc.next();
System.out.print("Capital: ");
String cap = sc.next();
map.put(country, cap);
}
for (String c : map.keySet()) System.out.println(c + " -> " + map.get(c));
sc.close();
}
}

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 java.util.*;
public class MapEx3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,Integer> scores = new HashMap<>();
scores.put("A", 10);
scores.put("B", 15);
System.out.println("Enter name to add points:");
String name = sc.next();
System.out.println("Enter points to add:");
int p = sc.nextInt();
scores.put(name, scores.getOrDefault(name, 0) + p);
System.out.println("Now: " + scores);
sc.close();
}
}

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 java.util.*;
public class MapEx4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,String> m = new HashMap<>();
m.put("k1","v1"); m.put("k2","v2"); m.put("k3","v3");
System.out.println("Map before: " + m);
System.out.println("Enter key to remove:");
String k = sc.next();
m.remove(k);
System.out.println("After: " + m);
sc.close();
}
}

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 java.util.*;
public class MapEx5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,Integer> freq = new HashMap<>();
System.out.println("Enter 5 words:");
for (int i = 0; i < 5; i++) {
String w = sc.next();
freq.put(w, freq.getOrDefault(w, 0) + 1);
}
System.out.println("Frequencies: " + freq);
sc.close();
}
}
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 java.util.*;
public class MapEx6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Character, List<String>> groups = new HashMap<>();
System.out.println("Enter 5 names:");
for (int i = 0; i < 5; i++) {
String s = sc.next();
char k = s.charAt(0);
groups.putIfAbsent(k, new ArrayList<>());
groups.get(k).add(s);
}
for (Character c : groups.keySet()) System.out.println(c + " -> " + groups.get(c));
sc.close();
}
}

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 java.util.*;
public class MapEx7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,Integer> m = new HashMap<>();
System.out.println("Enter 3 name-score pairs:");
for (int i=0;i<3;i++){ String n=sc.next(); int s=sc.nextInt(); m.put(n,s); }
String top = null; int max = Integer.MIN_VALUE;
for (Map.Entry<String,Integer> e : m.entrySet()) {
if (e.getValue() > max) { max = e.getValue(); top = e.getKey(); }
}
System.out.println("Top: " + top + " with " + max);
sc.close();
}
}

Expected Output / Notes:


Finds the name with largest score.

Example 8: Merge Two Maps

Explanation: Combine two maps (second overrides duplicate keys).


import java.util.*;
public class MapEx8 {
public static void main(String[] args) {
Map<String,Integer> a = new HashMap<>();
a.put("x",1); a.put("y",2);
Map<String,Integer> b = new HashMap<>();
b.put("y",20); b.put("z",3);
a.putAll(b);
System.out.println("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 java.util.*;
public class MapEx9 {
public static void main(String[] args) {
Map<String,String> m = new HashMap<>();
System.out.println("Is empty? " + m.isEmpty());
m.put("a","b");
System.out.println("Size: " + m.size());
}
}

Expected Output / Notes:


Initially empty true, after add size 1.

Example 10: Iterate Entries

Explanation: Iterate through entries and print key -> value lines.
import java.util.*;
public class MapEx10 {
public static void main(String[] args) {
Map<String,Integer> m = new HashMap<>();
m.put("A",10); m.put("B",20);
for (Map.Entry<String,Integer> e : m.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
}
}

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 data.txt.


import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileEx1 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try (FileWriter fw = new FileWriter("data.txt")) {
System.out.println("Enter 3 lines:");
for (int i = 0; i < 3; i++) {
fw.write(sc.nextLine() + System.lineSeparator());
}
System.out.println("Written to data.txt");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
sc.close();
}
}

Expected Output / Notes:


Creates/overwrites data.txt with 3 user lines.

Example 2: Read a file line by line

Explanation: Read and print all lines from data.txt.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileEx2 {


public static void main(String[] args) {
try {
File f = new File("data.txt");
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}

Expected Output / Notes:


Prints each line contained in data.txt.

Example 3: Append to existing file


Explanation: Add a new line at the end of an existing file without erasing it.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileEx3 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try (FileWriter fw = new FileWriter("data.txt", true)) {
System.out.println("Enter line to append:");
fw.write(sc.nextLine() + System.lineSeparator());
System.out.println("Appended.");
} catch (IOException e) {
System.out.println("Error");
}
sc.close();
}
}

Expected Output / Notes:


Adds the new line at the end of data.txt.

Example 4: Create and delete a file

Explanation: Create if not exists, then delete the file (demo).


import java.io.File;
import java.io.IOException;

public class FileEx4 {


public static void main(String[] args) {
try {
File f = new File("example.txt");
if (f.createNewFile()) System.out.println("Created example.txt");
else System.out.println("example.txt already exists");
if (f.delete()) System.out.println("Deleted example.txt");
} catch (IOException e) {
System.out.println("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 java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileEx5 {


public static void main(String[] args) {
try {
File f = new File("data.txt");
Scanner sc = new Scanner(f);
int count = 0;
while (sc.hasNextLine()) { sc.nextLine(); count++; }
System.out.println("Line count = " + count);
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}

Expected Output / Notes:


Counts lines present in data.txt.

Example 6: Copy file contents to another file

Explanation: Read a source file and write its contents into target file.
import java.io.*;
public class FileEx6 {
public static void main(String[] args) {
try (FileReader fr = new FileReader("data.txt");
FileWriter fw = new FileWriter("copy.txt")) {
int c;
while ((c = fr.read()) != -1) fw.write(c);
System.out.println("Copied to copy.txt");
} catch (IOException e) { System.out.println("Error"); }
}
}

Expected Output / Notes:


Creates copy.txt with the same contents as data.txt.

Example 7: Write CSV-like data

Explanation: Write comma separated student name and marks lines to students.csv.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileEx7 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try (FileWriter fw = new FileWriter("students.csv")) {
System.out.println("Enter 3 student name and marks:");
for (int i = 0; i < 3; i++) {
String name = sc.next();
int marks = sc.nextInt();
fw.write(name + "," + marks + System.lineSeparator());
}
System.out.println("Saved students.csv");
} catch (IOException e) { System.out.println("Error"); }
sc.close();
}
}

Expected Output / Notes:


students.csv will have lines like: Ravi,85

Example 8: Read CSV and compute average marks


Explanation: Read students.csv and compute average marks.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileEx8 {


public static void main(String[] args) {
try {
File f = new File("students.csv");
Scanner sc = new Scanner(f);
int sum = 0, count = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] parts = line.split(",");
int marks = Integer.parseInt(parts[1]);
sum += marks; count++;
}
sc.close();
if (count > 0) System.out.println("Average = " + ((double)sum/count));
else System.out.println("No data");
} catch (FileNotFoundException e) { System.out.println("students.csv not found"); }
}
}

Expected Output / Notes:


Computes average of marks stored in students.csv.

Example 9: Search a word in file

Explanation: Ask user a word and check if it appears in data.txt.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileEx9 {


public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter word to search:");
String key = scn.next();
try {
File f = new File("data.txt");
Scanner sc = new Scanner(f);
boolean found = false;
while (sc.hasNextLine()) {
if (sc.nextLine().contains(key)) { found = true; break; }
}
sc.close();
System.out.println(found ? "Found" : "Not Found");
} catch (FileNotFoundException e) { System.out.println("File not found"); }
scn.close();
}
}

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 java.io.FileWriter;
import java.io.IOException;

public class FileEx10 {


public static void main(String[] args) {
try (FileWriter fw = new FileWriter("safe.txt")) {
fw.write("This uses try-with-resources\n");
System.out.println("Wrote safe.txt");
} catch (IOException e) {
System.out.println("Error");
}
}
}

Expected Output / Notes:


Creates safe.txt and ensures writer is closed automatically.

You might also like