Skip to content
EX-306 · Computer Programming-I (JAVA)/Quick Revision Short Notes

Computer Programming-I (JAVA) (EX-306) - Unit 1 Short Notes

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:

    1. Problem Definition: Clearly state the problem.

    2. Algorithm Design: Create a step-by-step solution (logic).

    3. Coding: Translate the algorithm into a programming language (Java).

    4. Compilation & Execution: Convert source code to bytecode (javac) and run it (java).

    5. 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"
    • 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 (.class file). 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 (has java), JVM is the executor inside JRE.


1.3 Setting up the Java Development Environment

  1. Install JDK: Download from Oracle/OpenJDK. Verify with java -version and javac -version in terminal/command prompt.

  2. 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 run javac/java from any directory.

  3. IDE (Optional but Recommended): Eclipse, IntelliJ IDEA, VS Code. They manage projects, provide syntax highlighting, and auto-completion.

  4. Source File: Java source code must be saved in a file named exactly after the public class name, with .java extension (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 → Generates HelloWorld.class (bytecode).

    • java HelloWorld → Runs the program (JVM loads .class file).

  • 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 (suffix L) | 0L | | float | 32 | Single-precision (suffix F) | 0.0f | | double | 64 | Double-precision (default for decimals) | 0.0d | | char | 16 | Single Unicode character (e.g., 'A', '\u0041') | '' | | boolean | 1 | true or false | 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).
  • Constants: Immutable values. Use final keyword.

    
    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 is double by default). Must write 10.5f or (float)10.5.


1.6 Operators and Expressions

  • Arithmetic: +, -, *, /, % (modulus/remainder).

    • Integer division truncates: 5 / 2 = 2. 5.0 / 2 = 2.5.
  • Relational: ==, !=, >, <, >=, <=. Result is boolean.

  • Logical: && (AND), || (OR), ! (NOT). Used with boolean operands.

    • && 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):

    1. (), [], .

    2. ++, --, ! (unary)

    3. *, /, %

    4. +, -

    5. <, >, <=, >=

    6. ==, !=

    7. &&

    8. ||

    9. =, +=, 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 Scanner class from java.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() and nextLine(). The former leaves a newline \n in the buffer, which nextLine() consumes immediately. Use an extra sc.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
    
    }
    
    

    break is crucial in switch to 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 or switch.

    • 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 < 0 or >= length. Indices range from 0 to length-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 (using if-else), Number Series (using loops), Finding Max/Min in an array.

  • Variable Scope:

    • Block Scope: Variable declared inside { } (e.g., inside if or for) is accessible only within that block.
  • Critical Pitfalls:

    1. Off-by-One Error: Loop runs one time too many or too few. Remember array indices start at 0.

    2. Integer Division: int result = 5 / 2; → result is 2. Cast at least one operand to double for floating-point result: 5.0 / 2 or (double)5 / 2.

    3. Uninitialized Variables: Local variables (inside methods) must be initialized before use. Class/instance variables get default values.

    4. Scanner Newline Issue: As noted in 1.7.

    5. for Loop Variable Scope: The loop counter variable (i) is typically scoped to the loop. for (int i=0; ...) makes i inaccessible after the loop.

\boxed{\text{Always initialize variables. Test loop boundaries with small arrays (size 1, 2).}}

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in