5 min read

    Java for DSA — Basics

    JavaDsaBasicsVariablesTypesInput-output

    1. Basics

    Note

    Why this matters for DSA Every DSA solution starts with setting up variables, handling inputs/outputs, and understanding data types. Getting type ranges right (especially int vs long) prevents silent overflow bugs that result in wrong answers.


    1.0 What is Java?

    Java is a statically-typed, object-oriented language. Unlike Python, you must declare variable types, and code runs inside classes.

    Running Java Code for DSA

    • Install JDK (Java Development Kit)
    • Run a file: java Filename.java
    • Most platforms (LeetCode, HackerRank) require you to write code inside a class (often named Solution or Main).

    1.1 Variables & Constants

    In Java, variables must be declared with a specific type before they can be used.

    java
    // Primitive variables
    int age = 25;
    double price = 19.99;
    char grade = 'A';
    boolean isActive = true;
    
    // Reference variables
    String name = "Manik";
    
    // Constants (using 'final' keyword)
    final int MAX_SIZE = 100;
    

    1.2 Primitive Data Types

    Java has 8 primitive data types. In DSA, you'll mainly use int, long, double, char, and boolean.

    TypeSizeRange / ExampleUsed for in DSA
    byte1 byte-128 to 127Rare, low-memory buffers
    short2 bytes-32,768 to 32,767Rare
    int4 bytes~ −2×109-2 \times 10^9 to 2×1092 \times 10^9Standard integers, indices, counts
    long8 bytes~ −9×1018-9 \times 10^{18} to 9×10189 \times 10^{18}Large sums (e.g. factorial, modulo arithmetic)
    float4 bytes3.14fRarely used (use double for precision)
    double8 bytes3.14Decimals, percentages, geometric calculations
    char2 bytes'a', 'B'Character problems, Unicode (UTF-16)
    boolean1 bittrue / falseFlags, visited states, binary tracking
    Warning

    The Integer Overflow Trap The max value of a 32-bit signed int in Java is 2,147,483,647 (231−12^{31} - 1). If you sum up elements in an array or compute a large factorial, you might exceed this limit. This causes silent overflow where the value wraps around to negative.

    Fix: Use long instead of int when numbers can exceed 2×1092 \times 10^9. Add an L suffix to long literals: long val = 10000000000L;.


    1.3 Type Conversion & Parsing

    Converting between types is extremely common.

    java
    // 1. Widening Conversion (Implicit) - safe and automatic
    int small = 42;
    double large = small; // 42.0
    
    // 2. Narrowing Conversion (Explicit/Casting) - requires manual cast
    double pi = 3.14;
    int truncatedPi = (int) pi; // 3 (fractional part is discarded)
    
    // 3. String to Number (Parsing) - daily DSA driver
    int num = Integer.parseInt("123");
    long bigNum = Long.parseLong("9876543210");
    double decimal = Double.parseDouble("3.1415");
    
    // 4. Number to String
    String s1 = String.valueOf(123);
    String s2 = Integer.toString(123);
    

    1.4 Input & Output

    Standard input/output is essential for local testing and platforms like Codeforces.

    java
    import java.util.Scanner;
    
    public class Solution {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            
            // Output
            System.out.println("Hello World"); // prints with newline
            System.out.print("Adjacent ");     // prints without newline
            System.out.printf("Formatted count: %d\n", 42); // formatted output
            
            // Input
            String line = sc.nextLine(); // reads entire line
            int age = sc.nextInt();      // reads next integer
            double price = sc.nextDouble(); // reads next double
            
            sc.close();
        }
    }
    
    Tip

    Scanner Speed Warning Scanner is convenient but slow. For competitive programming tasks reading more than 10510^5 inputs, Scanner will cause a Time Limit Exceeded (TLE). In later chapters, we will introduce BufferedReader and custom fast I/O classes.


    1.5 Type Checking

    For reference types (objects), you can check types using instanceof.

    java
    String text = "hello";
    System.out.println(text instanceof String); // true
    
    // You cannot use instanceof directly on primitive types like int, double, etc.
    // Use wrapper classes if object representation is required:
    Integer boxedVal = 42;
    System.out.println(boxedVal instanceof Integer); // true
    

    Practice Drill

    java
    // Try implementing these locally inside a main method:
    // 1. Read two integers from Scanner and print their sum.
    // 2. Read a double, cast it to an integer, and print it.
    // 3. Swap two integer variables (a and b) without using a third temporary variable.
    // 4. Convert a String "456" to an integer, add 44 to it, and print it as a String.
    
    💡 Click for Solutions
    java
    import java.util.Scanner;
    
    public class BasicsDrill {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            
            // 1. Sum of two integers
            System.out.print("Enter two integers: ");
            int a = sc.nextInt();
            int b = sc.nextInt();
            System.out.println("Sum: " + (a + b));
            
            // 2. Cast double to int
            double dVal = 99.99;
            int iVal = (int) dVal;
            System.out.println("Casted int: " + iVal); // 99
            
            // 3. Swap without temp variable (using addition/subtraction)
            int x = 5, y = 10;
            x = x + y; // x becomes 15
            y = x - y; // y becomes 5 (original x)
            x = x - y; // x becomes 10 (original y)
            System.out.printf("Swapped: x = %d, y = %d\n", x, y);
            
            // 4. Parse, calculate and convert to String
            String numStr = "456";
            int parsedNum = Integer.parseInt(numStr);
            int resultNum = parsedNum + 44;
            String finalStr = String.valueOf(resultNum);
            System.out.println("Final String: " + finalStr); // "500"
            
            sc.close();
        }
    }
    

    ← Syllabus | Next → Strings