A. INTRODUCTION & ENVIRONMENT SETUP
What is Java?
-
Platform Independence: Java code is compiled into bytecode (
.classfiles) by thejavaccompiler. This bytecode can run on any device with a Java Virtual Machine (JVM), making Java "write once, run anywhere." -
JVM (Java Virtual Machine): An abstract machine that provides the runtime environment to execute Java bytecode. It performs loading, linking, and initialization.
-
JRE (Java Runtime Environment): Contains the JVM + core libraries (like
java.lang,java.util) needed to run compiled Java programs. It does NOT contain development tools. -
JDK (Java Development Kit): A superset of JRE. Contains JRE + development tools (
javac,java,javadoc, etc.). Essential for writing and compiling Java code.
[!TIP] Common Confusion: JRE is for running Java apps. JDK is for developing Java apps. You need JDK installed to compile.
Setting up the Development Environment
-
Download & Install JDK: Get the latest LTS version from Oracle or use OpenJDK.
-
Set PATH Variable: Add the JDK's
bindirectory (e.g.,C:\Program Files\Java\jdk-xx\bin) to the systemPATHto runjavacandjavafrom any terminal. -
IDEs vs. Text Editors:
-
IDEs (Integrated Development Environment): Eclipse, IntelliJ IDEA, VS Code. Provide code completion, debugging, project management. Recommended for labs.
-
Text Editors: Notepad++, Sublime Text. Lightweight, require manual compilation/execution via command line.
-
First Java Program: Structure & Execution
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
-
public class HelloWorld: Class name must match filename (HelloWorld.java). -
public static void main(String[] args): Mandatory entry point.staticallows calling without object creation. -
System.out.println(): Prints output with a newline. -
Commands:
-
Compile:
javac HelloWorld.java→ GeneratesHelloWorld.class(bytecode). -
Execute:
java HelloWorld→ Runs the class (omit.class).
-
B. BASIC SYNTAX & DATA TYPES
Identifiers, Keywords & Naming Conventions
-
Identifiers: Names for classes, variables, methods. Rules: Start with letter/
_/$; case-sensitive; no keywords. -
Keywords: Reserved words (e.g.,
public,class,void,int). Cannot be used as identifiers. -
Naming Conventions (Best Practice):
-
Class/Interface:
PascalCase(e.g.,StudentRecord). -
Variables/Methods:
camelCase(e.g.,studentName,calculateTotal()). -
Constants:
UPPER_SNAKE_CASE(e.g.,MAX_VALUE).
-
Primitive Data Types
| Category | Type | Size (bits) | Range / Description | Default Value |
|---|---|---|---|---|
| Integer | byte |
8 | -128 to 127 | 0 |
short |
16 | -32,768 to 32,767 | 0 | |
int |
32 | ~-2B to ~2B | 0 | |
long |
64 | Very large (suffix L) |
0L | |
| Floating-Point | float |
32 | Single precision (suffix F) |
0.0f |
double |
64 | Double precision (default for decimals) | 0.0d | |
| Character | char |
16 | Unicode character (e.g., 'A', '\u0041') |
'' |
| Boolean | boolean |
1 | true or false |
false |
Variables
-
Declaration:
dataType variableName;(e.g.,int age;) -
Initialization:
variableName = value;(e.g.,age = 20;) -
Declaration + Initialization:
dataType variableName = value; -
Scope:
-
Instance/Global Variables: Declared in class, outside methods. Accessible by all instance methods.
-
Local Variables: Declared inside a method/block. Accessible only within that block. Must be initialized before use.
-
Operators
| Type | Operators | Example |
|---|---|---|
| Arithmetic | +, -, *, /, % (modulus) |
a + b, a % b |
| Relational | ==, !=, >, <, >=, <= |
a == b |
| Logical | && (AND), ` |
|
| Assignment | =, +=, -=, *=, /=, %= |
a += 5 (a = a+5) |
| Unary | ++, --, +, - |
a++ (post), ++a (pre) |
Operator Precedence (High to Low):
++ --(unary) →* / %→+ -→> >= < <=→== !=→&&→||→= += -=etc.
\boxed{\text{Use parentheses }()\text{ to override precedence and improve clarity.}}
Type Casting
-
Implicit (Widening): Smaller type → Larger type. Automatic. Safe.
int i = 100; double d = i; // Implicit: int to double -
Explicit (Narrowing): Larger type → Smaller type. Manual. May lose data.
double d = 100.75; int i = (int) d; // Explicit: double to int, i = 100 (fraction lost)
Taking User Input with Scanner
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter integer: ");
int num = sc.nextInt(); // Reads integer
System.out.print("Enter string: ");
String str = sc.next(); // Reads single word (space-delimited)
String line = sc.nextLine(); // Reads entire line (use after nextInt/next() with caution)
sc.close();
}
}
[!TIP] Pitfall:
nextInt()/next()leaves a newline\nin buffer. CallingnextLine()immediately after will read this empty line. Fix: Add an extrasc.nextLine();to consume the newline.
C. CONTROL FLOW STATEMENTS
Decision Making
-
if: Executes block if condition istrue.if (score >= 50) { System.out.println("Pass"); } -
if-else: Executes one of two blocks.if (age >= 18) { System.out.println("Adult"); } else { System.out.println("Minor"); } -
if-else-ifladder: Checks multiple conditions.if (marks >= 90) grade = 'A'; else if (marks >= 80) grade = 'B'; else grade = 'C'; -
switch: Multi-way branch based on a singlebyte,short,int,char,String(Java 7+), or enum.switch (day) { case 1: System.out.println("Mon"); break; // break prevents fall-through case 2: System.out.println("Tue"); break; default: System.out.println("Invalid"); }
Looping
-
forloop (traditional):for(init; condition; update) { }for (int i = 0; i < 5; i++) { /* i=0,1,2,3,4 */ } -
Enhanced
for(for-each): Iterates over arrays/collections.int[] arr = {1,2,3}; for (int num : arr) { System.out.println(num); } -
whileloop: Pre-test. May execute 0 times.int i = 0; while (i < 5) { i++; } -
do-whileloop: Post-test. Executes at least once.int i = 0; do { i++; } while (i < 5);
Jump Statements
-
break: Exits the innermost loop orswitch. -
continue: Skips the current iteration, proceeds to next iteration of the loop. -
return: Exits the current method, optionally returns a value.
D. METHODS (FUNCTIONS)
Defining & Calling Methods
// Signature: returnType methodName(parameterList)
public static int add(int a, int b) { // Method definition
return a + b; // Returns value to caller
}
// In main:
int sum = add(5, 3); // Method call with arguments
-
void: Returns nothing. -
Non-
void: Must have areturnstatement matching the return type.
Parameters & Arguments (Pass-by-Value)
-
Java is strictly pass-by-value.
-
For primitives: A copy of the value is passed. Changes inside method do not affect original variable.
void modify(int x) { x = 100; } // Original variable unchanged -
For objects: A copy of the reference (address) is passed. Changes to object's state (fields) are reflected, but reassigning the reference is not.
Method Overloading
-
Concept: Multiple methods in same class with same name but different parameters (type, number, or order).
-
Rules: Must differ in parameter list. Return type alone is insufficient to overload.
int add(int a, int b) { return a+b; } double add(double a, double b) { return a+b; } // Valid overload // int add(int a, int b, int c) { ... } // Also valid
Command-Line Arguments
-
String[] argsinmainreceives arguments passed when running the program. -
Execution:
java MyProgram arg1 arg2 -
Access:
args[0]="arg1",args[1]="arg2".args.lengthgives count.public static void main(String[] args) { if (args.length > 0) { System.out.println("First arg: " + args[0]); } }
E. ARRAYS
Concept & 1D Arrays
-
Contiguous Memory: Elements stored in adjacent memory locations.
-
Fixed Size: Length determined at creation, cannot change.
-
Declaration & Instantiation:
int[] arr1; // Declaration arr1 = new int[5]; // Instantiation (size=5, default values 0) int[] arr2 = new int[]{1,2,3}; // Declaration + Init with values int[] arr3 = {1,2,3}; // Short syntax (only at declaration) -
Accessing Elements:
arr[index]. Index starts at0. Last index =length-1.int first = arr3[0]; // 1 arr3[1] = 20; // Changes array: {1, 20, 3} -
Length Property:
arr3.length→3. Not a method (no parentheses). -
Traversal:
// Traditional for loop (with index) for (int i = 0; i < arr3.length; i++) { System.out.println(arr3[i]); } // Enhanced for loop (value only) for (int val : arr3) { System.out.println(val); }
Arrays as Method Parameters
void printArray(int[] array) { // Passes reference copy
for (int val : array) System.out.print(val + " ");
}
// Call: printArray(arr3);
Two-Dimensional Arrays (2D)
-
Concept: Array of arrays. Jagged arrays possible (rows of different lengths).
-
Declaration & Initialization:
int[][] matrix1 = new int[3][2]; // 3 rows, 2 cols (all 0) int[][] matrix2 = { {1,2}, {3,4,5}, {6} }; // Jagged -
Accessing:
matrix2[0][1]→2(row 0, col 1). -
Traversal: Nested loops.
for (int i = 0; i < matrix2.length; i++) { // Rows for (int j = 0; j < matrix2[i].length; j++) { // Cols in row i System.out.print(matrix2[i][j] + " "); } System.out.println(); }
F. INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING (OOP)
Why OOP?
-
Procedural: Focus on functions/procedures operating on data. Data and functions are separate.
-
Object-Oriented: Focus on objects that combine data (state) and behavior (methods). Promotes modularity, reusability, easier maintenance.
Core Concepts: Class & Object
-
Class: Blueprint/template. Defines fields (variables) and methods.
class Student { // Class definition // Instance variables (state) String name; int rollNo; // Method (behavior) void display() { System.out.println(name + " : " + rollNo); } } -
Object: Instance of a class. Occupies memory.
Student s1 = new Student(); // Object creation with 'new' s1.name = "Rahul"; // Access fields via dot(.) s1.rollNo = 101; s1.display(); -
newkeyword: Allocates memory on the heap and returns a reference to the object.
Constructors
-
Special method called automatically during object creation.
-
Rules: Same name as class, no return type (not even
void). -
Default Constructor: Provided by compiler only if no other constructor is defined. Initializes primitives to default (
0,false), objects tonull. -
Parameterized Constructor: Accepts arguments to initialize fields.
class Student { String name; Student(String n) { name = n; } // Parameterized constructor } Student s = new Student("Rahul"); // Call -
Constructor Overloading: Multiple constructors with different parameters (like method overloading).
this Keyword
-
Reference to the current object within an instance method/constructor.
-
Uses:
-
Distinguish instance variables from parameters with same name.
Student(String name) { this.name = name; // this.name = instance var, name = parameter } -
Call another constructor in same class (
this(...)) - must be first statement. -
Pass current object as argument.
-
Access Modifiers & Encapsulation
-
private: Accessible only within the same class. Used for data hiding. -
public: Accessible from anywhere. -
Encapsulation: Bundling data (fields) and methods (behavior) together, restricting direct access to fields via
privateand providing controlled access viapublicgetter/setter methods.class Student { private String name; // Hidden data public String getName() { return name; } // Getter public void setName(String name) { this.name = name; } // Setter }
G. STRING HANDLING (FUNDAMENTALS)
String Class & Immutability
-
Stringobjects are immutable – cannot be changed after creation. Any modification creates a newStringobject. -
String Literals: Stored in String Constant Pool (SCP). If literal exists, reference is reused.
String s1 = "Hello"; // Created in SCP String s2 = "Hello"; // s2 refers to same SCP object as s1 (s1==s2 is true) -
newString: Always creates a new object in heap (not in SCP).String s3 = new String("Hello"); // New object in heap // s1 == s3 is false (different memory) // s1.equals(s3) is true (same content)
Common String Methods
| Method | Purpose | Example |
|---|---|---|
length() |
Returns number of characters | "Java".length() → 4 |
charAt(index) |
Returns char at index | "Java".charAt(1) → 'a' |
substring(begin) / substring(begin, end) |
Extracts part | "Java".substring(1) → "ava" |
equals(obj) |
Content equality (case-sensitive) | "Java".equals("java") → false |
equalsIgnoreCase(obj) |
Content equality (case-insensitive) | "Java".equalsIgnoreCase("java") → true |
toUpperCase() / toLowerCase() |
Converts case | "Java".toUpperCase() → "JAVA" |
trim() |
Removes leading/trailing whitespace | " Java ".trim() → "Java" |
concat(str) |
Concatenates (like +) |
"Ja".concat("va") → "Java" |
indexOf(ch) / lastIndexOf(ch) |
First/last occurrence index | "banana".indexOf('a') → 1 |
String Concatenation (+ Operator)
-
If either operand is a
String,+performs concatenation (converts other operand viaString.valueOf()).System.out.println("Age: " + 25); // "Age: 25" String s = "Hello" + "World"; // "HelloWorld" -
Compiler Optimization: Compile-time constant expressions are evaluated at compile time.
String s = "Hello" + "World"; // Compiled as "HelloWorld" directly.
[!TIP] Exam Focus: Difference between
==(compares references/memory addresses) and.equals()(compares content). Always use.equals()to compareStringvalues.