UNIT 1: FOUNDATIONS OF JAVA PROGRAMMING & BASIC SYNTAX
1.1 Introduction to Java and the Programming Environment
What is Java?
-
A high-level, platform-independent, object-oriented programming language.
-
Platform Independence: Achieved via the Java Virtual Machine (JVM). Java code (
*.java) is compiled to bytecode (*.class), which runs on any JVM. -
JRE (Java Runtime Environment): Contains JVM + libraries needed to run Java applications.
-
JDK (Java Development Toolkit): Contains JRE + development tools (like
javaccompiler) to develop Java applications.
Key Features:
| Feature | Description |
|---|---|
| Simple | Syntax similar to C/C++, but eliminates complex features like pointers. |
| Secure | Bytecode verification, no explicit pointers, runtime security checks. |
| Portable | Bytecode runs on any OS with a JVM (Write Once, Run Anywhere). |
| Object-Oriented | Everything is an object (except primitives). Supports classes, inheritance, etc. |
| Robust | Strong memory management, exception handling, type checking. |
| Multithreaded | Built-in support for concurrent programming. |
Setting up the Development Environment:
-
Install JDK: Download from Oracle/OpenJDK. Verify with
java -versionandjavac -version. -
Set Environment Variables:
-
JAVA_HOME: Points to JDK installation directory. -
PATH: Includes%JAVA_HOME%\bin(Windows) or$JAVA_HOME/bin(Linux/Mac) to runjava/javacfrom any directory.
-
-
IDE vs. Text Editor:
-
IDEs (Eclipse, IntelliJ IDEA, VS Code): Provide code completion, debugging, project management. Better for large projects.
-
Text Editor + Command Line: Lightweight, helps understand the compile-run process deeply.
-
[!TIP] EXAM TIP
- JVM is instance-dependent (one per running program), JRE is machine-dependent, JDK is developer-dependent.
javaccompiles source to bytecode.javaexecutes bytecode by invoking JVM.
The Java Programming Process:
Write Source Code (HelloWorld.java)
↓
Compile: `javac HelloWorld.java` → Generates HelloWorld.class (bytecode)
↓
Run: `java HelloWorld` → JVM executes bytecode → Output
1.2 Structure of a Java Program & First Program
Anatomy of a Java Class:
[public] class ClassName { // 'class' keyword, file must be ClassName.java
public static void main(String[] args) { // Entry point
// Statements
}
}
-
File Naming: Must match the
publicclass name exactly (case-sensitive). -
mainMethod Signature:public static void main(String[] args)-
public: Accessible by JVM. -
static: Can be called without creating an object. -
void: Returns nothing. -
String[] args: Array to hold command-line arguments.
-
Hello World Example:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Steps: Save as HelloWorld.java → javac HelloWorld.java → java HelloWorld.
Common Compilation & Runtime Errors:
| Error Type | Example | Cause |
|---|---|---|
| Compilation | error: class HelloWorld is public, should be declared in a file named HelloWorld.java |
File name ≠ public class name. |
error: cannot find symbol |
Variable/method name typo or undeclared. | |
| Runtime | Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException |
Accessing invalid array index. |
Exception in thread "main" java.lang.NumberFormatException |
Scanner.nextInt() on non-integer input. |
[!TIP] COMMON PITFALL
- Forgetting
;at statement end.
mainmethod signature must be exact (e.g.,String args[]is okay, butstring[] argsis not).
- Case sensitivity:
class≠Class.
1.3 Basic Syntax and Language Elements
Comments:
-
Single-line:
// comment -
Multi-line:
/* comment */ -
Documentation:
/** comment */(forjavadoctool).
Tokens (Smallest Individual Units):
| Token Type | Examples |
|---|---|
| Keywords | class, public, static, void, int, if, for (reserved, lowercase). |
| Identifiers | Names for classes, variables, methods (e.g., HelloWorld, myVariable). |
| Literals | Fixed values: 100 (int), 3.14 (double), 'a' (char), "text" (String), true (boolean). |
| Operators | +, -, =, ==, && |
| Separators | ; (statement end), {} (block), [] (array), () (method call/params). |
Statements & Blocks:
-
Statement: Complete instruction ending with
;(e.g.,int x = 5;). -
Block: Group of statements within
{}(defines scope).
1.4 Data Types, Variables, and Type Conversion
Primitive Data Types:
| Type | Size (bits) | Range / Description |
|---|---|---|
byte |
8 | -128 to 127 |
short |
16 | -32,768 to 32,767 |
int |
32 | \boxed{-2^{31} \text{ to } 2^{31}-1} |
long |
64 | -2^{63} to 2^{63}-1 (suffix L/l, e.g., 1000L) |
float |
32 | Single-precision (suffix F/f, e.g., 3.14F) |
double |
64 | Double-precision (default for decimals) |
char |
16 | Unicode character (e.g., 'a', '\u0041') |
boolean |
1 | true or false |
Variables:
-
Declaration:
dataType variableName;(e.g.,int age;) -
Initialization:
variableName = value;(e.g.,age = 25;) -
Declaration + Init:
dataType variableName = value;(e.g.,double price = 99.99;) -
Naming Conventions:
-
Variables/methods:
camelCase(e.g.,studentName). -
Constants (
final):UPPER_SNAKE_CASE(e.g.,MAX_VALUE). -
Classes:
PascalCase(e.g.,StudentRecord).
-
Type Casting:
-
Implicit (Widening): Small type → Large type. Automatic, safe.
int i = 100; double d = i; // int → double (safe) -
Explicit (Narrowing): Large type → Small type. Manual, may lose precision/data.
double d = 99.99; int i = (int) d; // double → int, i = 99 (fraction lost)
Scanner Class for Input:
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); // Reads integer
String str = sc.next(); // Reads single word (space-delimited)
String line = sc.nextLine(); // Reads entire line (including spaces)
[!TIP] CRITICAL PITFALL
nextInt()/next()does not consume the newline (\n). A subsequentnextLine()will read the leftover newline as empty input. Fix: Use an extrasc.nextLine();afternextInt()to consume the newline.
1.5 Operators and Expressions
Operator Categories:
| Category | Operators | Example |
|---|---|---|
| Arithmetic | +, -, *, /, % (modulo) |
10 % 3 = 1 |
| Relational | ==, !=, >, <, >=, <= |
5 > 3 → true |
| Logical | && (AND), ` |
|
| Assignment | =, +=, -=, *=, /=, %= |
x += 5; (x = x + 5) |
| Increment/Decrement | ++, -- |
i++ (postfix), ++i (prefix) |
Prefix vs. Postfix Increment:
int i = 5;
int a = i++; // a = 5 (old value), i = 6
int b = ++i; // i = 7 (incremented first), b = 7
Operator Precedence (Highest to Lowest):
-
(),[],. -
++,--,!(unary) -
*,/,% -
+,- -
>,<,>=,<= -
==,!= -
&& -
|| -
=,+=, etc.
Use parentheses
()to override precedence and improve readability.
1.6 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-else-ifladder: Checks multiple conditions sequentially. -
switch: Efficient for multipleint,char,String(Java 7+),enumvalues.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:
| Loop | Use Case | Syntax |
|---|---|---|
for |
Known iterations | for(int i=0; i<n; i++) { ... } |
Enhanced for |
Traverse arrays/collections | for(type var : array) { ... } |
while |
Pre-test loop (may execute 0 times) | while(condition) { ... } |
do-while |
Post-test loop (executes at least once) | do { ... } while(condition); |
Branching Statements:
-
break: Exits innermost loop orswitch. -
continue: Skips current iteration, proceeds to next. -
return: Exits the current method, optionally returns a value.
[!TIP] EXAM COMPARISON
- Use
forwhen iteration count is known (e.g., array traversal).
- Use
while/do-whilewhen condition depends on runtime input.
do-whileguarantees at least one execution.
1.7 Arrays (Single-Dimensional)
Declaration, Creation, Initialization:
int[] arr1; // Declaration
arr1 = new int[5]; // Creation (size=5, default values=0)
int[] arr2 = {10, 20, 30}; // Declaration + Init with values
int[] arr3 = new int[]{1,2,3}; // Alternate init
Access & Bounds:
-
Indexing:
arr[0](first element),arr[arr.length-1](last). -
ArrayIndexOutOfBoundsException: Occurs if index< 0or>= length.
Traversal:
// Traditional for loop (with index)
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// Enhanced for loop (no index)
for (int val : arr) {
System.out.println(val);
}
Common Operations:
-
Sum/Average:
int sum = 0; for (int val : arr) sum += val; double avg = (double) sum / arr.length; -
Min/Max: Initialize
min = arr[0],max = arr[0], then loop to compare. -
Linear Search: Loop through array, compare each element with target. Return index if found, else
-1. Time Complexity: O(n). -
Reversing: Swap
arr[i]witharr[n-1-i]forifrom0ton/2.
Command-Line Arguments (String[] args):
-
Arguments passed when running:
java MyProgram arg1 arg2 -
Accessed inside
main:args[0]="arg1",args[1]="arg2". -
args.lengthgives number of arguments.
[!TIP] ARRAY FUNDAMENTALS
- Array length is fixed after creation (
arr.lengthis final).
- All elements are default-initialized (
0forint,0.0fordouble,falseforboolean,nullfor objects).
- Arrays are objects stored in heap memory. The variable holds a reference to the array.
1.8 Practical Lab Exercises & Mini-Projects
Core Exercises:
-
Environment Setup: Install JDK, set
PATH, compile/runHelloWorld.javafrom command line. -
Simple Calculator: Use
Scannerto read two numbers and an operator (+,-,*,/), perform operation, handle division by zero. -
Number Guessing Game: Generate random number (using
Math.random()orRandomclass), user guesses with loop until correct, give "higher/lower" hints. -
Number Checks:
-
Prime: Check divisibility from
2to√n. -
Palindrome (number/string): Reverse and compare.
-
Armstrong: Sum of digits raised to power of total digits equals number.
-
-
Array Manipulation:
-
Sorting: Implement Bubble Sort (O(n²)) or Selection Sort (O(n²)).
-
Reversing: In-place swap.
-
Searching: Linear search (O(n)).
-
-
Student Grade Management:
-
Store marks of
nstudents in array. -
Calculate average, highest, lowest.
-
Count students above/below average.
-
Mini-Project Idea:
- Contact Management System: Use parallel arrays (or later, objects) for names, phones. Provide menu-driven options to Add, Display, Search, Delete contacts using array traversal and shifting.
[!TIP] LAB EXAM STRATEGY
- Always validate input (e.g., check for negative array size, non-numeric input).
- Modularize: Break problem into methods (e.g.,
int findMax(int[] arr)).
- Test edge cases: Empty array, single element, duplicate values, zero/negative inputs.