UNIT 1: FUNDAMENTALS OF PROGRAMMING & JAVA INTRODUCTION
1.1 Introduction to Programming and Problem Solving
-
Program: A set of precise instructions that directs a computer to perform a specific task.
-
Programming: The process of designing, writing, testing, and maintaining these instructions (code).
-
Programming Life Cycle:
-
Problem Definition: Clearly state the problem.
-
Algorithm Design: Create a step-by-step solution (logic).
-
Coding: Translate the algorithm into a programming language (Java).
-
Compilation & Execution: Convert source code to bytecode (
javac) and run it (java). -
Debugging & Maintenance: Find/fix errors and update the program.
-
-
Algorithm Characteristics (Pillars):
-
Input: Zero or more external values.
-
Output: At least one produced result.
-
Definiteness: Each step must be unambiguous.
-
Finiteness: Must terminate after a finite number of steps.
-
Effectiveness: Each step must be basic enough to be done manually.
-
-
Tools for Algorithm Design:
-
Pseudocode: Informal, English-like description of logic. Not syntax-bound.
- Example:
IF score >= 50 THEN Print "Pass" ELSE Print "Fail"
- Example:
-
Flowcharts: Graphical representation using standard symbols.
- DiagramCANVAS: Flowchart symbols: Oval (Start/End), Parallelogram (Input/Output), Rectangle (Process), Diamond (Decision), Arrows (Flow)
-
[!TIP] Exam Focus: Be able to distinguish between an algorithm's characteristics and write simple pseudocode for a given problem.
1.2 Introduction to Java
-
History & Key Features (SIMPLE, SECURE, PORTABLE, OO, ROBUST, MULTITHREADED, INTERPRETED, HIGH PERFORMANCE, DISTRIBUTED).
-
Java Platform:
| Component | Full Form | Primary Role | | :--- | :--- | :--- | | JDK | Java Development Kit | Development toolkit. Contains JRE + compiler (
javac), debugger, etc. | | JRE | Java Runtime Environment | Execution environment. Contains JVM + core libraries to run Java programs. | | JVM | Java Virtual Machine | Runtime engine. Executes Java bytecode. Provides platform independence. | -
"Write Once, Run Anywhere" (WORA): Java code compiles to platform-independent bytecode (
.classfile). The JVM (platform-specific) interprets this bytecode. This enables portability. -
Application Domains: Web applications (Servlets/JSP), Mobile (Android), Enterprise (Spring), Desktop (Swing/JavaFX).
[!TIP] Common Pitfall: Confusing JDK, JRE, and JVM. Remember: JDK is for developers (has
javac), JRE is for users (hasjava), JVM is the executor inside JRE.
1.3 Setting up the Java Development Environment
-
Install JDK: Download from Oracle/OpenJDK. Verify with
java -versionandjavac -versionin terminal/command prompt. -
Set Environment Variables:
-
JAVA_HOME: Points to JDK installation directory (e.g.,C:\Program Files\Java\jdk-17). -
PATH: Append%JAVA_HOME%\bin(Windows) or$JAVA_HOME/bin(Linux/Mac) to runjavac/javafrom any directory.
-
-
IDE (Optional but Recommended): Eclipse, IntelliJ IDEA, VS Code. They manage projects, provide syntax highlighting, and auto-completion.
-
Source File: Java source code must be saved in a file named exactly after the
public classname, with.javaextension (e.g.,HelloWorld.java).
1.4 Structure of a Java Program
// Documentation comment
/**
* This is a simple Java program.
*/
public class HelloWorld { // Class declaration
// Single-line comment
/* Multi-line comment */
public static void main(String[] args) { // Main method - entry point
System.out.println("Hello, World!"); // Statement
} // End of block
}
-
public static void main(String[] args)Breakdown:-
public: Access modifier, visible to JVM. -
static: Belongs to the class, not an instance. JVM can call it without creating an object. -
void: Returns no value. -
main: Method name (fixed entry point). -
String[] args: Array of strings for command-line arguments.
\boxed{\text{The JVM looks for the exact signature: public static void main(String[] args)}}
-
-
Compilation & Execution:
-
javac HelloWorld.java→ GeneratesHelloWorld.class(bytecode). -
java HelloWorld→ Runs the program (JVM loads.classfile).
-
-
Common Errors:
-
Syntax Error: Missing
;,}, incorrect keyword. Caught by compiler. -
Runtime Error:
ArrayIndexOutOfBoundsException,InputMismatchException. Program crashes during execution. -
Logic Error: Program runs but produces wrong output. Hardest to find.
-
1.5 Data Types, Variables, and Constants
-
Primitive Data Types (8 types):
| Type | Size (bits) | Range / Description | Default Value | | :--- | :--- | :--- | :--- | |
byte| 8 | -128 to 127 | 0 | |short| 16 | -32,768 to 32,767 | 0 | |int| 32 | ~-2 billion to ~2 billion | 0 | |long| 64 | Very large integer (suffixL) | 0L | |float| 32 | Single-precision (suffixF) | 0.0f | |double| 64 | Double-precision (default for decimals) | 0.0d | |char| 16 | Single Unicode character (e.g.,'A','\u0041') |''| |boolean| 1 |trueorfalse|false| -
Variables: Named memory locations. Must be declared with a type before use.
int age; // Declaration age = 25; // Assignment double price = 99.99; // Declaration + Initialization- Identifier Rules: Start with letter/
_/$, subsequent chars can be digits. Case-sensitive. Cannot be Java keyword (int,class).
- Identifier Rules: Start with letter/
-
Constants: Immutable values. Use
finalkeyword.final double PI = 3.14159; // PI = 3.14; // Compile Error: cannot assign a value to final variable PI -
Type Casting:
-
Widening (Implicit): Small type → Large type. Safe, automatic.
int i = 100; double d = i; // OK -
Narrowing (Explicit): Large type → Small type. May lose data, requires cast.
double d = 99.99; int i = (int) d; // i becomes 99
-
[!TIP] Exam Trap:
float f = 10.5;→ Compile Error (10.5 isdoubleby default). Must write10.5for(float)10.5.
1.6 Operators and Expressions
-
Arithmetic:
+,-,*,/,%(modulus/remainder).- Integer division truncates:
5 / 2 = 2.5.0 / 2 = 2.5.
- Integer division truncates:
-
Relational:
==,!=,>,<,>=,<=. Result isboolean. -
Logical:
&&(AND),||(OR),!(NOT). Used withbooleanoperands.&&and||exhibit short-circuiting.
-
Assignment:
=,+=,-=,*=,/=,%=. -
Increment/Decrement:
++,--.-
Prefix:
++x(increment, then use new value). -
Postfix:
x++(use old value, then increment).
-
-
Operator Precedence (High to Low):
-
(),[],. -
++,--,!(unary) -
*,/,% -
+,- -
<,>,<=,>= -
==,!= -
&& -
|| -
=,+=, etc.
-
\boxed{\text{Use parentheses () to override precedence and clarify complex expressions.}}
1.7 Input and Output
-
Output:
-
System.out.print(): Prints without newline. -
System.out.println(): Prints with newline. -
Concatenation:
+operator joins strings with other types.System.out.println("Sum: " + (a + b)); -
System.out.printf()/format(): Formatted output.System.out.printf("Price: %.2f", 49.99); // Output: Price: 49.99
-
-
Input (using
Scannerclass fromjava.util):import java.util.Scanner; // Required import Scanner sc = new Scanner(System.in); int num = sc.nextInt(); // Reads int double d = sc.nextDouble(); // Reads double String s = sc.next(); // Reads single word (token) String line = sc.nextLine(); // Reads entire line (including spaces) sc.close(); // Good practice to close
[!TIP] Common Pitfall: Mixing
nextInt()/nextDouble()andnextLine(). The former leaves a newline\nin the buffer, whichnextLine()consumes immediately. Use an extrasc.nextLine();after numeric input to consume the leftover newline.
1.8 Control Flow Statements
-
Selection (Conditional):
// if-else if (condition) { // code if true } else if (condition2) { // code if condition2 true } else { // code if all false } // switch (works with byte, short, int, char, String, enum) switch (grade) { case 'A': System.out.println("Excellent"); break; case 'B': System.out.println("Good"); break; default: System.out.println("Invalid"); // Optional }breakis crucial inswitchto prevent "fall-through." -
Iteration (Loops):
| Loop | Use Case | Check Condition | | :--- | :--- | :--- | |
while| Unknown iterations, pre-check | Before each iteration | |do-while| At least one iteration, pre-check | After each iteration | |for| Known iterations, counter-based | Before each iteration |// Traditional for for (int i = 0; i < 10; i++) { ... } // Enhanced for (for-each) - for Arrays/Collections int[] arr = {1,2,3}; for (int num : arr) { ... } // num takes value of each element -
Jump Statements:
-
break: Terminates the innermost loop orswitch. -
continue: Skips current iteration of the innermost loop and proceeds to next.
-
DiagramCANVAS: Flowchart comparing while, do-while, and for loop structures showing condition check placement relative to loop body.
1.9 Arrays (Introduction)
-
Need: Store multiple values of the same type under one name.
-
One-Dimensional Array:
// Declaration int[] scores; // Preferred style // OR int scores[]; // Creation (allocates memory) scores = new int[5]; // Array of 5 integers, default 0 // Declaration + Creation + Initialization int[] primes = {2, 3, 5, 7, 11}; // Size inferred (5) // Access scores[0] = 95; // First element (index 0) int first = scores[0]; int length = scores.length; // Property, not method -
Traversal:
// Using index-based for for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); } // Using enhanced for for (int s : scores) { System.out.println(s); } -
Common Error:
ArrayIndexOutOfBoundsException– accessing index< 0or>= length. Indices range from0tolength-1.
[!TIP] Exam Trap: Array size is fixed at creation.
int[] a = new int[5];→ valid indices:0,1,2,3,4.a[5]causes runtime exception.
1.10 Practical Applications & Common Pitfalls
-
Sample Programs: Calculator (using
switch), Grade Evaluator (usingif-else), Number Series (using loops), Finding Max/Min in an array. -
Variable Scope:
- Block Scope: Variable declared inside
{ }(e.g., insideiforfor) is accessible only within that block.
- Block Scope: Variable declared inside
-
Critical Pitfalls:
-
Off-by-One Error: Loop runs one time too many or too few. Remember array indices start at 0.
-
Integer Division:
int result = 5 / 2;→resultis2. Cast at least one operand todoublefor floating-point result:5.0 / 2or(double)5 / 2. -
Uninitialized Variables: Local variables (inside methods) must be initialized before use. Class/instance variables get default values.
-
ScannerNewline Issue: As noted in 1.7. -
forLoop Variable Scope: The loop counter variable (i) is typically scoped to the loop.for (int i=0; ...)makesiinaccessible after the loop.
-
\boxed{\text{Always initialize variables. Test loop boundaries with small arrays (size 1, 2).}}