Java for DSA — Basics
1. Basics
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
SolutionorMain).
1.1 Variables & Constants
In Java, variables must be declared with a specific type before they can be used.
// 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.
| Type | Size | Range / Example | Used for in DSA |
|---|---|---|---|
byte | 1 byte | -128 to 127 | Rare, low-memory buffers |
short | 2 bytes | -32,768 to 32,767 | Rare |
int | 4 bytes | ~ to | Standard integers, indices, counts |
long | 8 bytes | ~ to | Large sums (e.g. factorial, modulo arithmetic) |
float | 4 bytes | 3.14f | Rarely used (use double for precision) |
double | 8 bytes | 3.14 | Decimals, percentages, geometric calculations |
char | 2 bytes | 'a', 'B' | Character problems, Unicode (UTF-16) |
boolean | 1 bit | true / false | Flags, visited states, binary tracking |
The Integer Overflow Trap
The max value of a 32-bit signed int in Java is 2,147,483,647 (). 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 . Add an L suffix to long literals: long val = 10000000000L;.
1.3 Type Conversion & Parsing
Converting between types is extremely common.
// 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.
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();
}
}
Scanner Speed Warning
Scanner is convenient but slow. For competitive programming tasks reading more than 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.
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
// 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
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();
}
}