Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Java Basics

    The Whole Program, and Reading Input the DSA Way

    Everything from Chapters 1–8 in one program:

    Chapter 9 of 95 min read

    9.1 The StudyBuddy report#

    Everything from Chapters 1–8 in one program:

    Java
    public class StudyBuddyReport {
        static final int POINTS_PER_CORRECT = 10; // Ch 2: named constants, not magic numbers
        static final int PASS_MARK = 150;
    
        static int score(int correct, boolean onTime) {
            // Ch 7: a method with parameters and a return value
            int points = correct * POINTS_PER_CORRECT; // Ch 3: arithmetic
            if (onTime) {
                // Ch 5: a decision
                points += 20;
            }
            return points;
        }
    
        static String grade(int points) {
            if (points >= 200) return "A";
            else if (points >= PASS_MARK) return "B";
            else return "Needs practice";
        }
    
        public static void main(String[] args) {
            String[] students = { "Priya", "Rahul", "Aisha", "Vikram" }; // Ch 8: arrays
            int[] correctAnswers = { 18, 13, 20, 9 };
            boolean[] onTime = { true, true, false, true };
    
            int total = 0;
            int bestIndex = 0;
            int[] points = new int[students.length];
    
            for (int i = 0; i < students.length; i++) {
                // Ch 6: a loop over every index
                points[i] = score(correctAnswers[i], onTime[i]);
                total += points[i];
                if (points[i] > points[bestIndex]) {
                    bestIndex = i;
                }
                System.out.printf(
                    "%-7s %3d  %s%n",
                    students[i],
                    points[i],
                    grade(points[i])
                ); // Ch 4: printf
            }
            double average = (double) total / students.length; // Ch 3: cast before dividing
            System.out.printf("Average: %.1f%n", average);
            System.out.println("Top: " + students[bestIndex]);
        }
    }

    Real output:

    Output
    Priya   200  A
    Rahul   150  B
    Aisha   200  A
    Vikram  110  Needs practice
    Average: 165.0
    Top: Priya

    Notice: Priya and Aisha tie at 200, and Priya is reported as top because the check is > (strictly greater), so the first maximum wins. Change it to >= and Aisha wins. In interviews, say out loud how you handle ties — it's exactly the kind of detail interviewers look for.

    9.2 Two styles of coding problems#

    LeetCode-style (most big-company interviews): you write one method inside a class they give you. No main, no input reading:

    Java
    class Solution {
        public int maxScore(int[] scores) {
            int best = Integer.MIN_VALUE; // start below any possible value
            for (int s : scores) {
                best = Math.max(best, s);
            }
            return best;
        }
    }

    Competitive-programming style (Codeforces, CSES, some online assessments): you read input from stdin and print to stdout (The Linux Command Line Ch 5).

    Scanner is simple but slow for large inputs:

    Java
    import java.util.Scanner;
    
    public class ScannerDemo {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String name = sc.next();
            int score = sc.nextInt();
            System.out.println(name + " scored " + score);
        }
    }
    Terminal
    $ printf 'Priya 200\n' | java ScannerDemo.java
    Priya scored 200

    For input with hundreds of thousands of numbers, Scanner can be slow enough to exceed the time limit. The standard fast template uses BufferedReader (reads big chunks at once) and builds all output in one StringBuilder before printing it once (fewer system calls — Operating Systems Ch 2):

    Java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.StringTokenizer;
    
    public class ReadInput {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int n = Integer.parseInt(br.readLine().trim());
            StringTokenizer st = new StringTokenizer(br.readLine()); // splits a line on spaces
            long total = 0; // long: a sum of many ints can overflow
            int best = Integer.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                int score = Integer.parseInt(st.nextToken());
                total += score;
                best = Math.max(best, score);
            }
            StringBuilder out = new StringBuilder();
            out.append("total=").append(total).append('\n');
            out.append("best=").append(best).append('\n');
            System.out.print(out);
        }
    }
    Terminal
    $ printf '5\n72 95 60 88 100\n' | java ReadInput.java
    total=415
    best=100

    (throws IOException is about exceptions — Exceptions and Generics. For now, just include it.)