In the below code , i use `RunTimeException` to control when scanner finishes reading data. Reasons for this being 1. I cannot use any other library than java.lang 2. I cannot use Scanner either , We have been provided a StdIn class which has a static scanner.next() method only for reading strings. My stdin class in the code below is an attempt to post a SSCCE . Note : All the code is inside the main() because that is how the api demands it. Can someone review my code , and possibly tell if there's some other way i can do this better ? import java.io.BufferedInputStream; import java.util.Scanner; public class Subset { public static void main(String[] args) { int k = Integer.parseInt(args[0]); String[] arr = new String[k]; int i = 0; String str; while((str=stdin.readString())!=null && i < arr.length){ arr[i++] = str; // System.out.println(str); } try{ for(; (str=stdin.readString())!=null; i++){ int r = (int)(Math.random()*(i + 1)); if(r < k){ arr[r] = str; //System.out.println(str); } } }catch(RuntimeException e){ // do nothing } for(String s : arr){ System.out.print(s + " "); } System.out.println("\n"); } } class stdin{ private stdin(){} private static Scanner sc = new Scanner(new BufferedInputStream(System.in)); public static String readString(){ return sc.next(); } } **Command line input** : `echo A B C D E F G H I J | java Subset 3` **Output** `A F C`