Download Complete Java Programming Notes PDF | BCA | MCA | B.Tech | OOP | JDBC | Collections | Inte and more Cheat Sheet Java Programming in PDF only on Docsity!
1. INTRODUCTION TO JAVA Developed by James Gosling and his team in 1991. _——— @ First name was “Oak”. G Java is a hagbelevalll eetnaeeds object-oriented programming language oR as “Java” in 1995. ——w developed. by Sun Microsystems (now owned by Oracle). It is designed to have © Officially released by Sun Microsystems in 1996. —== Java saab * Java is a programming language and a platform. * It is used to develop applications for desktops, web, mobile, and more. * It is designed to be simple, secure, portable and robust. * Java follows Write Once, Run Anywhere. Features of Java 66 069000 6 000 Simple — Easy to learn and use. Object-Oriented - Based on OOPs concepts Platform Independent. - Write once, run. anywhere (WORA). Secure - Provides automatic memory management and. security Robust - Strong memory management and. exception handling. Architecture Neutral - No fixed Portable - Same program runs on different. platforms. Multithreaded - Supports concurrent programming. High Performance — Uses Just-In-Time (JIT) compiler. Distributed — Built-in support for networking. Dynamic — Can adapt to changing environment. 7. Applications of Java ae ee eens ie Summary: Desktop Applications (@.g., IDEs, Tools) Web Applications (e.g., Banking, Shopping) Enterprise Applications Mobile Applications (Android Apps) Games Scientific Applications Big Data Technologies Cloud-Based Applications as few implementation dependencies as possible. 3. How Java Works? 1. Java code is first written in a jave file. 2. The compiler (javac) converts it into byte code (.class file). 3. The JVM executes the byte code on any platform. Editi JSE (Java Standard. Edition) Now owned. by Oracle Corporation. Why Java is Platform Independent @ Java code is compiled into byte code, not machine code. feat me oe Machine), —| ® Byte code is executed by JVM. © JVM is available on every platform. ‘Output. © Therefore, the same program can run on Windows, Linux, Mac, etc. | Byte Code (.class) | . Write Once, Run Anywhere —_ _— | JVM (Java Virtual Machine) lava. Platforms and Editions | = Class aT Description Interpreter Core Java technology. Used for desktop | applications. X Used. for enterprise applications like web, | JEE (Java. Enterprise Edition) JME (Java Micro Edition) JavaFX servlets, JSP, EJB, etc. | Used for mobile and embedded devices. Used to build rich internet applications with advanced UI. irst Java Program 9. Java Environment Setup (JDK) #f HelloWorld. java Java Fully object-oriented Platform independent Automatic memory management — Manual memory management Uses JVM No pointers Slower than C++ public class HelloWorld { C++ To run Java programs, we need JDK installed. Not: fly object-oriented. | | soibesesatece: | public static void main(String[] args) { | re 1. JRE (Java Runtime Erwt ) System.out. printin(“Hello, World!"); 2, JVM (ava Virtual Machine) 3. Java Compiler (javac) 4, Other tools (java, javadoc, etc.) No JVM Supports pointers Faster than Java Java is a powerful, simple, secure, portable and. platform-independent language. @ Key Point: Java was designed with the goal of platform independence, It follows Write Once, Run Anywhere and is widely used in various applications. security, and robustness. 2. FEATURES OF JAVA What are Features? Why Java is Platform Independent? Features are the special qualities of Java that make it better and different from other programming languages. JVM on any Java Source Code Compiler Byte Code Main Features of Java (javac) (.class file) 1) Simple Java is easy to learn. Its syntax is simple and clean, similar to C/C++. 2] Cbjecticiotited * Byte code is executed by JVM on any platform. Java is based on OOP concepts like Class, Object, Inheritance, Polymorphism, Abstraction, Encapsulation. C3] Platform Independent Java code can run on any platform that has JVM. Write Once, Run Anywhere (WORA). 4) Secure Java is designed to be secure. It does not have pointers and provides automatic memory management. 5] Robust Java is robust because of strong type checking, exception handling and garbage collection. 6) Portable Java can be easily ported from one platform to another. The size of primitive data types is fixed. 16 (7) High Performance 11 With JIT Just In Time) compiler, Java provides high performance. Platform (java file) ¢ Compiler converts Java source code into byte code. Example: Simple Java Program // This is a simple Java program class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); 1 2 3 4 5 } 6 7 8 9 Output 8) Multi-threaded Java allows concurrent execution of multiple threads. Hello, World! It helps in developing interactive applications. Summary of Features fa fo 5 a =, 1. Simple 2. Object-Oriented 3. Platform Independent 4. Secure Easy to learn and ‘\ Supports OOP concepts Same code can run on No pointers, no virus understand with @_-@ which help in writing any platform that has threats. Automatic simple syntax. modular and reusable — JVM (WORA). memory management. — ~ ~ 5. Robust 6. Portable 7. High Performance 8. Multi-threaded 1 Strong type checking, Can be moved from fs oa JIT compiler and 0; Multiple threads can exception handling and G@—sa Sone system to another ~# optimized runtime run concurrently, garbage collection. easily. environment. improving performance. yO os Note: These features make Java a powerful, reliable and widely used programming language for desktop applications, web applications, mobile applications and enterprise systems. 4. JDK, JRE, AND JVM Introduction To understand how Java programs are developed and executed, it is important to know about JDK (Java Development Kit), JRE (Java Runtime Environment), and JVM (Java Virtual Machine). These three are the core components of Java Kit Tools (Compiler, Debugger, Javadoc, etc.) platform. 1. JVM (Java Virtual Machine) Relationship between JDK, JRE and JVM « JVM is the heart of Java. r « tis an abstract machine that provides runtime a D ue; t Kit) environment in which Java byte code is executed. a. = e JVM is platform dependent. JRE e It performs the following main tasks: (Java Runtime Environment) ¥ Loads code a + v¥ Verifies code JVM a Bisa: (Java Virtual Machine) v¥ Provides runtime environment Executes Java byte code ee eld dle ella and provides runtime 2. JRE (Java Runtime Environment) enorme \ e JRE is a part of JDK. ¢ It provides the libraries, other files and JVM Java Class Libraries that are required to run a Java program. e tis used to run Java applications. Other Supporting Files e It does not contain development tools (compiler, debugger etc.). aes ee Rg gee ag are pens adc ane Development Tools 3. JDK (Java Development Kit) (javac, java, javadoc, jar, etc.) e JDK is a superset of JRE. ‘ « lItis used to develop, compile, debug and run Other Utilities Java programs. e It contains JRE + development tools. 3 Zs e Itis used by developers. Difference between JDK, JRE and JVM Component Full Form Contains | Purpose Included In JVM Java Virtual Machine Class Loader, JRE Byte Code Verifier, Executes Java Execution Engine, byte code l | Runtime Area JRE | Java Runtime | JVM + Core Libraries Provides environment JDK | Environment | + Other Supporting Files to run Java programs JBK | Java Development JRE + Development | Used to develop, compile, — (Top level) debug and run Java programs Example How it Works? 1 /f Simple Java Program 1. The .java file is compiled by JDK (using javac compiler). Du Melase Hello 2. It = .class (byte code) file. 3 public static void main(String[] args) { 3. JVM (inside JRE) loads and executes the byte code. 4 System.out.printlh("Hello, JVM!"); 4. Output is displayed on the screen. 5 3 Seg Output i 8 Hello, JVM! 9 e Users need only JRE to run Java applications. v+y Key Points @ e Developers use JDK for writing and developing Java programs. 5. JAVA PROGRAM STRUCTURE Introduction Every Java program follows a specific structure. The structure defines the basic layout of a Java program and the order in which its components appear. 1. Basic Structure Example: Java Program Structure A simple Java program consists of —————————— SS = —_ ———_—— the following parts: 1 // 1. Documentation Section (Single line comment) (1) Documentation Section (Optional) 2 /* ) 0 Used to write comments about the program. 3 This program prints "Hello, Java!" This i 1ti-1li it. (2) Package Statement (Optional) 4 is is a milti-line commen Used to declare the package to which 5 */ the class belongs. 6 package mypackage; // 2. Package Statement (3) Import Statement (Optional) 7 . “ Used to import classes and packages 8 import java.util.*; // 3. Import Statement fram other packages. |— 9 \+ 4) Class Declaration 10 public class Hello { // 4. Class Declaration Every Java program must have at least one class. - L baa © main() Method 12 public static void main(String[] args) { // 5. main() Method This is the entry point of any Java program. 13 // 6. Statements JVM starts execution from this method. 14 System.out.println("Hello, Java!"); }+—_®8 + @ Statements Actual instructions or logic of the program. ae } 16 + @ Comments Used to provide explanations. They are ignored by the compiler. ~! rd & Y Note: Semicolon (;) is used to end a statement in Java. 2. Explanation of Structure ( ] | Component | Description Example Comments that describe the program. // This is a comment D tation Secti i ate ae It can be single line (//) or multi-line (/* */). /* This is a comment */ Declares the package name. It must be the Package Statement : z first statement in the program. package mypackage; Imports classes or packages required in Import Statement the program. import java.util.*; Defines a class. The class name must be the public class Hello { } Class Declaration : same as the file name. main() Method Entry point of the program. Program execution arietromn ean). public static void main(String[] args) Statements Instructions written inside the main() method. System.out.println("Hello, Java!"); Used to add explanation in the program. They See gtr aye ee. Comments // This is a comment 3. Rules for Writing Java Program * Class name should be the same as the file name. Output * main() method must be public, static and void. * Every statement should end with a semicolon (;). « Java is case-sensitive (e.g., Class and class are different). « Every block of code is enclosed in { }. Hello, Java! Summary | A Java program follows a fixed structure. Understanding this structure is the first step to write any Java program successfully. 4 Topic 7: OPERATORS IN JAVA Definition: Operators are special symbols that perform operations on variables and values. They are used to perform arithmetic, logical, relational and other operations. 1. Arithmetic Operators e Used to perform mathematical calculations. Operator Description Example + Addition a+b = Subtraction a-b * Multiplication a 7b / Division a/b % Modulus (Remainder) a % b 2. Relational (Comparison) Operators e Used to compare two values. It returns boolean result (true or false). r Example: public static public class ArithmeticDemo { int a = 20, b = void main(String[] args) { 35 Addition: 25 Division: 4 System.out.println("Addition: "+ (a + b)); System.out.println("Subtraction: " + (a - b)); System.out.println("Multiplication: " + (a * b)); System.out.println("Division: "+ (a / b)); System.out.println("Modulus: " + (a % b)); } } Output: Subtraction: 15 Modulus: @ Multiplication: 100 ~ Example: Operator Meaning public class RelttionalDemo { | public static void main(String[] args) { a Equal to int a = 10, b = 20; l= Not equal to System.out.println(a == b); // false > Greater than System.out.println(a !=b); // true System.out.println(a < b); ff true < Less than System.out.println(a > b); // false = System.out.println(a <= b); // true 25 Greater than or equal to System.out.println(a >= b); // false <= Less than or equal to ; } a | Output: false true true false true false | 3. Logical Operators > 3 P Example: e Used with boolean expressions. i i P public class LogicalDemo { Output: 3 public static void main(String[] args) { Operator Meaning boolean x = true, y = false; false true && Logical AND . System.out.println(x && y); // false false || Logical OR System.out.println(x || y); // true System.out.println(!x); // false ! Logical NOT } 3 4. Assignment Operators & Unary Operators System. out.println({a++); System.out .printIn(--a); System.out.println(a--); 7. instanceof Operator « Checks whether an object belongs to a particular class. Operator Example Operator Description = a = 10 ++ Increment ee ate 5. (eeia’e's) -- Decrement + Unary Plus = His g ‘Gs ae 24 - “Unary Minus io a*= 3 (a=a* 3) ! Logical NOT f= a fs 2 (a=a/ 2) Example: o he a= 2 (a =a % 2) | Sault aFitibcen: // 6 (pre-increment) // 6 (post-increment) // & (pre-decrement) f/f 5 (post-decrement) 6. Ternary Operator + Also called conditional operator. Syntax: condition ? valuel : valuez; | Example: int a = 10, b = 20; (a > b) 7? a : b: System.out.println("Maximum = " + max); int max = Output: | Maximum = 28 | 8. Operator Precedence (High to Low) E le: tee (ei 2 3 4 5 6 7 8 9 10 String s = "Java"; z s 3 Z Assi t AND gnment | System.out.println(s instanceof String); // true Q mney a fae += Relational Enpolity toa Logeal OR Tatton y Se L , ++ -- | <, >, <=, >= =:,!= Bk {| ? aa Note: Operators make our programs simple, efficient and easy to read. EE} CONTROL STATEMENTS (if, switch, loops) Control statements are used to control the flow of execution in a Java program. They allow a program to make decisions and repeat actions. 1. if Statement The if statement is used to execute a block of code if a given condition is true. if(condition) { // code to be executed if condition is true } 2. if-else Statement The if-else statement is used to execute one block of code if the condition is true and another block if it is false. if(condition) { // code if true } else { } // code if false 3. else-if Ladder The else-if ladder is used to check multiple conditions. if(condition1) { // code 1 } else if(condition2) { // code 2 } else { } ff code n 4. switch Statement The switch statement is used to execute one block of code from multiple options based on the value of a variable. switch(variable) { case valuel: ff code 1 break; case value2: // code 2 break; default: // default code } 5. Loops Loops are used to execute a block of code repeatedly. © for Loop for(initialization; condition; update) { // code to be executed } ¢ while Loop while(condition) { // code to be executed } e do-while Loop do { /f code to be executed } while(condition); FLOW OF CONTROL STATEMENTS Start Condition True Code | if-else else-if | switch | | loops | Ladder
& Variable True True case 1 for Condition 2 Block of get a or Code 1 rato) while Ces a or False ¥ ‘ do-while + t Block of rH oe Code 2 conditi (Pee default Else Block End agile 7 “@: * for, while, do-while are used for repetition. « Control statements help in decision making and repetition. Example « if, if-else, else-if, switch are used for decision making. int num = 10; if(num > 6) { System.out.println("Positive Number"); } else if(num < 6) { System.out.println("Negative Number"); } else { } System.out.println("Zero"); In Java, a String is a sequence of characters. Java provides two classes to work with strings: String (immutable) and StringBuffer (mutable). 1. STRING IN JAVA e String is a class that represents a sequence of characters. © Strings are immutable, i.e., once created cannot be changed. * String objects are stored in the String Constant Pool. Syntax: String sl = “Hello”; // using string literal | String s2 = new String("“Hello”); // using new keyword 2. COMMONLY USED STRING METHODS Method length() charAt(int index) Description Returns the length of the string. Returns the character at the specified index. concat(String str) Cenecatenates the specified string te the end. equals(Object obj) Compares this string with the specified object. equalsignoreCase(String str) Compares ignoring case considerations. substring(int beginindex) Returns substring starting from beginindex. substring(int beginindex, int endindex) Returns substring from beginindex to endindex-1. toUpperCase() Converts string to uppercase. toLowerCase() Converts string to lowercase. trim() Removes leading and trailing spaces. replace(char old, char new) Replaces all occurrences of old with new. split(String regex) Splits the string based on the given regex. 3. EXAMPLE: STRING IN JAVA 1 public class StringExample { | 2 public static void main(String[{] args) { | 3 Strings =" Hello Java “; 4 System.out.println("Original String: '" +s + """); 5 System.out.println(“Length: “ + s.length()); | 6 System.out.println("“Char at index 1: " + s.charAt(1)); 7 System.out.println("Uppercase: " + s.toUpperCase()); 8 System.out.println("Lowercase: " + s.toLowerCase()); ) 9 System.out.println("Trimmed: ‘" + s.trim() + "'"); 1e System.out.println("Substring(2,7): " + s.substring(2,7)); il System.out.println("Replace a with @: " + | s.replace(‘a', ‘@')); | 23 } 14} Output: Original String: " Hello Java * Length: 13 Char at index 1: Uppercase: HELLO JAVA Lowercase: hello java Trimmed: ‘Hello Java‘ Substring(2,7): llo J Replace a with @: Hello J@vé Ca - - KEY TAKEAWAYS * Use String when the value of string remains constant. e Use StringBuffer when the value of string changes frequently. 10. STRINGS AND STRING BUFFER IN JAVA 4. STRING BUFFER IN JAVA « StringBuffer is a mutable class, i.e., its content can be changed. « It is thread-safe (synchronized). « Used when we need to modify the string frequently. Syntax: StringBuffer sb = new StringBuffer("Hello"); J 5. COMMONLY USED STRINGBUFFER METHODS Method Description append(String str) Appends the specified string. insert(int offset, String str) Inserts the string at the specified position. delete(int start, int end) Deletes characters from start to end-1. replace(int start, int end, String str) Replaces characters from start to end-1, reverse() Reverses the sequence of characters. capacity() Returns the current capacity. length() Returns the length of the string. charAt(int index) Returns the character at the specified index. 6. EXAMPLE: STRINGBUFFER IN JAVA 1 = public class StringBufferExample { 2 public static void main(String[] ares) { 3 StringSuffer sb = new StringBuffer("“Hello"); 4 5 sb.append(" World"); /f Hello World 6 System.out.println("“After append: “ + sb); a 3 sb.insert(S, “, Java"); // Hello, Java World 9 System.out.printin("“After insert: “ + sb); 16 11 sb.delete(S, 11); // Hello World 12 System.out.printin("After delete: “ + sb); 13 14 sb.replace(6, 11, “Java"); /f Hello Java 15 System.out.println("After replace: “ + sb); 16 17 sb.reverse(); // aval] olleH 18 System.out.println(“After reverse: “ + sb); 19 +} ze 4} Output: After append: Hello World After insert: Hello, Java world After delete: Hello World After replace: Hello Java After reverse: ava] olleH 7. STRING vs STRINGBUFFER Feature String | StringBuffer Mutability Immutable (cannot be changed) Mutable (can be changed) Thread Safety | Not thread-safe Thread-safe (synchronized) Performance Slower when modification is frequent Faster for frequent modifications Memory Creates new object on modification Modifies the same object Usage Used when string is constant Used when string changes frequently « String is immutable, StringBuffer is mutable. * StringBuffer is thread-safe and more efficient for modifications. 11. METHODS AND RECURSION IN JAVA In Java, a method is a block of code that performs a specific task. It improves code reusability, modularity and readability. Recursion is a technique where a method calls itself to solve a problem. 1. METHODS IN JAVA 6. RECURSION IN JAVA A method is a collection of statements that are grouped together Recursion is a technique where a method calls itself to solve a to perform an operation. smaller instance of the same problem. Benefits of Methods: Characteristics of Recursion: * Code reusability * Method calls itself. * Improves readability * Must have a base condition (stopping condition). | « Easy maintenance e Every recursive call should bring the problem closer to base * Modularity (divide large problem into smaller parts) condition. 2. TYPES OF METHODS 7. SYNTAX OF RECURSION Type Description returnType methodName(...) { make ikea | ae aie fe ie | if (base condition) { 1. Built-in Methods revided by Java API. Example: Systerm.out.println() | a araiveluen Hibese case 2. User-defined Methods Created by the programmer. } else { // recursive call 3. SYNTAX OF METHOD methodName(. ..); a } returnType methodName(parameterList) { } // body of the method 8. EXAMPLE: FACTORIAL USING RECURSION return value; // (if return type is not void) } 1 public class FactorialExample { 2 // recursive method « returnType — data type of value returned by method 3 static long factorial(int nv) { (void if nothing returned) 4 if (n == @ || n == 1) // base case « methodName - name of the method 5 return 1; * parameterList —- list of parameters (can be empty) 6 else Fi return n * factorial(m - 1); // recursive call * return value — value returned by the method a } ET] 4. TYPES OF USER-DEFINED METHODS . F js 16 public static void main(String[] args) { Type Description 16 int num = 5; 12 long fact = factorial(num); 1. Method with no Does not accept parameters and 13 System.out.println("Factorial of "+ num +" = " + fact); parameters and no 14 } does not return any value. return value re | oo amodiath Accepts parameters but does parameters and no Output: not return any value. return value Factorial of 5 = 120 3. Method with no Does not accept parameters but Parameters and tut a Sa | return value ae em 9. RECURSION CALL FLOW (Factorial of 5) 4. Method with [ i | oe and Acesp ts ipatemeters and fartoelts) = ———® Return 120 E returns a value, | = 5 * factorial(4) 4 return value — 1 = l (final result) Trace Table i} F = 1 T 5. EXAMPLE OF METHODS f. ial(4 ! f ial ectanalt 4) ;- Been a n | factorial(n) 1 public class MethodExample { =. 4 * factorial(3) Ne 5 120 2 // Method with parameters and return value } I 3 static int add({int a, int b) { r 5 1 4 24 4 int sum = a + b; factorial(3) | Return 6 5 return sum; | = 3 * factorial(2) 4 \ J 4 3 6 6 } a i i : H 8 public static void main(String[] args) { | factorial(2) ' 2 2 3 int x = 10, y = 20; | 4 Return 2 , ; =9* i 3 Fi | = 2 * factorial(1) 4 1 1 18 int result = add(x, yy); // calling method \ 1 16 System.out.println("Sum = “ 4 result); + i} 11 } i op x. (a) 7 ! 8 1 | 15} a = ———» Return 1 | =1 (base case) Output: 7 ; ‘ Sum = 3@ ~ ! ra Y_ KEY TAKEAWAYS * Methods help in code reusability and better organization. * Every recursive solution must have a base condition. « Methods can accept parameters and return values. « Use recursion carefully to avoid infinite calls (StackOverflowError). « Recursion solves problems by breaking them into smaller « Recursion is useful for problems like factorial, Fibonacci series, subproblems. Tower of Hanoi, tree traversals, etc. 13. EXCEPTION HANDLING IN JAVA Exception Handling is a mechanism to handle runtime errors (exceptions) so that the normal flow of the program can be maintained. It helps in preventing abnormal termination of the program. 1. What is an Exception? * An exception is an unwanted or unexpected event | that occurs during the execution of a program. | * It disrupts the normal flaw of the program. Examples: * Division by zero * Array index out of bounds * File not found « Null pointer reference 4. Example: Division by Zero 2. Types of Exceptions Type Description Checked at compile-time. Must be handled using try-catch or declared using throws. Examples: IOException, SQLException Checked Exceptions Checked at runtime. Occurs due to programming errors. Examples: ArithmaticException, NullPointerException Unchecked Exceptions Serious problems that cannot be handled. Examples: QutOfMemoryError, StackOverflowError Errors 5. try-catch-finally Block 1 public class DivisionExample { 2 public static void main(String[] args) { try { 3 int a= 18, b = @, result; if code that may throw exception 4 try { } 5 result = a/b; // may throw exception catch (ExceptionType e) { 6 System.out.printin(“Result: “ + result); ff handle exception 7 } catch (ArithmeticException e) { } f:} System.out.println(“Cannot divide by zero!l"); Finally { 3 System.out.printin(“Exception: “ + e); if code that always executes 9 } } 1¢ , 10} * finally block is executed whether an exception Output: occurs or not. Cannot divide by zero! Exception: java. lang.ArithmeticException: / by zero 7. Multiple catch Blocks try { f/ risky code } eatch (ExceptionTypel e1) { #/ handle exception 1 catch (ExceptionType2 e2) { #/ handle exception 2 } catch (ExceptionTypeN en) { ff handle exception N ) * Catches different types of exceptions separately. * Specific exceptions must be caught before general exceptions. 10. throws Keyword * Used to declare that a method might throw an exception. * The exception is passed to the caller method. Syntax: * It is used to close resources like files, database connections, etc. 8. Example: Multiple catch 1 public class MultipleCatchExample { 2 public static void main(String[] args) { 3 int a[] = new int[S); 4 try { s int x = 18 / 8; 6 int y = a(16); 7 } catch (ArithmeticException e) { a Systea.out.printin(“Arithmetic Exception: “ + ©); 9 } cateh (ArrayIndeaQutofBoundsException e) { 18 Systes.out .printIn(“Array Index Exception: * + e); 11 } catch (Exceptien e) { 12 Systes.out.printin(“Some other Exception: " + e); 13 » 3 14 } 16 (OF Output: Arithmetic Exception: java.lang.ArithmeticException: / by zero 11. Custom Exception * We can create our own exceptions by extending Exception class, « Useful to represent application specific errors. returaType methodName() throws ExceptionType 1 class InvalidAgeException extends Exception { Example: 2 InvalidAgeException(string msg) { 3 super (mse); 1 import java.io.*; 4 } 2 public class ThrowsExample { ; 3 static void readFile() throws ToException { 6 ff Usage 4 FileReader fr = new FileReader(“test txt"); 5 } 7 «dif(age < 6) . } 8 throw new InvalidAgeException("Age cannot be negative”); oes Key Takeaways * Exceptions are handled to maintain normal flow of program. « Use multiple catch to handle different exceptions. « Use try-catch to handle exceptions. * finally block always executes. « throw is used to explicitly throw exception. * throws is used to declare exception. 3. try-catch Block try { // code that may throw exception } catch (ExceptionType e) { ff code to handle exception * try: contains code that may throw exception. * catch: catches and handles the exception. + ExceptionType: type of exception to be caught. * @ exception object which contains details about the exception. 6. Example: try-catch-finally 1 = public class Finallyéxample { 2 public static void main(String[] args) { 3 try { 4 int arr[) = (1, 2, 3}; 5 System.out.println(arr[$]); // may throw exception 6 } catch (ArrayIndexOutOfBoundsException ¢) { Fi System.out.printin(“Invalid index!"); 8 } finally { 9 System.out.println("This block always executes."); 10 } uw System. out .println("Program continues. .."); 12 } 14} ‘Output: Invalid index! This block always executes. Program continues... 9. throw Keyword + Used to explicitly throw an exception. * Mostly used in methods to indicate an error condition. ‘Syntax: throw new ExceptionType( “message” ); Example: 1 public class ThrowExample { 2 static void checkAge(int age) { 3 if(age < 18) 4 throw new ArithmeticException(“Not eligible to vote"); 5 ? 12. Common Exception Classes Exception Class Description ArithmeticException Arithmetic errors (e.g., divide by zero) ArrayindexOutOfBoundsException Array index is out of range NullPointerException Using null where object is required NumberFormatException Invalid conversion of String to number Input/Output errors Class not found at runtime IOException ClassNotFoundException * Custom exceptions help in application specific error handling. * Proper exception handling makes the program robust and user-friendly. TOPIC 14: CONSTRUCTORS IN JAVA A constructor in Java is a special member function that is used to initialize objects. It is invoked automatically when an object of a class is created. 1. What is a Constructor? A constructor is a block of code similar to a method. . It is used to initialize the data members of a class. It has the same name as the class. It does not have any return type, not even void. It is called automatically when an object is created using the new keyword. // Default Constructor class ClassName { ClassName() { /f initialization code // Parameterized Constructor class ClassName { ClassName(DataType parameter1, DataType parameter2) { /f initialization code } } 5. How Constructor Works? » When an object is created using new keyword, memory is allocated in heap. ® The constructor is called automatically. » It initializes the object's data members. » After execution of constructor, the object is ready to use. 6. Rules for Constructors Constructor name must be same as class name. Constructor must not have a return type. Constructor is called automatically when object is created. If no constructor is defined, Java provides a default Pw he constructor (no-argument constructor). 5. Constructer can be overloaded. Default Constructor Called Roll No: @ Name: Unknown Parameterized Constructor Called Roll No: 1@1 Name: Satyam Mishra 9. Default Constructor If we do not write any constructor in a class, Java compiler provides a default constructor. . Default constructor has no parameters and an empty body. It initializes object with default values. Note: Constructors are mainly used 2. Types of Constructors 1. Default Constructor (No-argument Constructor) - A constructor with no parameters. - If we do not create any constructor, Java provides a default constructor automatically. 2. Parameterized Constructor - A constructor with parameters. - Used to initialize objects with specific values. 4. Example Program class Student { int rollNo; String name; // Default Constructor Student() { rollNo = @; name = "Unknown"; System. out. println("Default Constructor Called"); } /f Parameterized Constructor Student(int rollNo, String name) { this.rollNo = rollNo; this.name = name; System. out.println("Parameterized Constructor Called”); : void display() { System. out.println("Roll No: " + rollNo); System.out.println("Name: “ + name); } public class ConstructorExample { public static void main(String[] args) { /f Calling default constructor Student sl new Student(); sil.display(); System. out. println(); f/f Calling parameterized constructor Student 5? new Student(1@1, “Satyam Mishra"); s2.display(); } 8. Constructor Overloading (Example) class Rectangle { int Length, width; 58 Rectangle() { #f Default constructor Output: length = @; width = @; | Rectangle({int 1, int w) { #! Parometerized constructor Area = 0 length = 1; width = w; Rectangle(int side) { ff Another constructor Area = length = width = side; Area = 49 void areaf) { System.out.printIn(“Area } “+ (length * width)); } public class QverloadingDemo { public static void main(String[] args) { Rectangle rigs. newiReccanatel)z Rectangle r2 = new Rectangle(5, Rectangle r3 = new Rectangle(7); rl.area(); r2.area(); r3.areal); ff Default 10); // Porameterized ff Anether constructor } } 10. Key Points w Constructor is used to initialize objects. vf It does not have return type. wv It is called automatically. wv It can be overloaded. wv It has same name as class name. to initialize objects. They are a special type of method. v Default constructor is provided by Java if not defined. 16. COLLECTION FRAMEWORK IN JAVA The Collection Framework in Java provides a set of interfaces and classes to store and manipulate groups of objects. It is a part of java.util package. 1. What is Collection Framework? 2. « It is a unified architecture for representing and manipulating collections. * It provides data structures like List, Hierarchy of Collection Framework Set, Queue, Map, etc, Collection + « |t improves program performance | and code reusability. + = ) Set f Queue ) ee aoe) « It is part of java.util package. [ ArrayList 3 | HashSet ) | PriorityQueue | ie a ( LinkedList } | LinkedHashSet Deque LinkedHashMap + =s ( Vector 7 TreeSet ArrayDeque + oo sae) ( ) 4. Example: ArrayList LinkedList Set Interface Hashtable J List Interface An ordered collection that allows duplicate elements, Maintains insertion order, Provides index-based access. Common Methods add(E e) add(int index, E e) Description Adds element at the end Adds element at specified position get(int index) Returns element at index set(int index, E e) Replaces element at index removelint index) Removes elernent at index size() Returns number of elements. contains(Object o) Checks if element exists 6. Queue Interface * A-collection designed for holding elernents prior to processing. * Follows FIFO (First In First Out) principle. ‘Common Methods Description offer{E e) Inserts element poll() Retrieves and removes head peek() Retrieves head isEmpty() Checks if queve is empty Example: LinkedList as Queue 1 QuevecInteger> q = new LinkedList<>(); 2 g.offer(18); 3 q.offer(28); 4 q.offer(3@); 5 System.out.println(q.poll(}); // 18 6 System.out.println(q.peek()); // 28 7 System.out.printin(q); // [26, 30] 9. Comparison of List, Set, Map 1 import java.util.*; * A collection that does not allow duplicate elements. = a. ae { * Does not maintain any particular order tat 1 publ fg stat gyre id \matn( setae) anes)) (except LinkedHashSet and TreeSet). 4 ArrayList list = new ArrayList¢>(); i 5 list.add(“Apple"); «* Useful for unique elernents. 6 list .add(“Banana™); 3 list. add(“Cherry"); Set Implementation Description 8 HashSet Does not maintain insertion order ) System.out.println(“List: “ + list); Uses hash table 16 System.out.println(“Element at index 1: “ F . 2. " 11 + list.get(1)); LinkedHashSet Maintains insertion order 12 TreeSet Stores elements in sorted order 13 list .remove ("Banana"); (Red-Black tree) 13 System.out.println(“After remove: “ + list); 13 ; } Example: HashSet 13 1 HashSet set = new HashSet<>(); 2 set.add(1e); Output: 3 set.add(20); List: [Apple, Banana, Cherry] 4 set.add(1@); // duplicate, not added Element at index 1: Banana 5 set.add( 36); After remove: (Apple, Cherry] 6 System.out .println(set); 7 /f Output: (28, 16, 3¢] (order may vary) 7. Map Interface 8. Example: HashMap * Stores data in key-value pairs, 1° HashMapcInteger, String> map = new HashMap<>(); * Keys are unique, values can be duplicate, 2 map.put(1, “Gne"); * Does not extend Collection interface. ee ae 4 map.put(3, “Three"); Common Methods Description 5 put(K key, V value) ids. key-value pair 6 System.out.println( “Map: + map); 7 System.out.println(“value for key 2: “ + map.get(2)); get(Object key) Returns value for key al imeps removeln} : remove(Object key) Removes key-value pair 9 System.out.println("After remove: “ + map); containsKey(Object key) Checks if key exists keySet() Returns set of keys e utput: values) Returns collection of values P Map: {1=sOne, 2=Two, 3=Three} i Returns number of pairs size() ee Ee Value for key 2: Two After remove: {2=Two, 3=Three} 10. Iterator Interface * Used to iterate over collection elements. * Provides methods: hasWext(), next(), remove(). Example: ArrayListeString? list = new ArrayList<>(); List.add("Aa"); list.add("8"); Iterator it = list.iterator(); whlle(it-hasNext()) { System. out. printIn(it.next()); YOu eww ew } x ,_ KEY TAKEAWAYS * Collection Framework provides ready-to-use data structures. Queue for FIFO, and Map fer key-value pairs. Use List for ordered data, Set for unique data, 11. for-each Loop (Enhanced for Loop) * Simplest way to iterate over collection. * Works with arrays and Collections. Example: 1 for(string s : list) { 2 System.out.println(s); 3 } 7) Output: fis ‘iB Prefer ArrayList over Vector (unless thread safety is needed). Use HashSet for speed, LinkedHashSet for insertion order, and TreeSet for sorted data. Feature List Set Map rh Keys: Not allowed Duplicates Allowed Not allowed Values: All nas No order No order Order Maintains order (HashSet) (HashMap) Scant (LinkedHashSet) Sorted (TreeSet) Access Index based No index Key based Null values Allowed ‘One null One null key (HashSet) Many null values Implementation | ArrayList, HashSet, HashMap, classes LinkedList, Vector LinkedHashSet, LinkedHashMap, TreeSet TreeMap, Hashtable 12. Benefits of Collection Framework > @AOB Improves productivity (pre-built data structures) Reduces programming effort Provides high performance Ensures type safety (Generics) Interoperability among data structures Use lterater and enhanced for loop for traversing collections. Collection Framework is powerful, efficient and flexible. TOPIC 17: POLYMORPHISM IN JAVA The word Polymorphism means “many forms”. In Java, it allows one interface to be used for a general class of actions. _ . ae PSS 1. What is Polymorphism? 2. Types of Polymorphism * It is the ability of an object to take many forms. | Type | Description | Example | I T 7 * A single reference variable can refer to Also called Static Polymorphism. 4 Cc ile Ti objects of different classes. a. oo Achieved by method overloading. | Method Overloading mi ism : * The same method can perform different tasks ene Resolved by compiler. | based on the object that invokes it. pict Also called Dynamic Polymorphism. * It is achieved by method overloading and ae i Achieved by method overriding. Method Overriding method overriding. meget ete Resolved at runtime. | 3. Compile Time Polymorphism (Method Overloading) 4. Run Time Polymorphism (Method Overriding) v Same class, same method name, but different parameter list v¥ Same method name, same parameters, but different implementation (number, type or order of parameters). in parent class and child class. v Return type may or may not be different. ¥ It is also called dynamic polymorphism. v It is also called static polymorphism. ¥ Achieved through inheritance. | Example Program | _ Example Program class Calculator { i class Animal { int add(int a, int b) { void sound() { ; return a + bj System.out.printLn("Animal makes sound"); double add(double a, double b) { } } return a + b; } class Dog extends Animal { int add(int a, int b, int c) { @0verride return a + b + c; void sound() { : } System.out.println("Dog barks"); public class OverloadingDemo { } ; public static void main(String[] args) { Calculator c = new Calculator(); public class OverridingDemo { System.out.printLn("Sum (2 int}: " + c.add(1@, 20)); public static void main(String[] args) { System.out.printLn("Sum (2 double): " + c.add([email protected], 20.5)); Animal a = new Dog(); // Parent reference, Child object System. out.printLln("Sum (3 int): “ + c.add(1@, 20, 38)); a.sound(); f/f Calls overridden method } } u ) } — ——_____—— = K Output: r Sum (2 int): 30 oe Sum (2 double): 31.0 Dog barks Sum (3 int): 60 5. How Runtime Polymorphism Works? 6. Rules for Method Overriding i 1. Method name and parameter list must be same. sound() method Animal a (Reference variable) 2. Return type must be same or covariant (subclass type). new Dog() . Access level cannot be more restrictive. (Object) 3 call 4. Static methods cannot be overridden (method hiding happens). 5. Final methods cannot be overridden. 6 . Private methods cannot be overridden. | JVM decides which method to call Hf at runtime based on the object. 7. Method Overloading vs Method Overriding Feature | Method Overloading Method Overriding Think of a “Remote Control”. T | * The same remote (reference) can control different devices (objects) Same method name, Same method name and ri 5 Definition i any like TV, AC, or Music System. | JaitepenEingcameters: || 2 |» The button “Power” (method) works differently for each device. Where |_In the same class In parent and child class * The remote doesn't know the internal working; it just gives the command, Binding | Compile time | Run time This is Polymorphism! Polymorphism Type | Compile time Run time Inheritance | Not required Required = Rane Wake | poe "ws not be Must, = same or iferen covartan icti | Cannot b TV AC Music System Access Modifier | No restriction eerie ai (Power) (Power) (Power) 9. Key Points @ Polymorphism allows code reusability and flexibility. @ It makes code easier to maintain and extend. @ Compile time polymorphism is achieved by method overloading. @ It is a key feature of Object-Oriented Programming. @ Run time polymorphism is achieved by method overriding. @ It is widely used in frameworks like Collections, I/O, etc. | Note: Polymorphism increases the extensibility of a program. It allows us to write more generic and reusable code. TOPIC 19: Encapasulation is one of the fundamental concepts of Object-Oriented Programming. It is the process of wrapping (binding) data and the methods that operate on data into a single unit, i.e., class, and restricting direct access to some of the object's components. | % 1. What is Encapsulation? Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. It restricts direct access to some of the object's components. It is achieved by using access modifiers and getter and setter methods. It protects the data from unintended changes. 3. How Encapsulation is Achieved? 2. Why Encapsulation? © To achieve data hiding. To improve security and protect data. * To make the code flexible and easy to maintain. To achieve better control over the data. It is a way to achieve abstraction. 4. Access Modifiers in Encapsulation Class // public getter methods public String getName() { return name; } public int getAge() { return age; } // public setter methods public vaid setName(String name) { this.name = name; } public void setAge(int age) { if(age > @) { this.age } else { System.out.printLn("Invalid age"); = age; } } } public class TestEncapsulation { public static void main(String[] args) { Student s new Student(); s.setName("Satyam Mishra"); s.setAge(2@); + s.getName()); + s.getAge()); System.out.println("Name: " System.out.println("Age: “ s.setAge(-5); // will not set invalid age System.out.println("Age after invalid input: 8. Disadvantages 7. Advantages v Better control over data, v Data is hidden from other classes. | v Increases security and data integrity. | (method call overhead). wv Code becomes flexible and easy to maintain. v Achieves abstraction. "+ s.getAge()); ® Requires more code (getters and setters).| ™ May slightly reduce performance ™® Overuse may make code too verbose. Egcapsllatifinits ocbiebediby: Modifier Package Subclass World 1. Declaring the class variables as private. private Yes No No No 2. Providing public getter methods to read the values. default Yes Yes No No 3. Providing public setter methods to modify the values. protected Yes Yes Yes No L public Yes Yes Yes Yes 5. Encapsulation Example class Student { , /f private data members Output: private String name; Name: Satyam Mishra private int age; Age: 20 Invalid age Age after invalid input: 20 Encapsulation Diagram hho Cc lass Student Private Data Members = name Outside - age World Data is Hidden Public Methods + getName() + setName() + getAge() + setAge() pe rrremet/ Access via Public Methods 6. Key Points * The fields of a class should be declared private. * Access to the fields is provided through public methods (getters and setters). * It is also known as data hiding. « Encapsulation allows you to make the class read-only or write-only as per requirement. * It improves the maintainability and security of code. 9. Interview Questions 1. What is encapsulation in Java? 2. How is encapsulation achieved in Java? 3. What are the advantages of encapsulation? 4. Can we achieve encapsulation without using getters and setters? | 5. What is the difference between encapsulation and abstraction? TOPIC 20: INTERFACES IN JAVA An interface in Java is a blueprint of a class. It has static constants and abstract methods only. It is used to achieve abstraction and multiple inheritance (of type). . What is an Interface? * An interface is a reference type in Java. * It contains only abstract methods (methods without body) and constants. Interface cannot be instantiated. * It is declared using the keyword interface. | © A class uses the interface by implementing it. Why use Interface? Achieves 100% abstraction. Supports multiple inheritance (of type). Provides a standard structure. Improves code flexibility and maintainability. ce ee Loose coupling between objects. 3. Syntax of Interface interface InterfaceName { // constant declaration dataType CONSTANT_NAME = value; // abstract method declaration returnType methodName(parameterList) ; 4. Important Points AIL methods in interface are public and abstract by default. All variables in interface are public, static and final by default. A class implements an interface using the implements keyword. A class can implement multiple interfaces (comma separated). An interface can extend multiple interfaces. YoY aN Ve ¥ ay An interface cannot be instantiated. 7. Interface Extending Another Interface interface Father { void show(); } interface Mother extends Father { void display(); } class Child implements Mother { public void show() { System.out.printIn("“Show method"); } public void display() { System. out.println("Display method"); 9. Key Points to Remember ¥ Interface contains only abstract methods and constants. v Methods are public and abstract by default. 5. Example Program // Interface interface Animal { void sound(); /f/ abstract method 3 // Class implementing interface class Dog implements Animal { public void sound() { /f method body System.out.printin("Dog barks"); } } // Test class public class InterfaceDemo { public static void main(String[] args) { Animal a = new Dog(); f/f upcasting a.sound(); f/f calling method } } Interface Classes Objects Velwface (ee) Vehicle por start 60 — Car € = new Cord); void start); Ko € ~ void stop(); x) ‘ y NS] Bike rou) 9 Bike b = new Biket): | eee ele) w Variables are public, static and final by default. wv Achieves abstraction and multiple inheritance. 6. Interface with ple Classes interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { public void draw() { System.out.print1In("Drawing Rectangle"); } 2 class TestShape { public static void main(String[] args) { Shape s; s = new Circle(); s.draw(); s = new Rectangle(); s.draw(); 10. Interview Questions What is an interface in Java? What is the use of interface? Can an interface have a method body? ‘Can we create an object of an interface? What is the difference between class and interface? Can a class implement multiple interfaces? Can an interface extend another interface? What are the rules of interface? 9. What is the use of implements keyword? 10. Give a real life example of interface. SOY CUR Bore Note: Interfaces are used to achieve abstraction, support multiple inheritance and design loosely coupled and flexible systems.