IT
CBSE Class 12 • Code 802
Unit 3: Java Programming
CBSE Class 12 — Information Technology (Subject Code 802)
Unit 3: Fundamentals of Java Programming
Comprehensive Study Notes with Complete Example Programs & Outputs
Showing all 10 study modules
No matching notes found
Try searching for another keyword such as Bytecode, double, while, Scanner, or Thread.
3.1
Introduction to Java & Program Structure
-
Computer Program & Programming: A computer program is a sequence of instructions given to a computer to accomplish a specific task. Programming is the preparation and writing of these instructions in a high-level language (such as Java, C++, or Python).
-
Java Bytecode & JVM (Platform Independence): Unlike traditional compilers that convert code directly into platform-specific machine code, the Java compiler translates Java source code (
.java) into highly optimized Java Bytecode (.class). At runtime, the Java Virtual Machine (JVM) acts as an interpreter that translates Bytecode into native machine code for the host OS (Windows, Linux, or macOS). This makes Java platform-independent and portable. -
NetBeans IDE Workflow: Projects are created via
File > New Project (Ctrl + Shift + N) > Java > Java Application. Saving a file (Ctrl + S) automatically compiles it (Compile on Save). Programs are executed viaRun > Run Project (F6)orRun > Run File (Shift + F6).
Anatomy of a Basic Java Program
- Package Statement: Declares a group of related classes that can share data and code (e.g.,
package helloworld;). - Class Declaration: The
public classname must exactly match the.javasource filename (e.g.,HelloWorld.javadefinespublic class HelloWorld). - Comments: Ignored by the compiler. Single-line comments start with
//and multi-line comments are enclosed between/*and*/. main()Method & Output: Execution begins atpublic static void main(String[] args). All statements end with a semicolon (;).System.out.println()prints text followed by a newline, whereasSystem.out.print()keeps the cursor on the same line.
3.2
Data Types and Variables
-
Variables: Named storage locations in memory whose values can change during program execution. Variables declared inside a method are local variables and are accessible only inside that method.
-
Variable Naming Rules: Must be a single word (no spaces); can begin with a letter, underscore (
_), or dollar sign ($); can contain letters, digits, and underscores; cannot be a Java reserved keyword (e.g.,int); and are strictly case-sensitive (percentagediffers fromPercentage).
Java’s 8 Primitive Data Types
| Data Type | Category | Size | Usage / Example |
|---|---|---|---|
| byte | Integer | 8-bit | Small whole numbers |
| short | Integer | 16-bit | Medium whole numbers |
| int | Integer | 32-bit | Standard integers (int total_marks = 400;) |
| long | Integer | 64-bit | Large integers |
| float | Floating Point | 32-bit | Single-precision fractional numbers |
| double | Floating Point | 64-bit | Double-precision decimals (double avg = 86.5;) |
| char | Character | 16-bit | Single character in single quotes (char grade = 'M';) |
| boolean | Logical | 1-bit | Stores only true or false |
String Variables & Concatenation: Multi-character text is stored using the String class enclosed in double quotes (e.g., String name = "Mayank";). When used with numbers, + performs arithmetic addition; when used with Strings, + concatenates (joins) them together.
3.3
Operators in Java
1. Arithmetic Operators (Example: int a = 20, b = 30)
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
| + | Addition | Adds two operands | a + b | 50 |
| – | Subtraction | Subtracts second operand from first | a – b | -10 |
| * | Multiplication | Multiplies both operands | a * b | 600 |
| / | Division | Returns integer quotient (truncates decimal) | b / a | 1 |
| % | Modulus | Returns remainder of division | a % b | 20 |
| ++ | Increment | Increases operand value by 1 | a++ or ++a | 21 |
| — | Decrement | Decreases operand value by 1 | b– or –b | 29 |
2. Relational, Assignment & Logical Operators
| Category | Operators | Purpose & Behavior |
|---|---|---|
| Relational | ==, !=, >, <, >=, <= | Compare two values and return a boolean result (true or false). |
| Assignment | =, +=, -=, *=, /=, %= | Assign values. Compound operators perform operation & assign (e.g., a += b means a = a + b). |
| Logical | && (AND), || (OR), ! (NOT) | Combine boolean expressions: && is true if both are true; || is true if at least one is true; ! reverses truth value. |
3.4
Control Flow Structures
A. Selection Structures (if-else & switch)
-
if,if-else, and Nestedif: Evaluates a boolean condition inside parentheses. Executes theifblock when true and the optionalelseblock when false. Placing anif-elseinside anotheriforelseforms a nested if. -
switchStatement: Matches a variable or expression (must evaluate tobyte,short,int, orchar) against multiple constantcaselabels. Each case ends withbreak;to exit the switch block. If no case matches, the optionaldefaultblock runs.
B. Repetition Structures (while, do-while, and for Loops)
-
Loop Terminology: Repeating a block of statements until a test condition fails is called looping. A single pass through the loop body is an iteration.
-
forLoop: Best suited when the exact number of iterations is known:for (initialization; test_condition; update) { statements }. Loop counters declared inside the header are scoped strictly within the loop body.
| Feature | while Loop |
do-while Loop |
|---|---|---|
| Control Type | Entry-controlled (checks condition before running body) | Exit-controlled (checks condition after running body) |
| Minimum Executions | 0 times (may never run if condition is initially false) | At least 1 time (always executes body once) |
| Syntax | while (condition) { statements } | do { statements } while (condition); (Semicolon required) |
Common Coding Errors in Loops (Board Exam Hotspots)
- Infinite Loop: Forgetting to update the loop counter inside a
whileloop causes it to run forever. - Misplaced Semicolon: Writing
while (x <= 5);orfor (int i=1; i<=5; i++);creates an empty null loop body. - Off-by-One Error: Using
<instead of<=(or vice versa), causing one extra or one fewer iteration. - Out-of-Scope Counter: Accessing a
for-loop counter variable outside the loop’s closing brace.
3.5 – 3.6
Arrays & User-Defined Methods
-
Arrays: An array is a collection of multiple values of the same data type stored under a single variable name. Array indexing starts at
0and runs up ton - 1for an array of sizen. -
Declaration, Allocation &
length: Dynamic allocation:double[] marks = new double[5];| Static initialization:double[] marks = {346, 144, 103, 256.5, 387.5};.marks.lengthreturns the total capacity (5). Accessing an index>= lengththrowsArrayIndexOutOfBoundsException. -
User-Defined Methods: A reusable block of code grouped to perform a specific task:
return_type method_name(parameter_list) { statements; return value; }. Usevoidif no value is returned. Declaring a method asstaticallows calling it without creating an object.
3.7 – 3.8
Object-Oriented Programming (OOP)
-
Class & Object: A class is a logical blueprint defining attributes (data members) and behaviors (method members). An object is a specific instance of a class created using the
newkeyword (Book b1 = new Book();). Members are accessed via the dot (.) operator. All Java classes implicitly inherit from the baseObjectclass. -
Constructors: A special method with the exact same name as the class and no return type, invoked automatically when an object is instantiated via
newto initialize data members. Defining a parameterized constructor disables the default no-argument constructor unless you explicitly define a parameter-less constructor alongside it. -
Access Modifiers (
publicvs.private) & Getters/Setters: Members declaredpublicare accessible both inside and outside the class. Members declaredprivateare visible only within their own class. Public getter and setter methods provide controlled read/write access toprivatedata members.
3.9
Java Libraries (
Java Libraries (java.util & java.lang)
-
Importing Packages: Prebuilt classes outside
java.langmust be imported using theimportkeyword before the class definition (e.g.,import java.util.Scanner;). Classes injava.lang(such asString,Integer,System) are imported automatically. -
User Input (
java.util.Scanner): Create aScannerobject attached to standard keyboard input:Scanner sc = new Scanner(System.in);. Usesc.next()to read aStringtoken andInteger.parseInt(sc.next())to read integer values. -
Array Manipulation (
java.util.Arrays):Arrays.sort(arr)sorts numeric arrays in ascending order andStringarrays alphabetically.Arrays.binarySearch(arr, key)searches forkeyin a sorted array and returns its 0-based index (or-1if not found).
Commonly Used String Class Methods (java.lang.String)
| Method Signature | Description | Example (s = "Hello World") |
Output |
|---|---|---|---|
| charAt(int index) | Returns character at specified 0-based index | s.charAt(6) | ‘W’ |
| concat(String str) | Appends str to the end of the string | s.concat(” Today”) | “Hello World Today” |
| contains(String s) | Returns true if substring exists | s.contains(“Hell”) | true |
| endsWith(String suf) | Tests whether string ends with suffix | s.endsWith(“old”) | false |
| equals(Object obj) | Case-sensitive equality comparison | s.equals(“hello world”) | false |
| equalsIgnoreCase(s) | Case-insensitive equality comparison | s.equalsIgnoreCase(“hello world”) | true |
| indexOf(ch / str) | Returns index of first occurrence | s.indexOf(‘W’) / s.indexOf(“rld”) | 6 / 8 |
| isEmpty() | Returns true if string length is 0 | s.isEmpty() | false |
| length() | Returns total number of characters | s.length() | 11 |
| replace(old, new) | Replaces all occurrences of char or String | s.replace(‘l’, ‘*’) | “He**o Wor*d” |
| toLowerCase() | Converts all characters to lowercase | s.toLowerCase() | “hello world” |
| toUpperCase() | Converts all characters to uppercase | s.toUpperCase() | “HELLO WORLD” |
3.10
Exception Handling
-
What is an Exception? An unexpected runtime error (such as integer division by zero throwing
ArithmeticExceptionor invalid indexing throwingArrayIndexOutOfBoundsException) that disrupts normal execution and terminates the program prematurely. (Note: Floating-point division by zero evaluates toInfinityinstead of throwing an error). -
try-catch-finallyMechanism: Thetryblock encloses statements that might generate an exception. Thecatchblock receives the exception object (e.g.,catch (Exception e)) and handles it gracefully using methods likee.getMessage(). The optionalfinallyblock always executes when thetryblock exits—whether an exception occurred or not—and is used for resource cleanup.
3.11
MySQL Database Connectivity (JDBC)
-
NetBeans Setup Steps: (1) Open
Servicestab > Right-clickDatabases> Register MySQL Server (configurelocalhost, port3306, usernameroot, password, and paths tomysqladmin/mysqld). (2) Right-click the registered server and click Connect. (3) InProjectstab > Right-clickLibraries> Add JAR/Folder and addmysql-connector-java-*.jar. -
4-Step JDBC Execution Flow: Import classes from
java.sql.*, establish aConnectionviaDriverManager.getConnection(), create aStatementobject, run the SQL query usingexecuteQuery()to get aResultSet, and iterate rows withrs.next().
3.12
Assertions, Threads, & Wrapper Classes
-
Assertions: Used during testing/debugging to verify logical assumptions:
assert age >= 18 : "Age not Valid";. If false, Java throws anAssertionError. Disabled by default; enable via command line (java -ea ClassName) or NetBeansProject Properties > Run > VM Options (-ea). -
Multithreading: Allows concurrent execution of multiple independent parts (threads) of a program. Created either by extending the
Threadclass or implementing theRunnableinterface and overridingrun(). Callingstart()launches the thread. Control methods includesetPriority(1–10),sleep(ms), andwait(). -
Wrapper Classes: Predefined classes in
java.langthat wrap primitive data types into objects so they can be passed by reference or manipulated with helper methods:Boolean,Byte,Character,Integer,Float,Double,Long, andShort. Common methods includeb.intValue(),Integer.parseInt("345"), andInteger.toString(3456).
