This comprehensive Java resource covers fundamental programming concepts through advanced topics. It begins with basic syntax, control flow (loops and conditionals), and object-oriented programming principles like encapsulation, inheritance, polymorphism, and abstraction. The material further explores advanced Java features such as exception handling, multithreading, collections (ArrayList), and string manipulation. File operations, interfaces, abstract classes, and generic types are also explained. The resource also discusses data structures (stacks, queues, linked lists, arrays, sorting, searching) and provides insights into becoming a Java developer, including necessary skills and career prospects. Finally, it includes examples of Java projects like an ATM, text editor, and signup form.
Java Programming Study Guide
Quiz
- Explain the concept of platform independency in Java. Why is Java known as a “Write Once, Run Anywhere” language?
- What is multi-threading in Java, and what are its benefits? Provide a brief example of a scenario where multi-threading would be advantageous.
- Describe the difference between pre-increment/decrement and post-increment/decrement unary operators in Java. Illustrate with a short code snippet.
- Explain the purpose of relational operators in Java. Give three examples of relational operators and describe the conditions under which they would evaluate to true.
- What is the primary function of logical operators in Java? Describe the behavior of the && (AND) and || (OR) operators.
- Explain the functionality of the ternary operator in Java. Provide a simple example demonstrating its usage and the benefit it offers.
- Describe the difference in behavior between a while loop and a do-while loop in Java. When might you choose to use one over the other?
- What is the purpose of the break statement within a switch block in Java? What happens if a break statement is omitted?
- Explain the concept of nested if statements in Java. Provide a simple scenario where using a nested if statement would be appropriate.
- What is the role of control statements in Java? List three different types of control statements discussed in the source material.
Quiz Answer Key
- Platform independency in Java means that a Java program can run on any operating system that has a compatible Java Runtime Environment (JRE) installed. Java achieves this because, upon compilation, the code is translated into platform-independent bytecode, rather than machine-specific code. This bytecode can then be executed by any JRE, making Java a “Write Once, Run Anywhere” language.
- Multi-threading in Java is a feature that allows a program to execute multiple parts (threads) concurrently. The benefit of multi-threading is that it can improve performance by utilizing the same memory and resources to perform multiple tasks simultaneously. For example, while typing in a word processor, a separate thread can be used to perform spell checking in the background.
- Pre-increment/decrement operators modify the value of a variable before it is used in an expression, while post-increment/decrement operators modify the value after it has been used.
- int a = 5;
- int b = ++a; // pre-increment: a becomes 6, b is assigned 6
- int c = 5;
- int d = c++; // post-increment: d is assigned 5, then c becomes 6
- Relational operators in Java are used to compare two operands and determine the relationship between them. They return a boolean value (true or false). Examples: > (greater than) evaluates to true if the left operand is greater than the right; < (less than) evaluates to true if the left operand is less than the right; == (equal to) evaluates to true if both operands are equal.
- The primary function of logical operators in Java is to perform logical operations on boolean operands, combining or negating boolean values. The && (AND) operator returns true if and only if both of its operands are true. The || (OR) operator returns true if at least one of its operands is true.
- The ternary operator in Java is a shorthand if-else construct that allows you to write a conditional expression in a single line. Its syntax is condition ? value_if_true : value_if_false. For example, int min = (a < b) ? a : b; assigns the smaller of a and b to min. The benefit is more concise code for simple conditional assignments.
- A while loop in Java evaluates its condition before executing the loop body. If the condition is initially false, the loop body will never be executed. A do-while loop, on the other hand, evaluates its condition after executing the loop body. This guarantees that the loop body will be executed at least once, even if the condition is initially false. You might use a do-while loop when you need to perform an action at least once before checking a condition.
- The break statement within a switch block in Java is used to terminate the execution of the switch statement and transfer control to the statement immediately following the switch block. If a break statement is omitted, the execution will “fall through” to the next case block, even if its value does not match the switch expression.
- Nested if statements in Java involve placing one if statement (or if-else statement) inside another if statement (or else block). This allows for more complex decision-making based on multiple conditions. A simple scenario would be checking if a number is positive, and then, if it is, further checking if it is also even or odd.
- Control statements in Java are used to manage the flow of execution within a program, determining which statements are executed and in what order. Three different types of control statements discussed in the source material are if-else statements, while loops, and for loops.
Essay Format Questions
- Discuss the key features of the Java programming language as outlined in the provided source. Analyze how these features contribute to Java’s popularity and suitability for various software development tasks.
- Explain the different categories of operators available in Java, providing examples of each type. Discuss how operators are used to manipulate data and perform computations within Java programs.
- Describe the various control flow statements in Java, including conditional statements and loops. Illustrate with examples how these statements enable programmers to create programs with complex logic and repetitive actions.
- Compare and contrast the different types of loops available in Java (while, do-while, for). Discuss the scenarios in which each type of loop is most appropriate and provide examples to support your reasoning.
- Analyze the concepts of exception handling in Java, including the use of try, catch, and finally blocks. Discuss the importance of exception handling for creating robust and reliable Java applications.
Glossary of Key Terms
- Platform Independency: The ability of a software program to run on any operating system or hardware platform without requiring significant modifications.
- Bytecode: The intermediate code produced by the Java compiler after compiling the source code. It is platform-independent and executed by the Java Virtual Machine (JVM).
- JRE (Java Runtime Environment): A software package that contains everything needed to run Java programs, including the JVM and supporting libraries.
- JDK (Java Development Kit): A software development kit that includes the JRE, a compiler (javac), and other development tools needed to create, test, and debug Java applications.
- Multi-threading: A programming technique that allows multiple parts of a program to run concurrently within a single process, improving performance and responsiveness.
- Operator: A special symbol that performs a specific operation on one or more operands (variables or values).
- Unary Operator: An operator that acts on a single operand (e.g., increment ++, decrement –, negation -).
- Arithmetic Operator: An operator that performs mathematical calculations (e.g., addition +, subtraction -, multiplication *, division /, modulus %).
- Shift Operator: An operator that shifts the bits of an operand to the left or right by a specified number of positions (<<, >>).
- Relational Operator: An operator that compares two operands and determines the relationship between them, returning a boolean value (e.g., >, <, ==, !=, >=, <=).
- Bitwise Operator: An operator that performs operations at the level of individual bits of the operands (e.g., & (AND), | (OR), ^ (XOR)).
- Logical Operator: An operator that performs logical operations on boolean operands (e.g., && (AND), || (OR), ! (NOT)).
- Ternary Operator: A conditional operator that takes three operands (condition ? value_if_true : value_if_false).
- Assignment Operator: An operator that assigns a value to a variable (e.g., =, +=, -=, *=, /=).
- Control Statement: A statement in a programming language that determines the flow of execution of the program (e.g., if-else, while, for, switch).
- Conditional Statement: A control statement that allows the program to execute different blocks of code based on whether a certain condition is true or false (e.g., if, else if, else, switch).
- Loop: A control statement that allows a block of code to be executed repeatedly until a certain condition is met (e.g., while, do-while, for).
- break Statement: A control flow statement used to immediately terminate the execution of a loop or a switch statement.
- Nested if Statement: An if statement that is placed inside another if statement or an else block.
- Robust: A characteristic of a program that indicates its ability to handle errors and unexpected input gracefully, preventing crashes or incorrect behavior.
- Exception Handling: A mechanism in programming languages to deal with runtime errors or exceptional conditions, allowing the program to recover or terminate gracefully.
- Compile-time Error: An error that is detected by the compiler during the process of translating the source code into machine code or bytecode.
- Runtime Error: An error that occurs during the execution of a program.
- Garbage Collector: An automatic memory management process in Java that reclaims memory occupied by objects that are no longer in use.
Java Programming Concepts: A Comprehensive Overview
Document Review: Java Programming Concepts and Features
This briefing document summarizes the main themes and important ideas and facts presented in the provided source, “002-Java_Full_Course_in_10_Hours__-03-24-2025.pdf.” The source covers fundamental aspects of the Java programming language, including its core features, operators, control statements, data structures, object-oriented principles, exception handling, file handling, threads, regular expressions, networking, and practical examples.
**I. Core Features of Java:**
The document begins by highlighting several key features of Java:
* **Platform Independence:** Java follows the “Write Once, Run Anywhere” (WORA) principle. Unlike languages like C or C++, Java code is compiled into **bytecode**, which is platform-independent and can be executed on any machine with a Java Runtime Environment (JRE). “unlike other programming languages such as C or C++ Etc which are compiled into platform specific machines Java is guaranteed to be right once Run Anywhere language on compilation Java program is compiled into bite code this bite code is platform independent and can be run on any machine plus this bite code format also provides security any machine with Java runtime environment can run Java programs.”
* **High Performance:** Although Java is an interpreted language and inherently slower than compiled languages like C++, it achieves high performance through the use of a **Just-In-Time (JIT) compiler**. “Java is an interpreted language so it will never be as fast as a compile language like C or C++ but just Java enables high performance with the use of just in time compiler so here Java provides us high performance.”
* **Multi-threading:** Java supports multi-threading, allowing programs to perform multiple tasks concurrently by utilizing the same memory and resources. “Java multi-threading feature makes it possible to write a program that can do many tasks simultaneously the benefit of multi-threading is that it utilizes the same memory and other resources to execute multiple threats at the same time like while typing grammatical errors are checked along.”
* **Security:** Java is considered a secure language, enabling the development of virus-free and tamper-free systems. Java programs run within the JRE with limited interaction with the host operating system. “when it comes to Security Java is always the first choice with Java secure features it enables us to develop virus free and temper free systems Java program always runs in a Java runtime environment with almost null interaction with host operating system hence it is most secure.”
* **Portability:** The cross-platform nature of Java makes its code highly portable. “the crossplatform feature enables the Java code to be highly portable.”
* **Object-Oriented:** Java is based on the object-oriented programming (OOP) model, where everything is treated as an object with data and behavior. This facilitates extensibility. “In Java everything is an object which has some data and behavior Java can be easily extended as it is based on objectoriented programming model.”
* **Robustness:** Java aims to eliminate error-prone code through compile-time and runtime error checking. It features automatic garbage collection for memory management and exception handling for mishandled exceptions. “Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error checking and runtime error checking but the main areas in which Java improvised were memory management and mishandled exceptions by introducing automatic garbage collector and exception handling.”
* **Availability:** JDK versions are available for various operating systems like Windows, Linux, and macOS. “in open jdk and the jdk versions are also available for all the types of operating systems such as Windows Linux Mac and many other flavors of Linux.”
**II. Operators in Java:**
The document details various types of operators in Java, explaining their functionality and providing simple code examples:
* **Unary Operators:** Operate on a single operand (e.g., increment `++`, decrement `–`, negation `-`). Examples demonstrate pre-increment, post-increment, pre-decrement, and post-decrement.
* **Arithmetic Operators:** Perform basic mathematical operations (+, -, \*, /, %). Examples show addition, subtraction, multiplication, division, and modulus. “Java athematic operators are used to perform addition subtraction multiplication and division they act as basic mathematic operations.”
* **Shift Operators:** Shift bits to the left (`<<`) or right (`>>`) by a specified number of positions. An example illustrates left shift operations and how binary representation is affected. “the shift operator is used to shift the bits in the value to the left or right side of the specific number of times we have two types of shift operators which are left shift operator and the right shift operator the left shift operator moves the specific number of bits towards the left side and the right shift towards the right side.”
* **Relational Operators:** Compare operands and return a boolean value (e.g., <, >, <=, >=, ==, !=). An example compares if `a` is less than `b` and `c`. “the Java relational operator is used to compare the operant on both the sides of the relational operator this particular operator judge whether one of the operant is greater or lesser or equal or not equal to the other operator.”
* **Bitwise Operators:** Perform operations on individual bits of operands (&, |, ^, ~, <<, >>, >>>). An example demonstrates bitwise AND and post-increment. “basically the bitwise operator is applied on the bits for example if we provide a number to the variable that particular number will be converted into binary format and after that the operation will be applied on the bits one by one.”
* **Logical Operators:** Combine boolean expressions (&& – AND, || – OR, ! – NOT). The relational operator example is extended to include the logical AND operator. “The Logical operators are the operators which are applied on both the ends or both the operant so the basic logical operators supported in Java programming language are and or and not the and operator is used to perform logical operation on two operant and it will result in a Boolean result so to become a true Boolean result and should be having both the operant as true and in order to result a True Value either one of the operant should be true and when it comes to not not is just a simple logical operator dat which negates the existing value that means if the value is true then after the not operation the value will be converted into false.”
* **Ternary Operator:** A shorthand for a simple if-else conditional expression (`condition ? value_if_true : value_if_false`). An example finds the minimum of two numbers using the ternary operator. “the ternary operator is simple but highly powerful operator used in Java programming language this particular ternary operator will reduce the code length to one line.”
* **Assignment Operators:** Assign values to variables (=, +=, -=, \*=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=). An example demonstrates simple assignment and compound assignment (addition and subtraction). “the assignment operators used in Java programming language are simply used to allocate the resultant memory into the variable which is located in the left side of the operant the basic assignment operators used in Java programming language are equals to and double equals to.”
**III. Control Statements in Java:**
The document explains and provides examples for various control flow statements in Java:
* **If Statement:** Executes a block of code if a specified condition is true. An example demonstrates a simple `if-else` statement to check if a number is greater than 20. “if the condition specified as true the if block will be executed otherwise the else block will be executed.”
* **While Loop:** Repeatedly executes a block of code as long as a specified condition is true. An example prints numbers from 5 to 15 with an increment of 2. “evaluates a certain condition if the condition is true then the code is executed the process is continued until the specific condition turns out to be false the condition to be specified in while loop must be a Boolean expression.”
* **Do-While Loop:** Similar to the `while` loop, but the loop body is executed at least once before the condition is checked. An example initializes a variable to 20, prints it once, increments it, and then checks if it’s less than or equal to 20 (resulting in a single execution). “the condition of the do V Loop is evaluated after the execution of the loop body this guarantees that the loop is executed at least once.”
* **For Loop:** Executes a block of code a specific number of times. An example prints numbers from 1 to 10. “used to iterate and evaluate a code multiple times when the number of iterations is known by the user it is recommended to use the fall Loop.” It highlights the three parts of a `for` loop: declaration, condition, and increment/decrement.
* **Switch Case:** Executes one block of code among many possible blocks based on the value of an expression. The document notes important points about `switch` statements, such as the use of `break` to terminate the statement sequence and the permissibility of constant case values. “used to execute a single statement for multiple conditions… certain points must be noted while using the switch state M which are one or n number of case values can be specified for a switch expression case values that are duplicate or not permissible a compile time error is generated by the compiler if unique values are not used next the case value must be a literal or a constant variables are not permissible the last condition is usage of break statement is made to terminate the statement sequence it is optional to use the statement.”
The document then proceeds to provide practical examples of `if-else-if` (ladder), nested `if`, ternary operator usage as a conditional statement, and `switch` case statements, including a leap year checker, a car class selector, finding the greatest of three numbers, determining the greater of two numbers, and a month name printer. It also demonstrates the use of the `break` statement within a loop to terminate it prematurely based on a condition.
**IV. Data Structures:**
The source delves into fundamental data structures in Java:
* **Arrays:**
* **1D Arrays:** Explained as a multi-value container. The concept of array declaration, initialization (with a fixed size), and how arrays are stored in RAM (stack for reference, heap for the actual array with default values) is introduced. Reading and updating elements in a 1D array are demonstrated with code examples.
* **Multidimensional Arrays (2D Arrays – Array of Arrays):** Explained as an array where each element is itself an array. The concept of different lengths for inner arrays is mentioned. Declaration, initialization, reading single elements, updating elements, and reading all elements using nested loops are illustrated with code.
* **Strings:**
* **String Literals (Interned Strings):** Explained how string literals are created in the “string pool” and how multiple references can point to the same literal, thus saving memory. The concept of lookup before creation and immutability is emphasized.
* **String Objects (Using `new` keyword):** Explained how the `new` keyword always creates a new string object in the heap memory, even if the content is the same as an existing literal or object.
* **String Methods:** A list of commonly used string methods is provided, including `equals`, `equalsIgnoreCase`, `length`, `charAt`, `toUpperCase`, `toLowerCase`, `replace`, `trim`, `contains`, `toCharArray`, `isEmpty`, `endsWith`, `startsWith`, `concat`.
* **String API Demonstrations:** Practical code examples illustrate the usage of `length()`, `charAt()`, `toUpperCase()` (showing immutability), `toLowerCase()`, `contains()`, `substring()`, `replace()`, `toCharArray()`, and `split()` methods. A use case for validating email and phone number format using string methods is also provided. The concept of string immutability is reinforced with a concatenation example.
* **StringBuffer:** Introduced as a mutable alternative to `String`, where data can be appended using the `append()` method without creating a new object each time.
* **Stack:** Defined as an abstract data structure following the Last-In, First-Out (LIFO) principle. The basic operations `push` (insert) and `pop` (remove) are explained. A code example demonstrates the implementation of a stack using an array, including `push`, `pop`, `isEmpty`, `isFull`, `peek` operations, and a driver `main` method to showcase its usage.
* **Queue:** Defined as an abstract data structure following the First-In, First-Out (FIFO) principle. The basic operations `enqueue` (insert at the rear) and `dequeue` (remove from the front) are explained. Its use in asynchronous data transfer and resource sharing is mentioned. A code example demonstrates using the built-in `Queue` interface (implemented by `LinkedList`) and its methods like `add`, `remove`, `size`, and `contains`.
* **LinkedList:** Explained as a linear data structure where elements are linked together using nodes. The difference between `ArrayList` (array-based) and `LinkedList` (node-based) in terms of memory allocation and performance is highlighted. Various methods of the `LinkedList` class are demonstrated with code examples, including adding elements (`add`, `add(index, element)`), clearing the list (`clear()`), cloning (`clone()`), finding the index of an element (`indexOf()`), and adding elements at the end (`offer()`).
* **HashMap:** Introduced as a map-based data structure that stores key-value pairs. Key characteristics such as allowing one null key and multiple null values, being unsynchronized, and not maintaining insertion order are mentioned. The concepts of initial capacity and load factor affecting performance are explained. Synchronized HashMap is discussed using `Collections.synchronizedMap()`, and the fail-fast behavior of iterators is noted. Common constructors are listed. A code example demonstrates basic `HashMap` operations like `put`, `get`, `containsKey`, `size`, and `clear`.
* **ArrayList:** Described as a resizable array implementation of the `List` interface, allowing dynamic addition and removal of elements. Key features include allowing duplicate elements, maintaining insertion order, and being non-synchronized. A code example shows basic `ArrayList` operations like adding elements (`add`), getting elements (`get`), setting elements (`set`), removing elements (`remove`), checking size (`size`), iterating through elements (using a for-each loop), and sorting using `Collections.sort()`.
* **Generics:** Explained as a feature that provides type safety to collections. The syntax for declaring generic classes and using type parameters is introduced. The benefits of generics, such as compile-time type checking and eliminating the need for manual type casting, are highlighted. An example demonstrates creating a generic `ArrayList` of strings.
* **File Handling:** Explained as reading from and writing to files in Java using the `java.io` package. The concept of streams (byte stream and character stream) is introduced. Various useful `File` class methods are listed (e.g., `canRead()`, `canWrite()`, `createNewFile()`, `delete()`, `exists()`, `getName()`, `getAbsolutePath()`, `length()`, `list()`, `mkdir()`). Code examples demonstrate creating a new file, getting file information, writing to a file using `FileWriter`, and reading from a file using `Scanner`.
**V. Threads in Java:**
The document covers the fundamentals of threads in Java:
* **Java Thread Definition:** Defined as a lightweight subprocess, the smallest independent unit of a program with a separate path of execution. Every Java program has at least one main thread.
* **Thread Life Cycle:** The different states of a thread are explained: New, Runnable, Running, Waiting, and Terminated, with a brief description of each state.
* **Creating Threads:** Two ways to create threads are explained:
* **Extending the `Thread` class:** An example shows creating a class that extends `Thread` and overrides the `run()` method. Creating an instance of this class and calling the `start()` method to begin execution in a new thread is demonstrated.
* **Implementing the `Runnable` interface:** An example shows creating a class that implements `Runnable` and implementing the `run()` method. Creating a `Thread` object by passing an instance of the `Runnable` class to the `Thread` constructor and then calling `start()` is demonstrated.
* **Multi-threading:** Defined as the ability of a program to execute more than one thread concurrently, allowing for optimal resource utilization. A simple example shows the main thread starting two custom threads (implementing `Runnable`) and their concurrent execution. The concept of `setDaemon(true)` is briefly mentioned.
* **Synchronization:** Briefly defined as a mechanism to control access of multiple threads to shared resources to prevent data inconsistency. An example of a scenario where synchronization is needed (booking a single movie ticket by multiple people) is given. The use of the `synchronized` keyword to acquire locks on objects is mentioned.
* **Difference between Processes and Threads:** A table summarizes the key differences based on control, resource sharing, dependency, memory space, and management.
* **Wrapper Classes:** Defined as classes that convert Java primitives into reference types (objects). Each primitive type has a corresponding wrapper class (e.g., `Integer` for `int`, `Boolean` for `boolean`). The concepts of boxing (primitive to object) and unboxing (object to primitive) are explained with examples. Auto-boxing and auto-unboxing are also introduced. The main reason for using wrapper classes (to treat primitives as objects) is mentioned.
* **Keywords: `final`, `finally`, and `finalize`:**
* **`final`:** Explained as a keyword used to make variables constant (cannot change value), classes non-inheritable, and methods non-overridable. Examples are provided for `final` variables.
* **`finally`:** Explained as a block used in exception handling that is always executed, regardless of whether an exception is thrown or caught. Its purpose for cleanup operations (e.g., closing database connections) is highlighted.
* **`finalize`:** Described as a protected method of the `java.lang.Object` class that is called by the garbage collector before an object is reclaimed. Its use for cleanup activities related to the object is mentioned.
**VI. Regular Expressions (Regex):**
The document introduces regular expressions in Java using the `java.util.regex` package:
* **Regex Definition:** Explained as a pattern used to match a sequence of characters.
* **`Pattern` and `Matcher` Classes:** The core classes for working with regex in Java are introduced. An example demonstrates compiling a pattern using `Pattern.compile()` and creating a `Matcher` object using `pattern.matcher()`. The `matcher.matches()` method is used to check if the entire input sequence matches the pattern.
* **Regex Character Classes:** Various character classes are explained with their meanings (e.g., `[abc]`, `[^abc]`, `[a-zA-Z]`, `[a-d[m-p]]`, `[a-z&&[def]]`, `[a-z&&[^bc]]`, `[a-z&&[^m-p]]`). An example demonstrates using `Pattern.matches()` with different character classes to test matching.
* **Regex Quantifiers:** Quantifiers specify the number of occurrences of a character or group. Various quantifiers are explained (e.g., `X?`, `X+`, `X*`, `X{n}`, `X{n,}`, `X{n,m}`). An example demonstrates using `Pattern.matches()` with different quantifiers to test matching.
* **Regex Meta Characters:** Meta characters provide shortcodes for common character sets (e.g., `.`, `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, `\b`, `\B`). An example demonstrates using `Pattern.matches()` with different meta characters to test matching.
* **Practical Regex Examples:**
* **Finding a given pattern in a string:** An example shows using `Pattern.compile()`, `Matcher`, and `matcher.find()` to locate occurrences of a specific pattern within a string.
* **Email Validation:** An example demonstrates using a regex pattern to validate the format of an email address using `Pattern.compile()` and `matcher.matches()`.
**VII. Networking with Sockets:**
The document provides a basic introduction to socket programming in Java using the `java.net` package:
* **Socket Definition:** Explained as a connection between two programs running on the same or different networks. Server sockets and client sockets are mentioned.
* **Client-Server Communication:** A simplified explanation of how a server listens on a specific port and a client connects to the server’s IP address and port to exchange data.
* **Basic Socket Programming Example:** Code snippets for a simple server and client are provided. The server code demonstrates creating a `ServerSocket`, accepting client connections, reading input using `BufferedReader`, and writing output using `PrintWriter`. The client code shows creating a `Socket`, connecting to the server, sending data, and receiving data. The interaction between the server and client (reading input until “over” is received) is described.
**VIII. Who is a Java Developer?**
The document concludes with a brief definition of a Java developer as a computer software developer or programmer who integrates Java programming language knowledge to build applications.
**IX. Practical Java Examples:**
The document includes several practical Java program examples:
* **ATM Machine:** A detailed explanation and code walkthrough of a simple ATM simulation program involving account management (checking and savings), balance inquiry, deposit, and withdrawal. The program utilizes classes for `Account`, `ATM`, and `OptionMenu`, demonstrating concepts like inheritance, user input, conditional statements (`switch`), and basic transaction logic.
* **Text Editor:** A description and code explanation of a basic text editor application built using Java Swing. It showcases features like creating/opening/saving files, editing (cut/copy/paste), font manipulation (bold, italic, size, type), color selection (foreground/background), and undo/redo functionality. It highlights the use of Swing components (`JTextArea`, `JMenuBar`, `JMenuItem`), event listeners, and the undo/redo mechanism.
**X. Common Interview Questions and Answers:**
A section addresses common Java interview questions:
* **What is JVM?** Explained as the software provided by the platform that provides the runtime environment to execute Java bytecode.
* **What is Synchronization?** Explained as a mechanism to allow controlled access of multiple threads to a shared object, preventing memory consistency errors. The `synchronized` keyword and the concept of acquiring locks are mentioned.
* **Difference between Processes and Threads:** Summarized in a table (already mentioned in the Threads section).
* **What is a Wrapper Class?** Explained as a way to convert Java primitives into reference types (objects). Boxing, unboxing, auto-boxing, and auto-unboxing are defined with examples. The reason for using wrapper classes (OOP adherence, passing by reference) is given.
* **What are the keywords final, finally, and finalize?** Explained with their respective purposes and usage (already mentioned).
* **What is OOPs?** Defined as Object-Oriented Programming System, a paradigm centered around objects. The four core principles (Encapsulation, Abstraction, Inheritance, Polymorphism) are listed and briefly explained.
* **What is an Object?** Defined as a basic unit of OOP, an instance of a class with state (data) and behavior (methods). The process of object creation in stack (reference variable) and heap (actual object) memory is explained.
* **Difference between Stack and Heap Memory:** Key differences are summarized based on usage, accessibility, memory management (LIFO vs. generational/key-value), and lifetime.
* **What are the different access modifiers in Java?** Four access modifiers (`public`, `private`, `protected`, and default/package-private) are listed and their visibility/accessibility scopes are explained.
* **Difference between HashTable and HashMap:** Key differences are highlighted based on null keys/values, synchronization, performance, and inheritance.
* **Difference between equals() and == operator:** Explained with a demonstration of comparing String objects. `==` compares object references (memory addresses), while `equals()` (in the case of `String`) compares the actual content of the objects.
* **Predict the Output of a Java Program:** A simple program with method calls and arithmetic operations is given, and the expected output (11) is explained step-by-step.
In summary, the provided source offers a comprehensive overview of fundamental Java programming concepts, supported by explanations and practical code examples. It covers essential language features, data structures, object-oriented principles, and common programming tasks, making it a valuable resource for learning Java.
Java Loop Control Statements: for, while, do-while
Java supports several types of loop control statements that allow you to execute a block of code repeatedly until a certain condition is met. The main types of loops in Java discussed in the sources are the for loop, the while loop, and the do while loop.
1. for Loop:
- The for loop in Java is used to iterate and execute a block of code multiple times when the number of iterations is known by the user.
- It is recommended to use the for loop when the number of iterations is known.
- A for loop has three basic parts:
- Initialization: This step initializes the loop counter variable. For example, int i = 1.
- Condition: This part specifies the condition that is evaluated before each iteration of the loop. The loop continues to execute as long as this condition is true. For example, i <= 10.
- Increment or Decrement: After each iteration of the loop, the counter variable is updated. For example, i++.
- Example:for (int i = 1; i <= 10; i++) {
- System.out.println(i);
- }
- This for loop will print the value of i ten times, from 1 to 10.
- A flow diagram of a for loop shows that initialization happens first, then the condition is checked. If true, the code inside the loop executes, followed by the increment/decrement, and the condition is checked again. If the condition is false, the loop terminates.
2. Enhanced for Loop (or Advanced for Loop):
- This type of for loop is used to iterate over elements in arrays and collections.
- It simplifies the process of iterating through each element without needing to manage indices explicitly.
- The syntax typically involves declaring a variable of the same type as the elements in the array/collection, followed by a colon, and then the array/collection itself.
- Example:String[] arrData = {“John”, “Jerry”, “Ralph”, “Jim”, “Tom”};
- for (String name : arrData) {
- System.out.println(name);
- }
- This loop will iterate through the arrData array and print each name.
- The flow of an enhanced for loop involves checking if there are any elements present in the array/collection. If true, it initializes a local variable with the first element and executes the loop body. This process continues for each element until all elements have been processed.
3. while Loop:
- The while loop evaluates a certain condition.
- If the condition is true, the code inside the while loop is executed.
- This process continues until the specified condition becomes false.
- The condition to be specified in a while loop must be a Boolean expression.
- Example:int i = 5;
- while (i <= 15) {
- System.out.println(i);
- i += 2;
- }
- This while loop will print values of i starting from 5, incrementing by 2, as long as i is less than or equal to 15.
- A flowchart of a while loop shows that the condition is checked first. If true, the code inside the loop executes, and then the condition is checked again. If the condition is false, the loop terminates.
4. do while Loop:
- The do while loop is similar to the while loop, but with a key difference: the condition is evaluated after the execution of the loop body.
- This guarantees that the loop is executed at least once, regardless of whether the condition is initially true or false.
- Example:int i = 20;
- do {
- System.out.println(i);
- i++;
- } while (i <= 20);
- In this do while loop, the value 20 will be printed once, even though the condition i <= 20 becomes false after the increment.
- A flow diagram of a do while loop shows that the statements inside the loop are executed first, and then the condition is checked. If the condition is true, the loop repeats; otherwise, it terminates.
5. Nested Loops:
- It is possible to have one loop inside another loop; this is known as a nested loop.
- For each iteration of the outer loop, the inner loop executes completely.
- Example:int[][] array = {{1, 2}, {3, 4}};
- for (int i = 0; i < array.length; i++) {
- for (int j = 0; j < array[i].length; j++) {
- System.out.println(array[i][j]);
- }
- }
- This example demonstrates a nested for loop iterating through a two-dimensional array. The outer loop iterates through the rows, and the inner loop iterates through the elements in each row.
6. break Statement in Loops:
- The break statement can be used to terminate a loop prematurely.
- When a break statement is encountered inside a loop, the control flow immediately exits the loop and continues with the statement immediately following the loop.
- Example:int[] numbers = {10, 20, 30, 40, 50};
- for (int num : numbers) {
- System.out.println(num);
- if (num == 40) {
- break;
- }
- }
- In this example, the loop will print 10, 20, and 30, and then when num is 40, the break statement will be executed, and the loop will terminate before printing 50.
7. Infinite Loop:
- An infinite loop occurs when the condition of the loop never becomes false, causing the loop to execute indefinitely unless it is terminated externally or by a break statement.
- A common way to create an infinite loop with a while loop is to use the condition true.
- Example:while (true) {
- System.out.println(“Edureka”);
- // Some condition to break out of the loop should be present
- // to avoid truly infinite execution.
- }
- This while loop will continuously print “Edureka”.
The source also briefly mentions the if statement as a control statement, but it is a conditional statement, not a loop, as it does not involve repeated execution of code based on a condition. Similarly, the switch case is a selection statement for executing a single block of code among multiple cases.
Java Switch Case Control Statement
The switch case statement in Java is a control statement used to execute a single statement for multiple conditions. It provides a way to choose one block of code to execute from a set of possible cases based on the value of an expression.
Here are some key aspects of the switch case statement based on the sources:
- Purpose: To execute a single statement among multiple conditions.
- Supported Data Types: The switch case statement can be used with short, byte, int, long, enum types, Character, String, and their corresponding wrapper types.
- Syntax: A switch statement includes a switch expression and one or more case labels. The switch expression is evaluated once, and its value is compared with the values of each case label.
- switch (expression) {
- case value1:
- // statements to be executed if expression equals value1
- break;
- case value2:
- // statements to be executed if expression equals value2
- break;
- // …
- default:
- // statements to be executed if expression does not match any case
- }
- Rules for Usage:
- One or n number of case values can be specified for a switch expression.
- Case values must be unique. Duplicate case values are not permissible and will result in a compile-time error.
- Case values must be literals or constants. Variables are not permissible as case values.
- The break statement is used to terminate the statement sequence within a case. If a break statement is not used, the execution will “fall through” to the next case. The use of the break statement is optional.
- There can be at most one default label. The default block is executed if the value of the switch expression does not match any of the case values. The default label is also optional and does not need a break statement after it.
- Example: The source provides an example where an instrument number is used in a switch statement to print the name of the selected instrument:
- int instrument = 4;
- switch (instrument) {
- case 1:
- System.out.println(“piano”);
- break;
- case 2:
- System.out.println(“drums”);
- break;
- case 3:
- System.out.println(“guitar”);
- break;
- case 4:
- System.out.println(“flute”);
- break;
- case 5:
- System.out.println(“uka”);
- break;
- case 6:
- System.out.println(“volin”);
- break;
- default:
- System.out.println(“invalid”);
- }
- In this example, because instrument is 4, the output will be “flute”.
In our previous conversation, we discussed various control statements in Java, including loops. The switch case statement is another important control statement that allows for conditional execution based on the value of an expression, offering an alternative to multiple if-else-if statements in certain situations. The source also mentions switch as one of the types of conditional statements available in Java.
Java Object-Oriented Programming Fundamentals
Object-Oriented Programming (OOP) is described as a programming style associated with programming concepts such as inheritance, polymorphism, abstraction, and encapsulation. Java is highlighted as one of the most sought-after skills and a language that follows an object-oriented programming paradigm. Whether you are a beginner or an experienced professional, understanding these key OOP concepts is crucial for building modular and maintainable code in Java.
At its core, OOP is a methodology or a paradigm using which we can design our software solutions. It centers around the concepts of objects and classes. An object is a real-world entity, anything you can see, touch, or feel, and it has both state (properties or attributes) and behavior (methods). A class acts as a blueprint or a drawing of an object, defining how an object will look and behave through its properties and behaviors.
The source emphasizes that having an object-oriented programming approach allows for creating different types of objects that share the same properties but have different values for those properties. OOP is presented as a bottom-up approach where you first think of objects and then start coding, contrasting with the top-down approach of procedural programming. It also offers better security through access modifiers compared to procedural approaches where data moves freely. Furthermore, OOP provides features like overloading, overriding, and inheritance that facilitate easier software design.
The source identifies four major fundamentals or pillars of OOP:
- Encapsulation: This is a mechanism where you bind your data and code together as a single unit. It also means to hide your data in order to make it safe from any modification. The analogy of a medical capsule is used, where the drug (data) is safe inside the capsule. Encapsulation ensures that the methods and variables of a class are hidden and protected. An example is given where user details like name, account number, email, and balance are encapsulated within a class.
- Inheritance: This is where the property of an object will be acquired by the other object. It establishes an “is a” relationship, like a parent-child relationship. A child class (sub class) inherits properties and methods from a parent class (super class). The source discusses different types of inheritance in Java:
- Single-level inheritance: One parent class and one child class.
- Multi-level inheritance: A chain of inheritance, like parent to child to grandchild.
- Hierarchical inheritance: Multiple child classes inheriting from a single parent class.
- The source explicitly states that multiple inheritance or hybrid inheritance is not directly supported in Java; interfaces are used to achieve similar functionality. Inheritance promotes code reusability and extensibility, and allows for overriding methods in the child class to provide specific implementations. It can also be used for data hiding by making attributes private in the parent class.
- Abstraction: This “refers to the quality of dealing with ideas rather than events”. It basically deals with hiding the details and showing the essential things to the user. When you make a call, you only see the option to pick up or reject, without knowing the internal processing. Abstraction helps to reduce code complexity. It can be achieved in two ways in Java:
- Abstract classes: A class declared with the abstract keyword. An abstract class cannot be instantiated (you cannot create an object of it). It can contain abstract as well as concrete methods. An abstract class can act as a template for its subclasses. The runtime environment can construct the parent object of an abstract class before constructing the child object.
- Interfaces: Known as a “blueprint of a class” or a collection of abstract methods and static constants. Each method in an interface is public and abstract and does not contain any constructor. Interfaces also help in achieving multiple inheritance in Java. A class implements an interface using the implements keyword.
- Polymorphism: Meaning “taking many forms” (poly – many, morph – forms). It is “the ability of a variable, function, or an object to take on multiple forms“. Polymorphism allows you to define one interface or method and have multiple implementations. Java supports two types of polymorphism:
- Runtime Polymorphism (Dynamic Polymorphism): A call to an overridden method is resolved at run time rather than at compile time. Method overriding is an example of runtime polymorphism, where a child class provides a specific implementation of a method already defined in its superclass. Upcasting (reference variable of the parent pointing to the object of the child) is a key aspect of runtime polymorphism.
- Compile-time Polymorphism (Static Polymorphism): A call to an overloaded method is resolved at compile time rather than at run time. Method overloading is an example, where a class has two or more methods with the same name but different arguments (number, types, or order of parameters).
In summary, Object-Oriented Programming in Java provides a powerful and structured approach to software development by organizing code around objects and classes and leveraging the principles of encapsulation, inheritance, abstraction, and polymorphism to create robust, modular, reusable, and maintainable applications.
Java Inheritance: Concepts and Types
Java Inheritance is a fundamental concept of Object-Oriented Programming (OOP) in Java where a child class (also known as a subclass or derived class) inherits the methods and properties of a parent class (also known as a superclass or base class). The source explains that inheritance establishes an “is-a” relationship between the classes, like the relationship between a parent and a child. For example, a Mobile is a Product.
Here are the key aspects of Java Inheritance discussed in the sources:
- Mechanism: Inheritance is achieved in Java using the extends keyword. When a class extends another class, it gains access to the non-private members (fields and methods) of the parent class.
- Benefits:
- Code Reusability: Inheritance promotes code reusability by allowing the child class to reuse the code already written in the parent class. This reduces redundancy and makes the code more maintainable.
- Extensibility: Inheritance enables you to add new features or modify existing ones in the child class without altering the parent class.
- Method Overriding: A child class can override (redefine) a method inherited from the parent class to provide its own specific implementation. This is a key aspect of achieving runtime polymorphism in Java.
- Data Hiding: By declaring attributes as private in the parent class, you can control their accessibility in the child class, contributing to data hiding.
- Types of Inheritance Supported by Java: The source outlines four types of inheritance in Java:
- Single Inheritance: One child class inherits from one parent class. The source provides an example where a HadoopTeacher class inherits from a Teacher class.
- Multi-level Inheritance: A child class inherits from a parent class, which in turn inherits from another parent class, forming a chain of inheritance. The source illustrates this with Class B inheriting from Class A, and Class C inheriting from Class B.
- Hierarchical Inheritance: Multiple child classes inherit from a single parent class. The source gives an example where Class B and Class C both inherit from Class A. Another example involves a Restaurant acting as a parent class with child classes like ItalianRestaurant, ChineseRestaurant, and MexicanRestaurant inheriting from it.
- Hybrid Inheritance: This is a combination of multiple inheritance and multi-level inheritance. The source mentions that while direct multiple inheritance (one class inheriting from multiple classes) is not supported in Java due to the “diamond problem,” hybrid inheritance can be achieved through the use of interfaces.
- Multiple Inheritance: The source explicitly states that multiple inheritance is not directly supported in Java. This is to avoid the ambiguity arising from inheriting methods with the same signature from multiple parent classes (the “diamond problem”). Java uses interfaces to achieve a form of multiple inheritance by allowing a class to implement multiple interfaces.
- “Is-a” and “Has-a” Relationships: The source also briefly touches upon “is-a” and “has-a” relationships. Inheritance represents an “is-a” relationship (e.g., BMW is a Car). A “has-a” relationship, on the other hand, involves a class having an instance of another class as a member (e.g., a BMW has an Engine). Inheritance is implemented using extends, while the “has-a” relationship is typically implemented through instance variables.
In our previous discussion about OOP, we established that inheritance is one of the four pillars, enabling code reuse and forming hierarchical relationships between classes. The new source provides more detailed explanations and examples of the different types of inheritance in Java and clarifies the language’s approach to the complexities of multiple inheritance through interfaces.
Java Exception Handling: A Comprehensive Overview
Exception Handling in Java is a crucial mechanism to deal with unwanted or unexpected events that occur during the execution of a program at runtime and can disrupt the normal flow of the program instructions. The source emphasizes that if exceptions are not handled, it can lead to system failure. Java’s exception handling mechanism aims to manage these runtime errors so that the normal execution flow is not disrupted.
Here’s a breakdown of exception handling in Java as discussed in the sources:
- What is an Exception? An exception is an unwanted or unexpected event that occurs during program execution. It’s a problem that arises during the execution of a program and can happen for various reasons like invalid user input, a file not being found, network connection loss, or the JVM running out of memory.
- Error vs. Exception: The source distinguishes between errors and exceptions:
- An error indicates a serious problem that a reasonable application should not try to catch. Errors are typically impossible to recover from and are usually related to the runtime environment, such as virtual machine error or stack overflow error.
- An exception indicates conditions that are reasonable for an application to try to catch. Exceptions can be recovered by handling them. They can be caused by the application itself (e.g., NullPointerException) or external factors (e.g., IOException).
- How JVM Handles Exceptions: When an exception occurs within a method, the JVM:
- Creates an exception object.
- This object contains the name and description of the exception and the current state of the program where the exception occurred.
- Throws this exception object to the runtime system (JVM).
- The JVM then tries to find an appropriate exception handler to deal with the exception.
- Exception Hierarchy: All exception and error types in Java are subclasses of the Throwable class, which is the base class of the hierarchy. Throwable has two main branches:
- Exception: This class is used for exceptional conditions that user programs should catch. Examples include NullPointerException, RuntimeException, IOException, SQLException, ClassNotFoundException, and ArrayIndexOutOfBoundsException.
- Error: This branch is used by the Java runtime system to indicate errors related to the runtime environment itself (JRE). Examples include VirtualMachineError and StackOverflowError.
- Checked vs. Unchecked Exceptions: Exceptions in Java are categorized into checked and unchecked:
- Checked Exceptions: These are exceptions that the compiler forces you to handle (using try-catch or declaring them using throws) because they are considered potential issues that might occur during normal operation (e.g., IOException, SQLException). They happen at compile time.
- Unchecked Exceptions (Runtime Exceptions): These exceptions are not checked by the compiler, and you are not forced to handle them (e.g., ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException). They typically result from programming errors and happen at runtime.
- Exception Handling Keywords: Java provides specific keywords to handle exceptions:
- try: The try block encloses the code that might throw an exception.
- catch: The catch block follows the try block and contains the code that handles a specific type of exception. There can be multiple catch blocks to handle different types of exceptions (multi-catch).
- finally: The finally block follows the try (and optional catch) block and contains code that will always be executed, regardless of whether an exception was thrown or caught. This is typically used for cleanup operations like closing connections. The catch block is not required if a finally block is present.
- throw: The throw keyword is used to explicitly throw an exception. You can throw built-in exceptions or create and throw your own user-defined exceptions.
- throws: The throws keyword is used in the method signature to declare that a method might throw a certain type of exception. It doesn’t throw the exception itself but indicates that the calling code needs to handle it.
- Nested try Blocks: A try block can be placed inside another try block, creating nested try blocks. This allows for handling exceptions in different scopes.
- User-Defined Exceptions: Java allows you to create your own custom exception classes by extending the Exception class (or its subclasses). This is useful when the built-in exceptions don’t adequately describe a specific error situation in your application. User-defined exceptions are thrown using the throw keyword.
- Passing Exceptions: The source provides an example of how exceptions can occur during operations like date format conversion and how these exceptions can be caught and handled.
- Methods of Exception Handling: The source lists try, catch, finally, throw, and throws as the various methods of exception handling in Java.
- Difference Between throw and throws:
- throw is used to explicitly throw an exception, while throws is used to declare an exception that a method might throw.
- throw is followed by an instance of an exception, while throws is followed by a class name.
- throw is used within a method’s body, while throws is used with the method signature.
- throw can throw only one exception at a time, while throws can declare multiple exceptions.
- Difference Between final, finally, and finalize: These are distinct keywords with different purposes:
- final: Used to apply restrictions on classes (cannot be inherited), methods (cannot be overridden), and variables (cannot be changed).
- finally: A block used to execute important code regardless of whether an exception is handled or not.
- finalize: A method used to perform cleanup processing just before an object is garbage collected.
Previously, we discussed how exception handling is a key feature that sets Java apart as a programming language. This new source provides a comprehensive overview of the concepts and mechanisms involved in handling exceptions in Java, which is crucial for building robust and fault-tolerant applications.
The Original Text
hello everyone and welcome to this Java full course by urea Java stands as one of the most influential programming languages powering everything from mobile applications to large scale Enterprise systems over the years Java has become a preferred choice for developers due to its platform independence strong security features and object oriented approach from Android apps and web appli ations to cloud-based Solutions and financial systems Java is everywhere whether you are an absolute beginner looking to learn your first programming language or a season professional aiming to refine your Java expertise this course is designed to help you understand key concepts with practical examples and hands- on learning so now let us outline the agenda for this Java full course in this course We Begin by answering the fundamental question such as what is Java I’m guiding you through the Java installation process to get you started on the right foot we will cover Core Concepts such as operators in Java and conditional statements in Java which lay the ground work for more advanced programming next we will dive into Java oops Concepts exploring the principle of objectoriented programming that make Java a powerful tool for building modular and maintainable code we will walk you through abstract classes inheritance and polymorphism providing clear examples and Hands-On exercises to solidify your understanding as we progress we will tackle exception handling in Java to ensure your programs are robust and error resistant you will learn how to work with arrays and navigate the collections Frameworks which are essential for efficient data management the course will also explore Java strings and interfaces setting the stage for more complex data structures we then move into specialized topics such as data structures in Java including in-depth discussion on link list and hashmap as well as gener to enhance type safety in your programs file handling Java threats and regular EXP option in Java will expand your toolkit for developing Advanced applications while soit programming in Java opens up the world of network communications finally we will guide you on how to become a Java developer showcase real well Java projects and prepare you for the essential Java interview question and answers to help you land your dream job in the tech industry but before we jump into the course content please like share and subscribe to our YouTube channel and hit the Bell icon to stay updated on the latest day content from edura also edure rea’s Java certification training crafted by top industry experts is designed to help you become an oracle certified professional this Java course covers skills such as objectoriented programming Java collection s SOA and web services also working with jdbc design patterns and along with popular development tools so check out the course Link in the description box below now let’s get started with our first topic what is Java there are many controversies that say Java is going to die and it has become weak compared to its competitors so many beginners and experienced programmers have a doubt if it’s really dying to clear this out let us have a quick look on the major applications and websites once ABNB Uber Facebook Instagram Google Amazon Netflix and lot many we shall begin with little basic history of java now why did we recall all these applications and websites it is because all these sck Giants are in the use of none other than Java programming language it is the base of all data frames storage and parts of every single major application this entirely proves that Java is never going to die it is getting evolved every single day and it is one of the major reasons behind the development of much major softwares now that we have a good clarification let us move ahead and learn Java really fast Java is also used in multiple ways for example social media big data and Hadoop Android application development data science and artificial intelligence data security software testing and data analytics now that we have a good clarification let us move ahead and learn Java really fast we shall begin with a little basic and history of java firstly history of Java Java was invented by James Gosling in the year 1995 it was basically invented for interactive television for God’s sake it was found too advanced and was also able to perform extraordinary and sizable tasks than just a television thing now let’s get started with Java installation go to your Chrome browser then search Java download hit enter go to the second website because we want the Java from Oracle when you click on that link you’ll be redirected to a page that will look something like this here it says jdk 21 is latest long-term support release so we want jdk 22 and below that you can see that it is for different machines so if you want for Linux you can go ahead and directly download it and if you want for Mac OS you have to change it and same goes for Windows now in Windows also you can download it using compressed archive or MSI installer but we’ll go ahead with the normal installer so download has started I’ll just go to my download folder and let’s see so here is our jdk file now let’s go ahead and run it it will ask you for the permission after that just click on next and I’ll just go ahead with the default it is best to keep it default now it will install after that just close it to verify this we’ll just go ahead and type CMD and type Java Das Dash version now we have installed jdk now we’ll just download one of the IDS the most popular in the market is Eclipse so for that just go ahead and type Eclipse download you can see the first site just go ahead and click it after that you’ll see page that will look something like this here’s the download option you can go ahead and click on this it will redirect you to this page now latest one is 20246 so this is for the June 2024 you can directly install eclipse in your system or you can download the specific package now we are going to go ahead with Java so this is for our Java and we are using window so click on this one after that click on download let me go to the download folder let’s see now we can see this is there and after that just extract it here now let’s open this folder here you can see the eclipse application just click on that it might take a while after that you can see this I’ll just keep the default and click on launch now it is starting Eclipse you might see a welcome page that you have to close now I want to create a Java project so just going to go to files and new ones now here I’ll just go to others and find Java click on Java project and then next after this let’s name our new project my first project make sure you don’t have space in the name after that we are going to use Java ac22 after that configure J then click on ADD now make sure you have selected standard VM standard virtual machine click on next and just click on the directory go to your local disk then into the program files there you can see your Java folder just go ahead and click on that here there are two options jdk 21 and 22 now we’re going to go ahead with 22 and just select the folder now since jdk 22 came here I’ll just go ahead and finish it after that you can see jdk 22 is here just apply it and apply and close after that nothing just finish it so so we can see the my first project is here now I want to create a class main class so I’ll just go ahead and click on file and new and here we can see class click on that after that make sure you have used public and then clicked on public static void main string arguments I’ll name this default the package name should be there and the name I’ll go ahead with me after that just go ahead and click on finish now going see the main Java file is here so this is our first program now let’s go ahead and run our favorite hello world program make sure you are typing correctly and don’t forget to use semicolon at the end now just go ahead and click on run over here it will ask you that you want to use yes so this is the console where you’ll get your output and since we havep print L and hello world we get the hello world now let’s try something else I’ll copy this and then paste it again now this time I’ll do please subscribe now let’s run it again it will start compiling again and if you don’t want to get annoyed by it just click always allow and now you know how to install Java and also if we have tried a simple code using it some of the major features are as follows firstly open source Java since its birth till today is an open source product there are many speculations that say Java is not free anymore but to be sure Java is still free and the open jdk and Oracle jdk are completely similar to each other other that means you can typee your code using Oracle jdk and execute it in open jdk and the jdk versions are also available for all the types of operating systems such as Windows Linux Mac and many other flavors of Linux followed by the first feature the next feature is high performance Java is an interpreted language so it will never be as fast as a compile language like C or C++ but just Java enables high performance with the use of just in time compiler so here Java provides us high performance followed by that the next feature is multi-threading Java multi-threading feature makes it possible to write a program that can do many tasks simultaneously the benefit of multi-threading is that it utilizes the same memory and other resources to execute multiple threats at the same time like while typing grammatical errors are checked along followed by this feature the fourth feature is secure when it comes to Security Java is always the first choice with Java secure features it enables us to develop virus free and temper free systems Java program always runs in a Java runtime environment with almost null interaction with host operating system hence it is most secure followed by this the next feature is Java’s platform independency unlike other programming languages such as C or C++ Etc which are compiled into platform specific machines Java is guaranteed to be right once Run Anywhere language on compilation Java program is compiled into bite code this bite code is platform independent and can be run on any machine plus this bite code format also provides security any machine with Java runtime environment can run Java programs followed by this the next feature is portability the crossplatform feature enables the Java code to be highly portable in Java everything is an object which has some data and behavior Java can be easily extended as it is based on objectoriented programming model the last but not the least feature of java is its robust nature Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error checking and runtime error checking but the main areas in which Java improvised were memory management and mishandled exceptions by introducing automatic garbage collector and exception handling we have previously examed Java’s key features and what sets it apart as a programming language in the operators in Java Java module Learners will learn about the various operators available in Java and how to use them to perform different types of operations within their code the operators in a programming language are specific or special symbols used along with the variables on numbers so as to carry out some specific operations the various operators available in Java are as follows there un Operator athematic Operator shift operator relational op Operator bitwise Operator logical Operator ternary Operator and finally the assignment operator we shall discuss about each and every single operator available in Java firstly the unary operator the Java Unity operator requires only one operant the UN operators are used to perform various operations such as incrementing or decrementing a value by one negating an expression inverting the value of aoan and many more now let us execute a simple example of unary operator in Java as you can see this particular example is based on unary operators so here I have declared a value 10 to the variable X of integer data type and now I’m trying to increment the value of x by 1 by adding the unary operator increment this particular incrementation is called post increment followed by that we have a similar increment operator which is placed before X which says it is a pre-increment operator followed by that we will try to decrement the value of x by1 by using post decrement operator where we will provide the decrement operator after X and similarly the same decrement operator is used before X when which says that it is a pred decrement operation now let us try to execute our program and see the output you can see the output has been successfully generated now followed by this let us move ahead and understand the athematic operator Java athematic operators are used to perform addition subtraction multiplication and division they act as basic mathematic operations now let us see a basic example for athematic operators you can see I have provided two variables that is a and b a has the value 10 and B has the value 5 so the basic arithmatic operations that I will be performing are addition subtraction multiplication division and modulus so the addition symbol is carried out by plus subtraction is minus is multiplication is star division is forward slash and modulus is modulus symbol these are common now let us execute this and see the output you can see all the athematic operations have been successfully executed and the output is also generated so you can see the addition is 15 subtraction is 5 multiplication is 50 division is 2 and modulus S zero now with this let us move ahead into the next type of operators which are none other than the shift operators the shift operator is used to shift the bits in the value to the left or right side of the specific number of times we have two types of shift operators which are left shift operator and the right shift operator the left shift operator moves the specific number of bits towards the left side and the right shift towards the right side now let us execute a sample program to understand the shift operators in a much better way you can see I have used shift operator here which is left shift and I’m using left shift operator to move two bits of 10 towards left side and three bits of 10 towards left side and two bits of 20 towards left side and four bits of 15 towards left side so basically what happens here is 10 will be converted into to binary numbers and similarly all the other numbers will be converted into binary numbers and the number of bits which we require that is two will be shifted in that particular converted binary number and the new number generated will be provided in decimal numbers and that will be our output let us execute this program and see our output you can see that the program has been getting executed and the new numbers are been generated here as the output so 10 after shifting two bits towards left will be generating 40 and 10 after shifting three bits towards left will generate 80 and similarly 15 after shifting four bits will generate in 240 now that we have understood the shift Operator Let us move ahead and understand the relational operator the Java relational operator is used to compare the operant on both the sides of the relational operator this particular operator judge whether one of the operant is greater or lesser or equal or not equal to the other operator now the basic operation what a relational operator does is it compares the two numbers for example if you have a as five and B as 10 and if you compare if a is greater than b then the result will be false because a is smaller than b so this is what a relational operator basically does now let us go through a sample program to understand relational operators in a much better way here you can see that I have declared three variables that is a b and c a has 10 B has 5 and C has 20 now what we doing is we comparing a is less than b and a is less than C and followed by that we’re comparing again a is less than b and a is less than C so this example is both for relational operator as well as logical operator so The Logical operation which we have used is and now let us try to execute this program and see the output and there you go the result is false because a is greater than b but not less than b similarly a is less than C but the result of and logical operator is false because to become true both sides of the operant should be true now let us move ahead and understand bitwise operator basically the bitwise operator is applied on the bits for example if we provide a number to the variable that particular number will be converted into binary format and after that the operation will be applied on the bits one by one let us execute a sample program to understand bitwise operators in a much better way so this particular example is based on bitwise operators here also we have the same three values that is a = to 10 B is = to 5 and C isal to 20 now we’re performing bitwise operations on the particular variables and comparing them using a logical operator which is and now let us try to execute this program and see the output you can see that the program has been successfully executed and the output is been printed but the value of a is been changed here from 10 to 11 this happened because it is based on the bitwise operation which we performed here that is A++ post increment now followed by this let us move ahead and understand the next type of operators that are The Logical operators The Logical operators are the operators which are applied on both the ends or both the operant so the basic logical operators supported in Java programming language are and or and not the and operator is used to perform logical operation on two operant and it will result in a Boolean result so to become a true Boolean result and should be having both the operant as true and in order to result a True Value either one of the operant should be true and when it comes to not not is just a simple logical operator dat which negates the existing value that means if the value is true then after the not operation the value will be converted into false now let us see one basic example to understand logical operators in a much better way you can see the previous example is the best fit to understand logical operators you can see the value here was false since a is greater than b so this value will result in a false and this value will result in false so false and false will result in false now moving ahead we shall understand the next type of operators which are the ternary operators the ternary operator is simple but highly powerful operator used in Java programming language this particular ternary operator will reduce the code length to one line to understand this in a much better way let us execute a sample program here you can see that we have two different values which are A and B A has 2 and B has five so the ternary operator is this particular statement here we have also allocated a new variable which is of integer type which is minimum so minimum is equals to a less than b if a is less than b then minimum is a and else B is equals to minimum so this particular operation is minimum here a is compared if a is truly less than b then a will be printed into minimum else B will be printed into minimum and finally we shall print the value which is stored into minimum now let us execute this and see the output you can see that the value of a which is two is been printed here after executing the ternary operator present in the line number seven now let us move ahead and understand the next type of operator which are the assignment operators the assignment operators used in Java programming language are simply used to allocate the resultant memory into the variable which is located in the left side of the operant the basic assignment operators used in Java programming language are equals to and double equals to to understand assignment operators in a much better way let us execute a sample Java program so this particular program is based on assignment operations here we have two different values which are A and B A isal to 10 and B is = to 20 now what we are basically doing here is using the assignment operator and adding value 4 to the value 10 and decrementing value 4 to the value 20 this particular operator used here is the assignment operator now the result will be AAL to 14 and B is equal to 16 now let us execute this program and see if the output will be correct or not you can see the output is as expected with this let us move ahead and understand the control statements in Java a control statement in Java is a statement that determines whether the other statement will be executed or not in simple terms it controls the flow of a particular program in Java now let us see the control statements which are present in in Java so the control statements supported in Java are if else Loop while loop do while loop for Loop and switch case so these are the basic control statements that each and every programmer must be known with now let us understand each and every one of these control statements and also execute a basic program to understand them in a much better way firstly we shall deal with the if statement or if control statement in this statement if the condition specified as true the if block will be executed otherwise the else block will be executed we shall execute a sample program to understand the IFL statement in a much better way so this particular program is based on if else control statement here we have the input a equal to 15 the first if condition will be in case if a is greater than 20 then the first print of statement should be executed else the other print of statement should be executed now let us execute this program and see the output since we know 15 is less than 20 we should be expecting the second set of statements to be executed which is a is less than 10 and hello world you can see the message has been successfully printed here followed by this let us move ahead and understand the next type of control statements which are supported in Java that is none other than the V Loop known as the most common Loop the V Loop evaluates a certain condition if the condition is true then the code is executed the process is continued until the specific condition turns out to be false the condition to be specified in while loop must be a Boolean expression an error will be generated if the type is used is not an integer type or a string type let us execute a basic example to understand this while loop in a much better way as you can see this particular example is based on while loop here we have a variable I which has the value five here the condition specified in by Loop is I should be less than or equal to 15 until then we have to execute the print of statement which prints the value of I and after that the value of I will be incremented by two now this particular set of Loop will be executed until the value of I is less than or equal to 15 once after this condition becomes true the loop will be terminated let us try to execute this program and see the output you can see the values 5 7 9 11 13 and 15 are printed successfully once after the value of I reached to 15 the loop got terminated and it exited the loop now followed by this let us understand the next type of loop which is the do while loop the do while loop is completely similar to The V Loop the only difference is that the condition of the do V Loop is evaluated after the execution of the loop body this guarantees that the loop is executed at least once now let us try to execute a sample program to understand do V Loop in a much better way you can see that this particular example is based on dowi Loop here we have a variable I which stores the value 20 so once after the value is been declared we have the Dov Loop so inside the Dov Loop we are supposed to print the value of I the value of I will be incremented by one every single time the loop is executed now the loop body of duy loop is finished so the condition is placed at the end of DUI Loop which says the the I value should be less than or equal to 20 until then this particular Loop is valid now the only suspense between du V Loop and V Loop is the do V Loop will be executed at least for once without checking the condition because the condition is placed after the do Loop body now let us try to execute this and see the output you can see that the Loop has been successfully executed the value 20 is printed only for once because the value of I which we declared was 20 and it is true according to the condition so the control got terminated let us move ahead and understand the next type of loop which is the fall Loop the fall Loop in Java is used to iterate and evaluate a code multiple times when the number of iterations is known by the user it is recommended to use the fall Loop to understand the fall Loop in a much better way let us try to execute one basic example based on Fall Loop so this particular example is based on for Loop here we have the value of i as 1 and the condition is I is less than or equal to 10 and after that a post increment so in this particular statement we will be printing the value of I 10 times until the for Loop is true the three basic parts of a follow Loop are declaration condition and increment or decrement so this particular first block which is I is equal to 1 is the Declaration part and after that I is less than or equal to 10 is the condition part and lastly i++ which is the increment is the last part now let us try to execute this program and see the output you can see that the program has been successfully executed and the value of I is printed for 10 times which is 1 2 3 4 5 6 7 8 and 9 and 10 now followed by this let us understand the next type of loop which is the switch case a switch statement in Java is used to execute a single statement for multiple conditions the switch case statement can be used with short bite int long enum types Etc certain points must be noted while using the switch state M which are one or n number of case values can be specified for a switch expression case values that are duplicate or not permissible a compile time error is generated by the compiler if unique values are not used next the case value must be a literal or a constant variables are not permissible the last condition is usage of break statement is made to terminate the statement sequence it is optional to use the statement if the statement is not specified the next case is automatically executed now let us try to execute a sample program to understand switch case in a much better way you can see that this particular program is based on switch statement the switch condition is instrument now here the condition is that we supposed to select the instrument number four which happens to be flute now we have a various set of instruments present in our case which are piano trums guitar flute Uka volin and lastly the default statement which is invalid let us try to execute this program and see the output since we have provided our selection to be four which happens to be flute the output should be directly generated as flute now let us run this and see the output you can see that the program has been successfully generated and the selected instrument flute is been displayed in the console now moving ahead we shall understand the objectoriented style of programming in Java object-oriented programming is a programming style which is associated with programming Concepts such as inheritance polymorphism abstraction and encapsulation most of the popular programming languages like Java C++ Ruby Etc follow an object-oriented programming Paradigm as Java being the most sought after skill skill we will talk about objectoriented programming Concepts in Java an object based application in Java is based on declaring classes creating objects from them and interacting between these objects the first objectoriented programming style we will be discussing today is encapsulation encapsulation is a mechanism where you bind your data and code together as a single unit it also means to hide your data in order to make it safe from any modification what does this mean the best way to understand encapsulation is to look at the example of a medical capsule where the drug is always safe inside the capsule similarly through encapsulation the methods and variables of a class will be hidden safe to understand encapsulation in a much better way let us go through a simple example so this particular program is the example for encapsulation here we have encapsulate the data members which are the name of the user which is Ravi and account number of the user and email of the user and the am which is present in the particular users’s account now we will try to execute this program and print the details of the user you can see the program has been successfully executed and the account number of the user has been displayed here along with his name and mail ID along with the balance amount which is present in this particular account so this particular example was based on encapsulation now let us move ahead and understand the next type of objectoriented programming style which is inheritance as we can see in the image a child inherits the properties from his father similarly in Java there are two classes they are parent class which is also called as a super class or a base class and the next type of class is a child class which is also called as a subass or a derived class a class which inherits the properties is known as a child class whereas the class whose properties are inherited is known as the parent class inheritance in Java is further classified into four types they are single inheritance multi-level inheritance hierarchial inheritance and lastly the Hybrid inheritance the first one single inheritance in single inheritance one class inherits the properties of another it enables a derived class to inherit the properties and behavior from a single parent class this will in turn enable code usability as well as add new features to the existing code here Class A is your parent class and Class B is your child class which inherits the properties and behavior from the parent class followed by that we have multi-level inheritance when a child class is derived from a parent class which happens to be also derived from from another parent class that is a class having more than one parent class but at different levels such type of inheritance is known as multi-level inheritance if we talk about the flowchart Class B inherits the properties and behaviors of Class A and Class C inherits the properties of Class B so here Class A is the parent class of Class B as well as Class C so in this case Class C implic L inherits the properties and methods of Class A along with the class B this is what we call as a multi-level inheritance followed by this we have hierarchial inheritance when a class has more than one child class or subclasses in other words more than one child class have the same parent class then such type of inheritance is known as hierarchial if we talk about the flowchart then Class B and Class C are the child classes that are inherited from the same parent class that is Class A followed by that the last type of inheritance is called the Hybrid inheritance the Hybrid inheritance is a combination of multiple inheritance and multi-level inheritance since multiple inheritance is not supported in Java it leads to ambiguity this type of inheritance can be only achieved through interfaces we will execute examples for each one of the type of inheritances the first example that we will be executing is based on single inheritance so in this particular example we have the parent class as teacher and the child class as Hado teacher so here what we are trying to do is we are trying to inherit the properties of the parent class teacher into the child class Hado teacher let us try to execute this program and see the output you can see that the program is been successfully executed and the properties of the parent class have been successfully inherited into the child class that is the college name designation of the teacher and the main subject which he or she will be teaching now followed by this we shall try to execute the next type of example based on inheritance repeat so the next type of inheritance is the multi-level inheritance this particular example is based on multi-level inheritance where one child class inherits the properties of multiple parents at different levels one happens to be the first class two happens to be the next class and lastly three happens to be the last child class which extends the properties of one and two let us try to execute this program and see the output you can see that the program has been successfully executed and the output has been successfully generated on the console edure Rea happy learning followed by this we shall move ahead and understand the next type of inheritance so this particular example is based on hierarchial inheritance where two or more classes inherit the properties of one parent class so here the class one happens to be the parent class and class two and three are the child classes which are inheriting the properties from the same parent class which happens to be one let us try to execute this program and see the output you can see that the program has been successfully executed and the output has been generated which says Eda have be learning now we have discussed all the three inheritances which are single level inheritance multi-level inheritance and hierarchial inheritance the last type of inheritance which happens to be multiple inheritance or Hybrid inheritance happens to be not supported in Java to make this happen Java has come up with a new idea which is called as interface so we shall discuss about Java interfaces in the further chapters so the next Concept in object-oriented style of programming is the abstraction abstraction refers to the quality of dealing with ideas rather than events it basically deals with hiding the details and showing the essential things to the user if you look at the image here whenever you get a call we get an option either to pick it up or just to reject it but in reality there is a lot of code that runs in the background so we don’t know the internal processing of how a call is generated that’s the beauty of the abstraction therefore abstraction helps to reduce the code complexity you can achieve abstraction in two ways that is by using an abstraction class or an interface we shall understand abstract classes first an abstract class in Java contains abstract keyword what does the abstract keyword mean if a class is declared abstract it cannot be instantiated which means you cannot create an object of an abstract class also an abstract class can contain abstract as well as concrete methods now followed by that the next one is an interface interface in Java is known as a blueprint of a class or you can say it is a collection of abstract methods and static constraints in interface each method is public and Abstract but does not contain any Constructor along with abstraction interface also helps you to achieve multiple inheritance in Java we shall execute one single example for each one of these to understand abstraction in a much better way so the first example that we will be executing will be based on abstraction and the abstract class which is declared here is person so to declare this particular class we have used the keyword abstract so this particular abstract class consists of the following segments the first one is the name of the person gender of the person after this we have the class which inherits or extends this particular abstract class which is student so inside student we have a variable called as student ID which is declared as private now the elements from the abstract class will be extended into this particular student class and the output will be generated so let us execute this program and see the output you can see the program got successfully executed and the output is being generated here we have the name of the student as Priya and gender female similarly Karan Kumari John and their genders and also their degrees Karan Kumari and John are puring engineering and Priya is not studying so now let’s move ahead and understand interfaces in Java this particular example is based on interface and here the interface that we have declared is about a basic calculating functions which are add substract multiplication and divide so here we have declared the interface using the keyboard interface and as you can see we don’t have any Constructors inside this interface and followed by this this is our main class which is student which will implement the interface math to perform the addition subtraction multiplication and division operations let us try to execute this program and see the output now you can see the program got successfully executed and now the program is asking us to enter any two digits to perform addition let us enter 10 and 20 and you can see the sum has been successfully generated now it is asking values to enter to perform substraction let us enter 10 and five you can see the output as five now it is asking for values to perform multiplication let us enter 10 and 20 you can see the product as 200 and finally the division operation let’s enter 20 and five you can see the quotient is four so this is how face works now followed by this the fourth and last type of objectoriented programming style is none other than the polymorphism polymorphism means taking many forms where poly means many and morph means forms it is the ability of a variable function or an object to take on multiple forms in other words polymorphism allows you to Define one interface or method and have multiple implementations polymorphism in Java is of two types first runtime polymorphism and compile time polymorphism in Java runtime polymorphism refers to a process in which a call to an overridden method is resolved at run time rather than at compile time in this a reference variable is used to call an overridden method of a super class at runtime method overriding is an example of runtime polymorphism we understand method overwriting and method overloading in the further Concepts that is the advanced Java Jaa programming Concepts and followed by that we have the next compile time polymorphism in Java compile time polymorphism refers to a process in which a call to an overloaded method is resolved at compile time rather than at run time method overloading is an example for compile time polymorphism method overloading is a feature that allows a class to have two or more methods having the same name but with different arguments passed to the methods are different and like method overriding arguments can differ in number of parameters passed to the method data types of the parameters sequence of data types when passed to a method with this we come to an end of objectoriented style of programming in Java now let us continue with Advanced Java Concepts the first amongst the advanced concepts in Java is exception handling so first of all what is an exception an exception is an unwanted or unexpected event which occurs during the execution of a program at runtime that disrupts the normal flow of the program instructions error versus exception error an error indicates serious problem that a reasonable application should not try to catch whereas exception indicates conditions that are reasonable to an application that might try or to catch now how does a jvm handle exception there is a method called default exception handling whenever inside a method meod if an exception is occurred the method creates an object known as exception object and hands it off to the runtime system that is jvm the exception objects contain name and description of the exception and the current state of the program where the exception has occurred so this is how the exception is handled let us try to execute a simple program based on exception handling to understand it in a much better way so this particular example is based on exception handling in in Java so this particular program is related to divide by0 exception where the given number will be divided by 0 so anything cannot be divided by 0 so this particular exception is called as divide by0 exception and we cannot divide any number by zero let us run this program and see the output you can see that the program has been successfully executed and the output is been generated which says can’t divide it by zero now moving ahead the next Advanced Java concept is multi-threading multi-threading in Java is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU each part of such a program is called as thread threads are lightweight processes within a same process now let us try to execute a sample program to understand multi-threading in a better way now this particular example is based on multi-threading in Java we’ll be creating multiple threads like one or two and we will be seeing if that particular thread is existing and running or not now let’s try to execute this program and see the output don’t worry about the codes we will send you at your request if you provide your mail ID now you can see threads are created here thread one and thread 2 have got created and thread one is running thread 2 is getting started and also thread 2 is also running now you can see the functionalities of thread 1 and thre to and they are existing safely now with this let us move ahead into the next concept which is call by value and call by reference in Java call by value and call by reference in Java is just function calling firstly call by value means calling a method or a function with a parameter as value through this method the argument value is passed to the parameter while on the other hand call by reference means calling a method with a parameter as a reference which is the address of the value let us execute one example each to understand them in a better way so this particular example is based on call by Value method here we will be providing the values of A and B and call the function swap so this particular function is based on swapping the values between A and B so the values of a is 30 and the value of B is 45 so after calling this swap function the values of A and B will be swap now let let’s execute this program and see the output as you can see the programs has been successfully executed and before swapping the values were 30 and 45 now the values are exchanged now with this let us move ahead and execute an example based on call by reference so this particular example is based on call by reference we are performing the same swap function here but here we are providing the address of the values now let’s run this program and see the output you can see the program has been EX executed and the values have been successfully swapped now let us move ahead and understand the next Advanced programming Concept in Java that as method overloading and Method overriding method overloading is a feature that allows a class to have more than one method having the same name if their arguments list are different it is similar to Constructor overloading in Java that allows a case to have more than one Constructor having different arguments list now let us execute a sample program to understand method overloading in Java so this particular example is based on method overloading in Java here we have two different methods on the same name the name is ADD and the first method is having only two variables and the second method is having three variables now let us try to call these functions and see the output you can see both the functions have been executed and the sum is been displayed in the output console here so this was method overloading now let us move ahead and understand method overriding in Java in any object-oriented programming language overriding is a feature that allows a subass or a child class to provide a specific implementation of a method that is already provided by one of its super classes or parent classes method over adding is one of the major way in which Java can achieve runtime polymorphism now this particular example is based on method overriding here we have two different functions so the first function is in the parent class which is move and the second function is with the same name which is move that is existing in the child class that is dog both these methods are implemented in the main class and the functionalities of both the methods are included in the main class now let’s try to execute this program and see the output as you can see the program has been successfully executed and the output has been generated now let us dive into the conditional statements which are available in Java the conditional statements describes the compiler to carry out the execution of a particular code segment in a program until the condition is satisfied the types of conditional statements available in Java are ternary operator F operator LF operator LF ladder nested if breake and switch let us execute some examples related to all these conditional operators one by one firstly we shall execute an example based on if loop as you can see this particular example is based on if Loop here I’m providing a number which is a negative integer number minus 10 and here I’m providing an if condition which says that if the number is greater than zero then I should be printing a prin of statement which is number is positive else my interpreter will be printing the message the number is negative now let us try to execute this program and see how does it work as you can see the output has been generated which says the number is negative since the number which I provided was a negative integer number the condition here is failed and the message which was lying outside the if Loop which is the number is negative is been printed here now let us execute the next control statement where which is the lsf statement as you can see this particular example is based on lsf Loop here I’m trying to provide an integer value to the variable a according to my condition if the number which I have included results in a modulus is equals to 0 then I should be printing the message as even number else I should be providing the number as odd number now let us try to execute this program and see how does it work now as you can see the output screen is asking me to enter an integer value let us try to input an even number as you can see I have inputed an even number and I have received an output as an even number as the condition of the if Loop is been satisfied now let us try to input an odd number and see if the else Loop is working properly or not as you can see it is asking for an input now let us try to input an odd number which is 7 and see the output as you can see the output is generated as an odd number which means the L Loop is working fine now let us try to execute another example based on lcf Loop here I’m trying to execute an example based on ear I’ll be trying to input an year which the program will find out if it is a leap year or not the condition I have provided for if statement is if the ear modulus is equals to equals to Z and year modulus 100 is not equals to 0 or E modulus 400 is equals to equals to 0 then I must print the the message the ear you have entered is a leapia this means all the conditions which are stated in the if Loop must be true else it should print a message which says the ear you have entered is not a leap year now let us try to execute this program and see how does it work as you can see the output screen is asking me to enter an ear now let us try to enter a leapia as you can see the conditions which are provided in the if statement are true and we are printing the message the ear you have entered is leapia now let us try to provide an input which is not a leapia as you can see now it is asking for an Year let us input the present year which is 2019 and see if it is a leap year or not as you can see the conditions which were provided in the if Loop are not satisfied and the program is printing the message which is the year you have entered is not a leap year now let us try to execute some programs based on F’s ladder in this particular example we are trying to execute LF fladder condition as you can see here I’m trying to provide an integer typee input to the variable Choice according to the choices I have provided the first choice will select a sedan type class car and the second choice will select SUV type Class Car the third choice will provide Sports type class car and the fourth choice will provide crossbreed type class car if the provided input is neither of all these four then it will provide the last message which is invalid Choice as you can see the first F ladder will compare the choice if the choice is equals to equals to one then it will print the message sidan class and the next lsf ladder will compare the choice if it is equal to equal to two if it is equals to two then SUV class will be printed and in the next lsf ladder if the choice is equals to three then Sports class message will be printed and followed by that lsf ladder you’ll have the next ladder which will compare the choice to be equals to equals to 4 if it is true then crossb segment message will be printed if neither of all these conditions are true then finally an else block will print a final message which says it is an invalid choice now let us try to execute this program and see how does it work as you can see the program has been successfully executed and it is asking for a choice now let us try to select SUV type vehicle for that we need to provide an input as two as you can see the SUV class me is successfully selected now followed by this program let us execute nested F condition this particular example is based on nested if condition in this particular example I’m going to provide inputs for three numbers ns1 is = to 20 N2 is = to 30 and n 3 is equal to 10 and finally we have another integer type variable which is greatest using the netive condition we’ll try to find out the greatest number out of all these three as you can see the first if statement has the condition if N1 is greater than equal to N2 then it should enter an inner F Loop inside the inner F Loop we have a condition which says if N1 is greater than or equal to N3 then it should enter the loop and print greatest is equal to N1 else it should print greatest is equal to N3 after the completion of the if condition if neither of the statements which are provided in the if condition are true then the control will flow into the else condition inside the else condition we have an if condition which states if N2 is greater than or equal to N3 then it should print N2 else it should print n three now the final output will be generated along with the message which the largest number is and the greatest value now let us try to execute this program and see how does it work as you can see the output has been successfully generated and it says the largest number is 30 now let us try to execute an example based on ternary operator this part particular example is based on ternary operator as you can see I’m trying to provide an input to two numbers which are A and B which will be integer values this particular statement is our ternary operation this states that if the provided input a is greater than b then a should be declared as the greater number else if the condition is false then B should be declared as the greater number now let us try to execute this program and see how does it work as you can see the program has been successfully executed and it is asking for a value for the variable a let us enter 10 now it is asking for a value to the variable P let us enter five now let us see the output as you can see the output is 10 this states that the number a is greater than number B now let us try to execute an example based on switch conditional statements so this particular example is based on switch conditional statement here I’ll be ask a question as enter any month so I’ll be entering an integer value to the variable month if the input value is one then the program will execute January if the input value is two the program will execute February similarly if the input value is 12 then it will execute December and if neither of the cases match to the input which I provide then it will execute a default message which will be invalid input now let us try to execute this program and see how does it work as you can see the program has been successfully executed and it is asking me to enter any month let us try to input three as you can see see March is the message which has been printed by the program now let us try to execute an example based on break statement as you can see in this particular example I have provided an integer array which has the values 10 20 30 40 and 50 and here I’m trying to print the same array using a print statement with a provided condition if the number is equal = to equals to 40 then the follow Lo should terminate at that particular instance now let us try to execute this program and see how does it work as you can see the output has been successfully generated and the values 10 20 and 30 are printed but 40 and 50 are not printed because at this particular if statement we have provided a condition that if the number is equals to equals to 40 then the control flow should break so these were the few examples for conditional statements now let us continue with our Loops in Java we have three types of Loops firstly the for Loop next is wi Loop and finally we have do wi Loop the first type of loop is the for Loop the for Loop is a conditional flow statement which allows you to execute a specific code segment for a finite number number of iterations for a follow Loop we have three arguments namely initialization variable the condition variable and the counter variable which might be either increment or decrement now let us try to execute a program to understand for Loop in a better way before we execute an example of for Loop let us see the flow diagram of the for Loop here we have the initialization Step at the first and later the control flow will enter a conditional statement if the conditional statement happens to be true then a particular code segment or a particular set of statements are executed and after that the control flow enters into the increment or decrement variable and the variable will be incremented or decremented according to the condition provided once after the increment or decrement process is finished then the control flow will again enter into the conditional statement and verifies the condition if the condition is true then the same Loop will be executed else the control will exit from the condition statement now let us try to execute a program to understand this in a better way this particular example is based on fur loop as you can see I have a variable by the name ARR data which is of string type and this particular variable holds five elements which are John Jerry Ralph Jim and Tom which happen to be the names of the employees of a particular company now we will be using a follow Loop to display the names of these employees this happens to be the for Loop where we have the initialization variable which is I is equals to 0 and followed by that we have a conditional statement which is I is less than ARR data. length and finally we have an increment variable which is I ++ now let us try to execute this for Loop and see how does it work as you can see the loop has been successfully executed and we have our output here let us move on to the next example of fall Loop which is either called as enhanced for Loop or Advanced for Loop in this particular for Loop we will be having a conditional statement at the very beginning of the program the control flow enters the conditional statement and finds if there are any elements present in the array or not if the statement is true then the control flow will enter the initialization statement where a variable will be initialized once after the initialization is finished the control flow will directly enter into the condition statement of the program if there are any elements present in the program and the condition is true then it will execute the set of statements and initialize the local variable and once after the local variable is initialized then the control flow will continue into the same loop again if there are no elements present in the array then the control flow will exit the condition and stop and here as you can see if we come back into the initial conditional statement if there were no elements present in the array then the condition will become false and the control flow will directly exit the condition and comes to a stop now let us try to execute a program to understand this Advanced fall Loop or enhanced fall Loop in a much better way as you can see I have considered the same example of the list of employee names and here we are using the advanced for Loop which states that the control flow must enter the array and print all the elements present in the array according to their index now let us try to execute this program and see how does it work once after the control flow will enter into the array all the elements present in the array are printed until the last index value as you can see the program has been successfully executed and the output has been generated with this let us try to execute nested follow Loop before executing an example let us try to understand the flow diagram of the nested for Loop in a nested for Loop the program will begin at start and the control flow will encounter the first Loop statement after that the control flow will enter into the condition if the condition is true then it will enter into the inner fall Loop if the condition is false then the control flow will directly exit the first outer fall Loop now let us see if the condition is true once the condition is true then the control flow will enter into the inner for Loop and inside the inner for Loop it will encounter a condition statement if the condition is true then the control flow will start to execute a set of statements which are present inside the inner fall Loop and once after the statements are executed it will enter into the increment or decrement statements once after the increment or decrement is done the control flow will again enter into the condition statement and checks if the condition is true or not if the condition is true the same Loop will execute again and if the condition is is false then it will exit the condition statement and it will enter into the increment or decrement variable of the outer fall Loop once after increment or decrement of the out of for Loop is done it will again check the condition in the out of for Loop and if it is false then it will exit now let us try to execute a program to understand this in a much better way this particular example is based on nested for loop as you can see I have considered an integer type variable which is array which which is going to be a twood dimensional array and this particular Loop is our outter for Loop and this particular Loop is our inner for Loop once after the outer for Loop is triggered it will start the inner for Loop once after the execution of inner for Loop is finished then the inner follow will trigger the outer follow Loop for increment or decrement once after the increment or decrement is done then the condition is verified and the control flow will enter into the inall loop again once after the inall loop is executed then it will again trigger the aut ofall Loop and the condition is checked if the condition is true the process will continue else the control flow will exit both the fall loops and execute the statements which are present outside the loops now let us try to execute this program and see how does it work as you can see the program has been successfully executed and the data present in the row one and row two have been successfully printed here as you can see this is the first row which is row zero and this is the second row which is Row one and the data in the row zero is 1 2 and the data in the row one is three and four now let us learn about while loop while loop is a control flow statement that executes itself repeatedly until a given Boolean condition is satisfied while look can be considered as a repeating if statement let us see the flowchart of the vile Loop to understand this in a much better way as you can see in this particular example the control flow will begin at a decision if the decision is true then a particular segment of code is executed and again the control flow will enter into the decision box if the condition is true then the loop is repeated else the condition will exit the decision box let us try to execute an example to understand the V Loop this particular example is based on while loop here I’ll be providing an input to the integer type variable which is num and according to the while condition provided here we’ll find out if the input number is a prime number or not a prime number for that we have provided a condition in the while loop which states that if the variable I is less than or equal to the number divided by two then it should enter while loop and inside the while loop we have again a condition which states that if the number modulus I is equals to equals to Z then flag will be set to true and the control flow will be broken here and I will be incremented and outside the V Loop we have an if statement which states if the flag is not true then we should print it is a prime number else we should print it is not a prime number now let us try to execute this program and see how does it work as you can see the program has been successfully executed and it is asking for an input now let us try to input a prime number as you can see the output is 3 is a prime number similarly now let us understand do while loop two while loop is considered to be a conditional statement which is completely similar to the normal while loop the only difference is that the doy Loop has a Boolean or a conditional statement present at the end of the loop this makes the doy Loop execute at least for once to understand this in a better way let us check out a flow diag R in this particular example the control flow will first encounter the statement so this particular statement will be executed at least for once without checking the condition once after the statements are executed the control flow will enter into the conditional statement now the condition is checked if the condition is true then the same statements will be executed once more once after the statements are executed then the condition is checked again if the condition is true then the same Loop will be continued else the control flow will exit the condition now let us try to execute a program to understand this in a much better way this particular example is based on doile Loop so in here I’ve considered an array into which I’ll be entering elements the process of entering the elements will continue until I provide an input zero and finally all the numbers which I have provided into the AR AR will be summed up and the final summation of all the elements present in that particular array will be printed now let us try to execute this program and see how does it work as you can see the program has been successfully executed and it is asking me to enter the numbers let us try to enter a number other than zero my first number will be 9 and after that let me enter another number other than zero which will be 7 followed by that 5 as you can see it is continuing to accept the numbers which are other than zero and now let us try to enter zero and see what happens as you can see the loop is been terminated and the sumission of all the numbers which are provided into the array are summed up and the summation is provided as 25 so with this let us execute the next type of loop which is infinite Loop before we continue into the infinite Loop let me provide you a simple example to understand while loop and do V Loop in a much better way you must be familiar with the Road Runner Cartoons as you can see the Road Runner here is running on V Loop and the coyote which always tries to hunt the Road Runner is trying to execute itself using a do while loop so here the condition was checked first and the Road Runner is safe and in the case of coyote it was using a dowi loop and executed itself without checking the condition and it is outside the CLI so this is the basic difference between the V Loop and the two vile Loop now with this let us enter into the infinite Loop the infinite Loop is not actually a practically designed Loop instead it is a situation where a condition of the loop fails and the execution process until you stop it manually let us try to execute a program to understand infinite Loop in a much better way so this particular example is based on infinite Loop where I have provided a v Loop so here the condition of the V Loop is always true and the control flow will enter into the V Loop and will print the message edura let us try to execute this program and see how does it work as you can see the program has been successfully executed and it is continuing to print the Eda message continuously now I have to stop this manually and exit the infinite loop as you can see the infinite Loop has been successfully terminated now objectoriented programming so guys this is one of the software design methodologies that how we going to write a software solution in the industry and it’s followed widely so what is this objectoriented programming it’s a methodology or a paradigm using which we can design our software Solutions now there are two major Words which you need to focus on the first one is object and the second one is class now why object comes first in class later because of the term itself object oriented not class oriented so we’ll discuss on these objects and classes so guys object is a real world entity when I say a real world entity what does it mean it means anything which you can see touch feel is an object for example la laptop mobile phone chair table fan anything even you and me are the objects so every object will have some State and behavior what’s a class class is a blueprint or I can say it’s a drawing of an object so how an object will look like how object is going to be represented that we can do by having this guy called class so let’s say there is a class called Dog which is a represent ation how a dog will look like so we will have a representation in two of the ways the first one is properties and the second one is Behavior now properties are also referred to as attributes for example what is the weight what is the age what is the size color breed so these are the properties I can even say that they are the attributes which are linked to your object Behavior goes like eat sleep run back Etc and Etc so let’s say a nose over here is used for having a process called breathing or respiration respiration is a behavior so we have object with the properties and behavior so object will have properties object will have behavior and these properties and behavior will be written in the class to describe the object so having object oriented programming approach we can have different type of objects so this properties will remain same but the value for their properties will change now the size age color and breed for all the different dog objects it’s going to change guys right so even when I talk about something like employer to a company let’s say plumber electrician Carpenter let’s say HR let’s say software engineer now the different employees they have the same details that’s like what is their employee ID what is their name what is their age what is their fold but the data for these properties will be different now same way the sleep pattern would be different for different people right so this is what we are going to understand that different objects they will have the properties same properties but with the different values right so I can say an object is a container which is containing properties and behavior both now how we are different from procedural approach the way we used to write programs in C so how is it different right let’s have some comparisons coming in here so object oriented programming is a bottom to up approach what does this mean this means you think of an object first and then you start coding you think of data first top down approach is like where you just start writing the program we modularize our program into objects whereas in procedural approach we need to write functions for security we have access modifiers we got default private public protected but there we have no excess modifiers objects can move and communicate with each other through member functions but whereas in functions we don’t have objects so data is just moving freely so having access modifiers are a software solution can be designed with much more security right as compared to procedural approach and lastly we have have features like overloading overriding inheritance and many other features which objectoriented programming will give us so that we can very easily design our softwares which procedur programming will not do that now there are four major fundamentals when it comes to object oriented programming structure guys we got encapsulation abstraction polymorphism and inheritance so these are the four major building blocks of any object oriented programming language right so we even call them the pillars for the oops so we’ll discuss them one by one to begin with what is inheritance so guys inheritance is where the property of an object will be acquired by the other object we have a relationship called is a relationship so it’s a parent child relationship so having this relationship let’s say animal is the parent mammals reptiles amphibians and birds they are the children so this is is a relationship bird reptile mammal is an animal right that is how we are relating them we also call this concept as generalization because here we are generalizing so many different types as one single type right so we call animal as super or the parent class whereas mammals reptiles amphibians Birds they are known as sub or the child classes so guys let us have one example on inheritance and therea let’s try to code it so consider that there is an object structure called Product so product is going to have a product ID product will have a name product will have price so these are few of the attributes associated with the product right now I’m taking this use case let’s say we are to develop an e-commerce solution for an e-commerce solution now there will be a product which can be an LED TV so LED TV will extend the product right so is a benefit of extending LED TV from product so you’ll get all these attributes in the LED TV as well right so we just need to write additional parameters so we will come here and say what is the BR and what can be the technology for LED TV and any other attributes if you want to have we can have a mobile which can extend the product so we can have Ram what is the OS what is the SD card size and many more attributes so extension is what is called inheritance so if we don’t have extension so how the things will work let’s see that with no extension we need to rewrite a similar code snippet again and again so you see p name price brand technology is the data associated with LED TV same is with the mobile so P name price they are the common attributes so when we know that we have some common attributes or common properties which will be Reus again and again this is like repeating the code again and again whereas when we are coming up with this structure here so we are reusing the similar code again and again you have product as one guy and you now keep on reusing it again and again so let’s try to come up and write one small program here and understand this example so I’m going to say a new Java project so we are using Eclipse as an ID so you can use intell J developer so whatever you want to use you can use that let’s say a new Java project I’m going to say oops so in this objectoriented programming structure on the SRC I’m going to do a right click and say a new class now this new class over here let us name it inheritance app with the main method so I’m going to write a package let’s say cod. edura so this package name cod. Eda contains inheritance app with the main method right so we know what is main main is executed by jvm right when my program will run now let’s come here and write this class as product and I’m going to write one Constructor here here with says ceso product object constructed and thereafter let’s have some attributes we got product ID what is the name and let’s say what is the price so we can even have more attributes but I got these many details so I’m going to write methods now so this is Constructor the default one so the methods I’ll say void let’s say set product details where I will say let’s take three inputs P ID name and price so I’m going to say this. p ID is p ID this dot name is name and this dot price is price so we call this guy as a method which is setting the details into the the product object I can even say to write data in product object we have this method we also call the methods as behavior and attributes are also referred to as state same way I’ll have show product details where I will come and say cisu let’s see plus product just give me a moment all right so I’m going to say product ID this and thereafter I’ll just have this coming in now I will say ciso name back SLT plus the name the next way we have price back SLT and the price so this is the method which will read the data right so to read data from product object so we call this structure this class product is textual representation how an object will look like in the memory right you need to understand that this P name price they do not belong to the class they belong to object so whatever we write in class is in actual property of object as we are describing the object right so using class you are textually describing the object so P name price they do not belong to class Constructor the methods they belong to the object so if you want something to be property of class if you want anything which should belong to class make it static right so this is what you need to do now coming here guys let us create the product object so create an object what object I want product object let’s say product is a new product so remember this statement is an object construction statement but product is not an object it’s a reference variable which holds the hash code of the object in hexa decimal notation so what does this mean this means that if I will say product is plus product so when you run this code here as Java application you will get to have a product object constructed and this guy reference variable is giving you this 7852 e922 so we get 7852 e922 as a hash code now this might vary from system to system right so we say product is a reference variable right so product is a reference variable not an object it is pointing to the object which is created in the memory in the heat so next is writing data in object so I will say product dot set the product details let’s say product ID is 101 let’s say name is iPhone x let’s say the price is 70,000 so this is the data within the object which we have wrote and now let’s say reading data from object you will say product dot show the product details when you run this code here let me comment out this structure here and here after writing the data I’m just going to put up this C statement data written in product object so just to show this so we got product object constructed and then data written in product object and this is data with respect to your product object so this is how we get to see data within the object write and read operations very basic structure of an object now we can even write the data directly coming here let’s write the data directly so I can say product dot P ID let me create another object so I’m going to say a product this time let’s say this as product one is a new product or let’s say this is a product two this guy is product one and here I I’ll say Product 2 do p is 2011 Product 2 dot name is Nike shoes Product 2 dot price is let’s say 5,000 so this is writing the data directly sorry my bad so this is integer so you’ll say Product 2 dot show the product details so just going to do an empty print line here for the correct output so what you see is product object constructed we are not writing the data using any method we are writing the data directly and you see the data read operation happening again so if you don’t want the data to be written directly you can make the attributes go as private so having your attributes as private so you are limiting the user not to write the data directly you see you are now getting an error here so I’m not going to make everything private let’s say the product ID is private so when you have any attribute marked as private you will not be able to access it so this is an error now since attribute marked as private cannot be accessed you cannot access an attribute which is marked as private so what we will do now so we can have an indirect way to access P ID we can create a method which says set the P ID you take integer as input and you say this dot p is p ID so guys when I’m using this so This Means reference to the current object so this means reference to current object so the left hand side P belongs to object right hand side P belongs to the method set P ID okay so LHS belongs to the object and rhs belongs to Method so we can similarly say in get P which returns back the PID So when you say set p and get P ID what does it mean so these are the special methods we call them Setters and getters seter and getter is required when you have your attribute marked as private so you have some indirect way of capturing these details in your object so now I can come here and say Product 2 do set the P ID as 2011 now this is going to work for us so I think the basic product object structure is clear to everyone now moving ahead into our use case where we are going to extend the product right so let us take one example of mobile and extend the product now I’m going to say a class called mobile with it extends product so this is known as a relation where we say mobile is a product and here mobile is child and product is parent so what I’ll do is I’ll create a mobile Constructor and say a ciso mobile object constructed right so this is how we going to deal with the object now let us comment out this code snippet in the main so instead of having the direct product object I’m going to write a mobile object now so I’ll say a mobile is a new mobile now whenever I am requesting for the mobile object right so we are requesting to get mobile object constructed so this is what we are doing here now when you write this instruction what you see is before your mobile object is constructed project product object is getting constructed so it’s like parent object is constructed before the object of child right so what is the behavior here so product object gets constructed before the mobile object so as a rule of inheritance it is like firstly you get the parent object constructed and then the mobile object constructed so guys I hope this is clear right so what is happening here we have parent object constructed before the mobile object as this becomes the rule to inheritance and we say this is object to object now you will be glad to see that everything whatever product had will be acquired in Mobile right so we can come here and we can say mobile do set the product details mention the P ID let’s say 301 mention the name let’s say iPhone x mention the price let’s say 70,000 and then you say mobile dot show the product details when you run this code you get to see that a product object constructed mobile object constructed data written in the product object and you see the details flowing for you so guys I hope this is clear right so whatever you had in the parent you got in the child right so we have the things coming up for the child and we can very easily access those things now this product over here we can have something like let’s say string what is the OS int what is the RAM and int what is the size of SD card right so let’s say SD card size now these are additional attributes additional attributes of mobile other than the product so these are the additional attributes now what I’m going to do is I’m going to have this guy over here called set product details let’s do a copy here and let’s try to do a paste here now I’m going to say string OS int RAM and int SD card size so here I’ll say this dot OS is OS this dot Ram is RAM and lastly this dot SD card size is SD card size you see p is not accessible we getting an error here it says it’s not visible because it’s marked as private so private is not inherited and visible into the child all right I’m going to make this p as default so we talk about the excess modifiers later
but we are focused on understanding the oops here now we actually have this same method name set product details right so we have redefined the same method from the parent into the child with different inputs so we got two methods in the child so we have now two methods in the child one from parent and one of child right so both are different as in based on inputs right even though name is same even though name is same they are different based on the inputs so whatsoever belongs to the parent that is inherited into the child and now in the a child we have the same method coming up again why we did this because we wanted to set the data for the additional attributes so this is known as method overloading same method name with different inputs so what I can do now is why to access the parents method here I can have my own method mobile do set the product detail with the p ID let’s say 301 name let’s say iPhone X price let’s say 70,000 OS let’s say iOS Ram let’s say 4 SD card size let’s say 128 and thereafter I’m going to say mobile. show the product details now when you run this code guys what we see is it says data written in product object so what I can do is I can just manipulate this and I can say data written in Mobile object when you run this code you see data written in the mobile object but whatever you are reading is the one which was inherited from the parent so this read method show product details is inherited from the parent and that is being used here so hence we cannot see more than three details I’ll redefine this method as well so let’s redefine show product details as well but here we have same inputs two methods one from parent one in child and we have same signatures when I say same signatures it means they have same input details so what I’ll do is I’ll extend the data here so we’ll have OS we’ll have RAM and we’ll have SD card so we’ll have this OS RAM and SD card science now what you will observe is that when the show product details will be executed so we got two show product details method one in the parent one in the child so child method will be executed and not the parent method so this fundamental over here is referred to as overriding very very beautiful concept guys so overriding versus overloading method overloading whereas this is Method overriding so same method name with same inputs in parent child relationship so only in a parent child relationship now when you run this code here what you see is the other details also coming in now we know the reason that why we need to overload a method why we need to override a method we need to overload a method so that we can write the exact data which we want so we are customizing this method in the child we are overwriting the methods so that we can display more data so we are customizing the methods in the child right so overloading and overriding is what where we are having customizations to predefined methods we don’t want these predefined method we want the way we want to present the data and we have it in front of us so this is a very quick introduction to objectoriented programming structure guys so now let us come here and understand the next part so inheritance is where one object will acquire the properties of other object it’s is relationship the parent child relationship so synthetically you need to come up and say extends so which is extension right what are the advantages code reusability so we are reusing the code having an extensibility we are using overriding we are even having the features to hide the data if you privatize any attribute you won’t be able to inherit it so we got different types of inheritance so you got single level multi-level and hierarchical where single level is one parent one child multi- level is parent to child to grandchild and hierarchy is having one parent with more than one children multiple inheritance that’s opposite of hierarchy is not supported in Java so there is no virtual keyword there is no pointer technique in Java by which we can solve the problems like dreaded Diamond here so in single level inheritance we got one parent and we got one child so arrow is upwards because B is an a right so it’s extension relationship then we have multi level parent to child child to grandchild and thereafter guys we got hierarchy where one parent with the multiple children so remember we don’t have support for multiple inheritance in Java that’s like the reverse of this hierarchy multiple parents having the same object next is polymorphism so guys it is having the same name with the different different definitions so you can say mothers they are the best example of polymorphism they handle kids they handle office they handle home more than one form right so here polymorphism can happen in two different ways compile time and runtime so what is compile time versus runtime so compile time means overloading we call it static polymorphism so compiler will ensure which method will be executed for which function call so there are some rules to overload the method name should be same and the argument list or the inputs to the method that should be different and unique so the other form is runtime polymorphism that’s like Dynamic polymorphism where we got Method overriding All right so overriding we got some rules coming in here so the rules to override is where the method name should be same input should be same return type is something which must be same or the subtype of the overden method and excess level it must be same or more restrictive now what is abstraction guys so abstraction is achieved using abstract classes and interfaces so this is where we achieve a runtime polymorphism in a different approach right so here we have an abstract class so an abstract class is created using an abstract keyword so here we will have the methods with abstract keyword we even have non-abstract methods this is a class for which you cannot create objects you can have Constructors you can have static methods but we cannot create the object right so you can even have the final methods substract class X as a template for the various methods and definitions to be executed so moving ahead so the better version of abstract class is an interface so interface is a blueprint for a class which will contain some constants and Abstract methods so it will enable a multiple inheritance and helps in achieving the loose coupling so a class can extend a Class A Class implements an interface now this is one of the major differences between classes and interfaces so we got interface to interface inheritance as well so guys abstract class and interfaces so as in practically we’ll see it in our other sessions so lastly what is encapsulation where we are going to privatize the data so we can have an attribute we can mark it as private and when the attribute is marked as private it cannot be accessed so we need Setters and Getters so as to access this private data so so encapsulation leads to data hiding so it is focusing on security what are abstract classes in Java abstract class in Java act as a boundary between the implementation method and its functionality it is used to exchange the functionality between the concrete class members and the abstract class abstract classes are considered as those classes that hide the method implementation details from the user and show only the method functionality they declare using the keyword abstract and these methods can include abstract as well as non-abstract methods in them with this let us continue with the next topic which is why do we need an abstract class in Java we need abstract classes in Java for the following reasons firstly default functionality abstract classes are designed to provide a default functionality of the defined method for all the sub classes next template abstract classes provide a template for future specific classes next code reusability abstract classes allow code reusability followed by that we have separate method definition abstract classes separate the method definition from the inherited sub classes next we have loose coupling abstract classes help the users to achieve loose coupling between the class members and class methods last but not the least which is dynamic method resolution abstract classes support Dynamic method resolution in runtime with this let us jump into our next topic which is rules for using abstract classes in Java to use the abstract classes in Java we are supposed to follow the rules defined as below firstly in any project or a program always remember that the abstract class cannot be instantiated the next one is an abstract class can also accommodate final methods next an abstract class must always be declared using the abstract keyword followed by that an abstract class can have both abstract as well as non-abstract methods finally it can have Constructors as well as static methods so these are the rules required to use abstract classes in Java with this let us now understand the ways to achieve abstraction in Java abstraction is one of the objectoriented programming practices to achieve abstraction in Java we have two methods first using an abstract class and the next method using an interface now let us understand the Syntax for using abstract classes in Java for defining abstract classes and Abstract methods in Java we have the following syntax firstly let us understand the syntax to declare an abstract class in Java for example here I’m declaring a class by the name edureka and I’m using abstract keyword here here now similarly let us understand how to declare a method using the syntax the Syntax for declaring a method is almost similar to the syntax of declaring a class the only change is that the use of parenthesis and a semicolon with this let us try to execute some practical examples of abstract classes in Java to understand the terminology in a much better way the first example would be student information after this we shall execute two more examples the examples will be same but implementation will be different first we’ll use an interface to execute the same program followed by that we’ll execute the same program using an abstract class this is done to understand the difference between an abstract class and an interface now let us execute our first example as you can see this particular example is based on abstract classes you can see that I have used the abstract keyword to declare this particular class which is person this person class includes private data members which are name and gender similarly I have also included another method which is an abstract method and I have declare that method using the abstract keyword and inside the abstract method I have to written some data related to the person class now let us move on to the next class which is the student class this particular student class is a normal class and this student class is extending the abstract class which is person inside the student class we have some information related to the student which are student name student gender and student ID here we will be extending the abstract class which is person into the student class and from there we’ll be extending the details of name and gender now let us try to execute this program to understand this in a much better way as you can see the program has been successfully executed and the data is also been displayed here according to the output the names of the students are Priya Karan Kumari and John and their respective genders are also been displayed here now let us try to execute an example based on interface the program that we decided to execute based on both interface as well as abstract class is to find out the area of two shapes which are rectangle and circle now let us try to execute this program and see how does it work firstly we shall Implement interface as you can see in this particular example I’m using interface and inside the interface I have described two methods which I draw and area here we have provided input to both the methods which I draw and area for both the shapes which is circle and rectangle now let us try to execute this program and see the output as you can see according to the data provided to both Circle and rectangle here are the outputs of their area now let us execute the same program using an abstract class as you can see this particular class is the abstract class which is shape and inside the shape we have two methods which are the area of the shape and draw function followed by that we have the class rectangle which extends the abstract class which is shape and inside the rectangle class we are implementing draw method as well as area method similarly followed by the rectangle class we have Circle class which extends shape abstract class and inside the circle class we also have draw method and area method finally we have the class edura where we’ll be providing the data for rectangle class as well as Circle class now let us try to execute this program and see how does it work as you can see the program is successfully executed and the area of rectangle and circle are generated you can see that the area of rectangle is 600 followed by that the area of circle is 628 with this let us move on to our next topic which is the difference between an abstract class and interface the first difference between abstract class and interface is abstract class can include abstract as well as non-abstract methods while interface can have only abstract methods the next difference is abstract class includes non-final variables on the other hand interface can include only final variables followed by that abstract class can include static non-static final and non-final variables compared to abstract classes interfaces can include only static and final variables the next difference is abstract class can Implement an interface while interface cannot Implement an abstract class now we shall discuss how to implement abstract classes as well as interface to implement an abstract class we use the keyword extents and to implement an interface we use the keyword implements the next difference is abstract classes can extend Java classes and interfaces while interface can extend only an interface the last difference is that members can be private as well as protected in an abstract class while in an interface members are declared as public by default why do we need inheritance to understand this let us consider a simple example of two different watches first one is a classic dial watch and the next one is a modern digital watch the functionalities defined for a dial watch are display date display day and display time similarly let us get into the advanced version of the watch which would be our digital watch the function alties required for the digital watch are as follows display day display date display time light set alarm and set timer as you can see three functions from the dial watch are repeating here in real time this would be considered as code redundancy you might avoid by removing the extra code from the digital watch but it results the digital watch will be missing the three functionalities which are display time display date and display dat you might try to keep them in the digital watch and try to remove those from the dial watch but again in the real time scenario you will lose the existence of dial watch the only solution for this problem is by applying inheritance to both the classes where the dial watch will act as a parent class and digital watch will act as a child class the child class will inherit all the methods and properties of the parent class and successfully reduces the code redundancy improves the readability and the functionality of the code to an exponential level now that you have theoretically understood what the term inheritance means let us now get into Java inheritance and understand it through an example like any other programming languages Java inheritance is also known as a procedure where the child class inherits all the methods and properties of the parent class as you can see the tablet here is inheriting the properties both from laptop and a mobile phone this was a pictorial example let us see a practical example through a code in this particular example we have two classes the first one is teacher which acts as a parent class inside the teacher class we have two strings teacher and edura along with that we also have a print statement which has teaching message inside it now let us get into our child class Hadoop teacher happens to be our child class and in our child class we have a string called as spark now we will be performing a print operation with which has to access the college name designation and the main subject as you can see we have the main subject inside our child class and college name and designation of the lecturer in our parent class now we’ll try to inherit the parent class through the keyword extents and this is the name of our parent class which is teacher now let us try to run this program and see the output as you can see we have successful inherited both the messages from the parent class which is Eda which happens to be the college name and the designation which happens to be the teacher and the main subject which is spk this is been displayed from the child class and the message from the parent class which is teaching now that you have understood Java inheritance in a practical way let us now get into the types of inheritances supported by Java Java basically supports four types of inheritance namely single inheritance multi-level inheritance hierarchial inheritance and Hybrid inheritance let us discuss each one of them in detail firstly single inheritance single inheritance is a procedure where one child class inherits the methods and properties of one parent class in simpler words the whole system consists of only two classes one parent and one child let us understand this through an example here we shall consider two classes one class will be person and the other class will be employee where the person class acts as a parent class and employe class acts as a child class let us execute this program practically you can see here that this happens to be a parent class which is person which has two different functions the first function is set age and the second function is set name now let us move on to our child class inside our child class we have one method which happens to be set employe ID the methods set name and set age which are in the parent class are required in the child class as well so let us try to inherit those into this child class so this is the code for inheriting the properties of the parent class into the child class where I’ll be inheriting the properties of get name and get H into my child class to display the data of a particular employee in an organization now let us try to execute this program and see how does it work as you can see the properties of get name are in inited and I have successfully named my employee as ragir and I have set the age of ragir as 23 and accordingly his employee ID is EMP 11101 so this was single inheritance now let us move into the second one which happens to be the multi-level inheritance multi-level inheritance is a process where multiple child classes inherit the properties from their preceding parent classes to understand this in a better way let us consider a simple example as you can see in the picture Class A is the parent class and Class B and Class C happens to be the child class here child Class C is inheriting the properties from its preceding parent which happens to be Class B and Class B is inheriting the properties and methods from the superior class which happens to be Class A this was a pictorial representation now let us see a practical example through a code as you can see this is our program and calculator is a parent class similar to class A in a picture which performs basic mathematical operations such as multiplication subtraction addition and division now let us move into our class B which would be the class advanced advanced class can perform a little Advanced operations such as modulus of a number square root of a number and square of a given number and now let us move on to our child Class C which happens to be the area so this class can perform a little Advanced calculation such as finding an area of a geometric figure such as Square rectangle and circle now we need a calculator which could perform all these operations in one single class for this the only solution would be multi-level inheritance where we will be inheriting all the methods and properties of superior parent class into the succeeding child classes now we have tried to inherit all the properties and methods of the preceding parent classes into the last child class let us try to execute this program and see the output as you can see the values are already passed to all the functions now their respective outputs have been successfully displayed so this was multi-level inheritance now let us move on to the next one which happens to be the hierarchial inheritance hierarchial inheritance is a procedure where we’ll be having multiple child classes and all the child classes will be inheriting the properties from the major parent class here let us assume an example of a restaurant we shall have four different restaurants here the first one would be a parent restaurant and the other three will be Chinese restaurant Italian restaurant and Mexican restaurant the parent restaurant will be having various types of ingredients which the child classes might need in their dishes as well let us see this practically to understand this in a better way so this would be our parent restaurant which will be having the ingredients like bread vegetable stew and cheese now let us get into the first child class which happens to be the Chinese restaurant the Chinese restaurant already has noodles and Momos to cook their special dishes they might need vegetables too and cheese similarly let us get into Mexican inside Mexican they already have nachos and sweet potato for their special dish they might need cheese and vegetables toew or even bread for making some better dishes similarly let’s get into Italian which have pasta and sausage available so to prepare their special dishes related to sausage they might require bread and to prepare their special dishes related to pasta they might require cheese and vegetables too so how does all these three restaurants get their ingredients from simple they apply hierarchial inheritance and inherit all the properties from the parent class and cook their special dishes now let us run this program and see how does it work as you can see all the child classes have successfully inherited their parent and the data is also been displayed the first one is the Italian restaurant so they have requested for bread vegetable stew and cheese from the parent class and they say that they already have pasta and sausage available with them now the second one happens to be the Chinese restaurant and they say that they have requested for bread and vegetable stew from the parent class along with cheese and they have noodles and Momos already available with them similarly the final child class happens to be the Mexican restaurant and they see that they have also requested for bread vegetable stew and cheese from the barent restaurant and they already have nachos and sweet potato available with them so this was an example for hierarchal inheritance now let us move on to the next one which happens to be the Hybrid inheritance as simple as the name suggests Hybrid inheritance can be a combination of any other inheritances as you can see in the picture displayed here you can see multi-level inheritance here and hierarchial inheritance so these are the two combinations of two inheritances possible in Java The overal Inheritance pattern can be called as a Hybrid inheritance now you might be wondering about another possibility in inheritance which might be obviously the multiple inheritance here one single child class can inherit all the methods and properties from two or more different parent classes but sadly in Java this results in a diamond problem and could not support multiple inheritance it is possible to achieve this Behavior through Java interface with this we shall move to our next topic which is EA and has a relation is a relation basically deals with inheritance and interface any child class which inherits or implements a parent class is said to be in a easa relation coming into ha a relation it uses instance variables to reference the objects of the parent class this might be a little confusing let us understand it practically as you can see the BMW car is a vehicle which is inheriting the properties of a vehicle so it happens to be in a East a relationship with vehicle and coming into has a relation it has an engine so the BMW car is referencing to an object of engine class and said to be having an has a relationship with engine class let us execute a program and see this practically as you can see my child class is BMW and it is extending to the parent class which is car and also extending to another parent class which is Java so PMW class is in an EA relationship with car and in an has a relationship with engine class now let us execute this program and see how does it work as you can see the class BMW has successfully inherited both the classes which are car and engine and the properties which it inherited from car class is the color which is blue and the speed from the engine which is 256 with this let us get into our last topic which is Method overloading and Method overriding method overloading is defined as a procedure of having two or more methods with the same name within a single class provided the argument list must different method overloading is divided into three types the first type would be having different number of parameters and the second one will be having different types of data type and the third one will be the variation in the sequence of the parameters with different data types let us see each one of them practically this particular example is the first type of method overloading here in our parent class you can see we have two functions on the name of display so the first display method has one parameter which is a character type and in the second display method we have two parameters one is of a character type and the other one of an integer type so from the child class I’m inheriting these both methods and one of the object has one single parameter which happens to be the character type and the second object has two different parameters one of it is a character type and the other one is an integer type let us execute this program and see how does it work here you can see the output the first one is calling the first display method with one single parameter and the second one is calling the second display method which has two parameters now let us see the second type of O loading in here we have two display methods in a parent class one of the method has character type of data type and the other one is having integer type of data type in a child class I’m passing character type of data to the first display method and integer type of data to the second display method now let us try to execute this program and see how does it work as you can see the data has been successfully displayed the first one is calling the method display with character type and the second one is calling the method with integer data type now let us see the third type of method overloading in here we having the same two display methods in the parent class one of them is having the character data type in the first position and integer data type in the second position and vice versa in the second display method now similarly through my child class I’m passing two different parameters the first object will be passing character data type in the first position and integer in the second one and the second object in the vice versa now let us execute this program and see how does it work as you can see the message from the first display method is been executed here which shows that the first object is referring to the first display method and the second object to the second display method now let us take a step further and understand type promotion as well in one of my display methods I have provided character and double attributes whereas float and character attributes in the object The Interpreter will implicitly promote the data type of the object from float to double this type of promotion is valid since there is no other display function with matching attributes now let us try to execute this program as you can see the object has selected the first display method and upgraded the float to double the message from the first display method has been displayed here which happens to be function one now let us try an example where we should have a display function with matching attributes and verify if the promotion is accepted or not as you can see the object display is passing two data types which is an integer one and Float one and here we have the first display function with float and integer data types let us try to execute this program as you can see we have the output now in this scenario there is no type promotion since there is already the data type which is available and the parameters are matching with this we shall get into method overriding method overriding is a process where both the child and parent classes have the same methods there are also some rules for method overriding which say the argument list of the child class should match the parent class the second one is access modifier of the class should be less restrictive than the parent class and the third one is local parameters cannot be overridden local parameters in the sense the parameters with access modifiers as private static and similar ones let us see each one of these rules practically so let us execute our first example here we have defined two objects which are pointing to the display methods the first object implements the display method from the parent class whereas the second object implements the display method from the child class this happens in the runtime hence this process is called as runtime polymorphism let us execute this program and see how does it work as you can see the display methods are been implemented and the data present in the methods are also displayed now let us discuss about some key points of method overwriting first one the argument list of the child class should always match the argument list of the parent class second one the access modifiers of the child class should be less restrictive when compared to the parent class let us see this practically as you can see in my example the child class has an access modifier as public and the bearing class is having an access modifier as protect Ed this program will be executed without any errors let us try to execute this as you can see the data has been also displayed which says the child class method has been executed now let us try to change the access modifiers now the only change what I have done is I have changed the access modifier of the parent class to public and the access modifier of the child class to predict it as you can see the eclipse editor is throwing an error which says that the child class cannot have an access modifier which is highly restricted than the parent class now let us discuss our last topic which happens to be about the super keyword in method overriding the keyword super can be used in the child class to call the method defined in the parent class with its name the super method is used to invoke the Constructor defined in the parent class let us see this practically using super keyword I’m calling a method by name My Method from the parent class now let us try to execute this program and see if it can successfully call the method or not as you can see it has successfully called the method from the parent class and the data is also been displayed what is polymorphism to understand understand this phenomena let’s take an example of a chameleon I hope you all know what exactly is a chameleon in the real world you might have seen this creature changing its color based on its requirement to hide itself from the Predators if someone inquires you how does it do that you can simply say because of its polymorphic nature similarly in the programming World Java objects possess the same functionality where each object can take multiple forms this property is known as polymorphism in Java where poly means many and morph means one or more forms in this session for today we shall discuss one of the key concepts of object-oriented programming which is none other than polymorphism now that we have understood what exactly is polymorphism let us go through some examples here you can see the image the person in the middle can act in multiple forms firstly you can see the same person being a student followed by that he will become an employee of a company and also he would like to play some sports followed by that the same person is acting as an interviewer for a fresher then the same person is acting as a normal human being who is purchasing groceries and followed by that the last example of the same person being a family man you can see the same person is playing different roles at different situations this is called as a polymorphism of a human being now that we have finished the first example let us go through the second example of polymorphism here suppose you have to save contact numbers of different persons now it’s not possible that every single person in your contact list have two numbers but few of them may have so in this situation let us assume that you have a friend by name Jack and Jack has two numbers you have saved the first number and in case if you want to save the second number you don’t have to create the new method called create contact and save the second identity number you can just call the same create method what you have created for the first one and save the second number with the same name here you have saved Jack contact ID with the same name but you have two different numbers so this example is based on polymorphism now that we have discussed two examples of polymorphism let us move ahead to the next topic where we will discuss about the types of polymorphism available in Java so there are basically two types of polymorphism available in Java they are static polymorphism and dynamic polymorphism let us understand each of these in a bit detail firstly the static polymorphism a polymorphism that is resolved during compile time is known as static polymorphism method overloading is an example of compile time polymorphism so what exactly is Method overloading method overloading is a feature that allows a class to include two or more methods to have the same name but the different parameter list to understand this in a bit more detail let us go through a sample program so you can see this particular example is based on polymorphism or method overloading so in the class called my class we have created two methods the first method is my class which has the statement to print the message bricks followed by that in the same class we we have another method called my class which has the same name but inside this method we have a variable I of integer data type and inside the second my class method we have a message which says building new house that is plus I plus feet tall we are giving the height which is I so this height will be replaced here and the message will be printed so followed by this we have the void in this void method which is the info we have a message again which says houses height feet tall so this height will be replaced by the height we provide in the second my class method and followed by that we have another void info which prints the message saying S Plus houses height feet tall so you can see we have two different methods with the same name that is my class and followed by that the second my class and followed by that we have the same info or the same info method with different parameters now this is our main class which will access these two methods and print the data which we require now that we have gone through the program let’s execute this and see the output as you can see the program has been successfully executed and the output has been printed here you can see that the provided height is zero so the building is been provided as 0 ft tall if we replace the height with another number like say 100 then the program will be executed again and the updated data will be printed here so that with static polymorphism and Method overloading followed by Static polymorphism and Method overloading we shall Advance into the second type of polymorphism which is none other than the dynamic polymorphism so Dynamic polymorphism is a process in which a call to an overridden method is resoled at runtime that’s why it is called runtime polymorphism or dynamic polymorphism method overriding is one of the ways to achieve dynamic polymorphism in any object-oriented programming language overriding is a feature that allows a subass or a child class to provide specific implementation of a method that is already provided by one of its super classes or parent classes now let us execute a sample program to understand Dynamic polymorphism and function overriding as you can see this particular example is based on method overriding or dynamic poly morphism here we have a parent class and a child class the parent class is the animal and the child class is the dog so inside the parent class we have a method called move and similarly with the same name the same method is also included in the child class dog so what exactly we doing in the main program is we’re trying to call the parent class method move as well as the child class method move in our main program so let’s see and execute the program and generate the output you can see the program has been successfully executed and both the methods are being called so inside the parent class animal the method move is been executed and animal scan move message is been printed successfully followed by that in the child class dog the move method is been called and the message dogs can walk and run message is been printed successfully so with this let’s move ahead and understand the next Topic in our discussion that is the advantages of dynamic polymorphism so the first advantage of dynamic polymorphism is support for method overriding Dynamic polymorphism allows Java to support overriding of methods which is central for runtime polymorphism followed by that the second advantages it allows subclasses to add it specific methods subclasses to define the specific implementation for the same so these are the few advantages of dynamic polymorphism let us move ahead and understand the different characteristics of polymorphism in Java in addition to these two main types of polymorphism in Java there are other characteristics in Java programming language that exhibit polymorphism like coercion polymorphic coercion deals with implicit type conversion done by the compiler to prevent type errors a typical example is seen as an integer and string concatenation as shown in the following example you can see string s strr is equals to string is equal to 2 so this example is based on coercion which will be an implicit type conversion done by the compiler followed by cotion we have operator overloading an operator or method overloading refers to a polymorphic characteristic of same symbol or operator having different meanings or different forms depending on the context for example the plus symbol is used for mathematical addition as well as string concatenation in either case only text that is the argument types determines the interpretation of the symbol the first plus symbol is used in string data type so the plus will be considered as a concatenated operator and followed by that the next place where the plus operator is used is in the integer data type so here the summation of both the numbers will be performed and the output will be as this so the first one is 22 and the second one is f followed by operator overloading we have polymorphic parameters polymorphic parameters allows the name of a parameter or method in a class to be associated with different types in the below example I have defined content as a string and later as an integer the Declaration of polymorphic parameters can lead to a problem known as variable hiding here the local Declaration of parameter always overrides the global Declaration of another parameter with the same name to solve this problem it is often advisable to use Global references such as this keyword to point to the global variables within the local context now with this let us move ahead into the next topic that is the super keyword super is a keyword it is used inside the subass method definition to call a method defined in the super class let us execute a sample program to understand the functionality of super keyword as you can see this particular example is based on super keyword so here you can see we are trying to call a method from the parent class or super class using the Super Key word now let’s try to execute this program and see the output you can see that the program has been successfully executed and the method from the super class has been extended successfully into the child class using super keyword now with this we shall move ahead and understand the basic difference between the static polymorphism and dynamic polymorphism the first difference is static polymorphism relates to method overloading whereas the dynamic polymorphism relates to Method overriding the second difference is in the static polymorphism errors are resolved at compile time whereas in Dynamic polymorphism errors can only be determined at run time let us go through a code segment to identify errors in static overriding you can see the first line of code which is void difference between the numbers X and Y followed by that we have another method with the same name where we’ll differentiate the numbers X and Y of float data type and the last int diff A and B so here we identify a compile time error similarly let’s go through a code segment for dynamic polymorphism you can see the college here is the parent class and the object we creating is from the child class so the reference of parent is pointing to the child here that is college obj is equals to new student followed by that the method of child is being called which is obj do exam so this is an example for dynamic polymorphism exception is a problem that arises during the execution of a program it can occur for many different reasons say a user has entered an invalid data or a file that needs to be open cannot be found or you can also say that a network connection that has been lost in the middle of Communications or the jvm has run out of memory many such cases but if we do not handle them it leads to a system failure so handling an exception is very important and that’s where Java introduced exception handling mechanism to handle the runtime errors so that the normal execution flow will not be disrupted for example class not found IO exception SQL exception Etc now let’s move ahead and see the difference between error and exception first errors are impossible to recover but exception can be recovered by handling them next errors are of type unchecked but exceptions can be either checked or unchecked type just wait a little while and you will know what are checked and unchecked type of exceptions and errors are something that happen at runtime but exception can happen either at compile time or runtime exceptions are caused by application itself whereas errors are caused by the environment on which the application is running so these are the key points of difference between errors and exceptions now let’s see what is exception hierarchy all exceptions and errors types are subclasses of class throwable which is a base class of hierarchy here one branch is heeded by exception that is this class is used for exceptional conditions that user program should catch for example say null pointer X exception runtime exception Etc and other Branch error are used by the Java runtime system to indicate the errors that has to do with the runtime environment itself that is JRE for example virtual machine error or stack Overflow error Etc so how Java virtual machine handles exceptions whenever inside a method if an exception has occurred then the method creates an object known as exception object and hands it off to the runtime system system and this exception object contains name and description of the exception and also the current state of the program where exception has occurred and creating the exception object and handling it to the runtime system is called throwing an exception then using try catch finally methods these exceptions can be handled so this is how Java virtual machine handles exceptions internally next let’s see the differences between checked and unchecked exceptions and simp terms exceptions that happen at compiled time are checked exceptions like IO exceptions Etc and runtime exceptions are called unchecked exceptions like divide by zero array out of bound null pointed exception Etc basically unchecked exceptions are built-in exceptions in Java so checked exceptions cannot be simply ignored the programmer should handle these exceptions and runtime exceptions are ignored at the time of compilation now let’s let’s see the basic example of exception so here I have defined the class and inside the main method I have a tri block so in this tribe block the code that we are going to write May raise a exception that is it contains the code that raise exception and then the raised exception will be handled in the catch block so let’s see a small program as how it occurs first I’ll create a new package called exception edura and now I’ll create a new class called sample exception finish so inside the class the first thing that we are going to do is we are going to write the main method so here I’ll will create a string s Str and make it as null so now after this I will try to retrieve the length of the string so when I execute this program it will throw an exception why because the string is null and we are trying to retrieve the length of the string as I said it throws null pointer exception because the string is null it does not contain any values so now let’s use try and catch method to handle this exception so what I’m going to do here in Tri block I’m going to write the code that will raise an exception say I have given a 30 and B a zero now I will try to divide a number by zero like in C is equal to a by B so just tell me what happens here now say if we try to divide a number by zero then it says we cannot divide the number by zero because it raise an arithmetic exception correct so let’s see how that occurs now as it throws an exception here so what I’ll do to maintain the normal flow of execution I will write the cat block to handle the exception that is okay let’s run the program and see the output so as I told the exception has being catched by catch block so here first it will throw the exception and then it goes to the catch block catch block handles the arithmetic exception e so it prints cannot divide a number by zero so this is how exception handling works now let’s see the various types of exceptions so in Java there are two types of exceptions one buil-in exceptions and the other one user defined exceptions first let’s see what is buil-in exceptions these are the exceptions which are available in Java libraries and they are suitable to explain certain error situations like arithmetic exception array index outof bound exception class not found IO exception runtime exception number format Etc so let’s see an example and understand how built-in exception works so this example is one type of exception that is arithmetic exception where we try to divide the number by zero and it results in arithmetic exception and we have catched the method so let’s see one more example of that kind now I’ll use one more Tri block here what I’m going to do is I’m going to declare the integer number and try to pass a string variable so what happens it’s obvious fact that it throws an exception so let’s see how so just tell me one thing I have declared a integer number and trying to pass a string variable so what happens it obviously throws the exception now in order to maintain the normal flow we have to handle this exception so I’ll use a catch block and handle the number format exception so now let’s execute and see first it said cannot divide by zero because we handle arithmetic exception and next we handled number format exception next we will see how array index outof bound exception occurs and how it can be handled so here you can see I have created an array of size five and now I’ll try to access the seventh element in the array so what happens after this it will obviously throw an exception why because the size of the array is five and I’m trying to access the array that is out of bound so what happens when I catch the exception it says array index out of bound exception sorry it is array index out of bounds now again let’s execute as I said again the array index out of bounds exception got handled and it printed the output so this is how built-in exceptions are present in Java libraries so now I will jump into the methods of exceptions because you need to know the throw and throws methods to understand user defined exceptions after I complete the methods of exceptions I will explain you the user defined exceptions so these are the various methods of exceptions that is try catch finally throw and throws let’s see each of them first try try block is used to enclose the code that may throw exception the syntax is as follows as you have already seen it’s very simple we write a code that throws exception and we can handle it using the catch block next Nester try Nester try block is nothing but a try within a tri block for example you can see here I have declared one try and inside that I have created one more try catch and there is one one more try as well so let’s see a small example as how it works so I’ll do one thing here I’ll give a triy block within the tri block and then after catch I will end the statement and after that I will print like system. out. print Ln let’s print some other statement just look at the program first what I did so from here I have modified the program I have given one Tri block and inside one try block I have given one more try and catch block okay and now I have created one more try catch and handled here after that what I’m doing I’m just giving a statement as print other statement after that I’m closing this dry block then I’m again catching the exception and handling that okay so within this one Tri block there are two Tri blocks so that’s how Nest TR can be used so let’s see the output see first it’s saying that cannot divide by zero because it was the first thing that we have done and within the tri block it said number format exception because the first Tri block got executed and next for this one more exception that it WR it said it handled and again it’s printed other statement that’s all because we are not declaring anything in the other Tri block that is the main Tri block so it is not printing that exception if this drive block has thrown any exception again that would have been printed but as there is nothing it’s not printing so this is a usage of Nest a try and how it can be declared and this is how it works now let’s see the usage of catch block as in these previous examples you have already seen how it can be used and there’s also one more thing that is multic catch that is if you have to perform various task at the occurrence of various exceptions then you can use Java multic catch block so here you can see you have one Tri block and you have multiple catch blocks so let’s see how that works I’ll modify this program only for you so here I have one Tri block and I have two different catch blocks let’s execute and see so first it printed number format exception and then it printed other statement why this exception did not get handled because there was no any exception that was being thrown for this okay if there was any exception that was thrown then it would have been handled so this is how you can use multiple catch blocks next we’ll see finally finally is a block that is used to execute important code such as Closing Connection stream Etc no matter whether exception is handled or not finally block will always be executed so in the previous example you saw that after declaring a tri block you must use catch block to maintain the normal flow but on using finally block the catch block is not required let’s see how I’ll do one thing I’ll remove all the catch blocks here so I just have a tri block now I’ll give finally and print the statement okay so now let’s execute this as I said we have not used catch block it throws the exception but even on throwing the exception the flow will not be disrupted there because we have used finally block to execute the code so you can see the finally block is always executed so that’s how it works next let’s see what is throw throw is nothing but a keyword which is used to throw an exception so you can see the syntax here inside a method you are throwing an exception let’s see how it throw was an exception let’s modify this program first I’ll Define the function here so inside the throw block I’m going to throw an arithmetic exception okay now let’s handle the exception using catch block I’ll close this average function and call this function in the main method so first I throw the exception in tribe block and catched it and now I’m calling the entire function in the main method so let’s see what will be the output it’s just telling the exception is being caught correct why because when we call the average function in the main method it goes back to the loop exception will be throw but it is been catched correct so this is how throw is used to throw an exception and it can be handled the cach block simple let’s see what is throws throws is also a keyword which is used to declare the exceptions it does not throw any exception but it specifies that there may occur any exception in the method and it is always used with the method signature let’s see how again I’ll modify this program itself as I have told it is used with method signature I’m going to use the throws keyword along with the method and I’m also using a throw keyword to throw the arithmetic exception now inside the main method I’ll use a tri block so this is a example where in I’m using the throw keywords along with the method signature and inside this I’m throwing a new exception but when I’m calling the method or a function in inside the tri Block in main method it will throw an exception so instead of handling it I’m just printing the finally block so let’s see what happens so you can see here first the inside average function is printed and then it says that there is a exception in the main method that is we are throwing an exception as we are not handling that at the end it’s printing the finally block simple so this is how throws is used next let’s see the difference between throw and throws first throw is explicitly used to throw an exception but throw is used to declare an exception we have already seen how it worked next checked exceptions cannot be propagated using only throw but checked exceptions can be propagated using throws throw is followed by an instance and throws is followed by a class and throw is always used within a method and throws is used with the method signature and throw can throw only one exception and not multiple exceptions and throws can declare multiple exceptions just how we saw how it worked next we’ll see the difference between final finally and finalize so final is a keyword finally is a block as we saw and finalize is a method final is used to apply restrictions on class methods and variables but finally is used to place an important code and finalize is used to perform clean up processing just before the object is garbage collected coming to final the final class cannot be inherited and the final method cannot be overridden and the final variable cannot be changed coming to finally it will be executed whether the exception is handled or not we already saw how it worked now let’s see a user defined exception sometimes the buil-in exceptions in Java are not able to describe a certain situation in such cases a user can also create exceptions and that are called as user defined Exceptions there are two important points first one a user defined exception must extend the exception class the second one the exception is thrown using a throw keyword so let’s see how it works I’ll modify the same program first inside the tri block I’ll throw an exception using throw keyword I will handle the exception using catch block I’ll close the class now I will extend the exception using extends class so let’s par some argument here and let’s try to print the output so let’s par some argument as we have thr a new exception and when I’m extending my exception then what happens let’s C I’ve saved the program and I’m giving the value of a to B okay now let’s see what will be the output as expected it should print the value as five let’s see whether it prints the same prescribed value or not exactly we got the output as desired that is the throw keyword is used to create a new exception and throw it to the catch block and then it got handled and when we and when extending that we will get the same desired output so this is how how you can create a user defined exception now coming to the end of the discussion let’s see what are custom exceptions and how to pass an exception I’ll modify the same program again so in this case if the number that we entered is more than 100 then it should throw an exception else it should print the provided input is valid let’s see how after that I’m reading a number here and then trying to validate the input and tri block if the input is not validated then it will be handled in the catch block again this is a user defined exception so it must extend the exception class so this is how I have created custom exception so let’s run the program and check what will be the output so it’s asking to enter the number that is less than than 100 so I’ll enter 99 says valid input again I’ll run the program now I’ll enter 101 it says input is greater than 100 and it C the exception that is I have mentioned here if the number is greater than 100 then it should throw an exception and that exception is caught in the catch block so this is how custom exception can be used in Java now let’s also see how to pass an exception in this case we are going to pass a simple date format so for that I need a java. simple date format package I’ll import that now I’ll make the class as public and let’s write the code for the simple date format I’m going to create a reference called SDF so I’m going going to pass the input date that we enter so this is very simple I’ll tell you how if we enter the date in this format then it should print as valid input or else it should throw an exception let’s see how to do that so in the tri block first I have read the input date and then output date and have created a reference for them and if there is any error in case of changing the date format or while converting the date formats then that exception will be handled in the catch block and next in the main method I have used a scanner class to read the format so let’s run the program and check the output so first let’s enter the date format which is invalid so I’ll give something so it’s telling that some error has occurred while converting the date formats so it’s telling exception is here that is when we’re trying to pass the exception and the unpassable date will be so and so now let’s execute it one more time and enter the proper date format that is 0 1 01 1 996 so it’s telling after changing the date format it will be this that is the one which I have given in this format from the input date format which is in day month and year it change the output date format by passing the input date to year month and date correct so this is how we can pass the exception so to begin with guys array is a data structure to hold you know more than one values so it’s going to be a multivalue container for us so it can contain homogeneous elements so you can say it’s a limitation or it’s a plus point right so it maintains the type safety check so we cannot store different type of data in the same array so it has to be the same type so if you’re going to create an array for integers it must be only integers now all the elements they are stored under one single variable name so we have a reference variable which will be pointing to the array now the data stored in an array is a contiguous memory location it means that they are the neighbor now so there are various different types by which we can represent the data in arrays so we can represent the data as single dimensional or 1D array which is storing the elements as in a row so just consider it as a row in a continuous row we are storing the elements so that is how we started right so in a use case to store the country’s population so this element can store State one population count next element can store the other state population count so on and so forth now two-dimensional array is array of arrays right so it’s a collection of collection now so here what we are understanding two dimensional array that it’s going to hold the population for the world let’s say the first array will store the population for Indian States the second array can hold the population for some other countries different states so if you have more than these kind of problems so where you have data coming up in the form of some let’s say you want to process images right you want to rotate an image you want to process an image on some colors so here we just don’t have a two Dimension array we just not have array of arrays so we got multi-dimensional arrays so in that regard we got this multi-dimensional arrays where lot of
data can be stored so typically when you are going to come up with the image processing problem so you’ll be working in the multi-dimensional array so one of the use cases now let’s see how we can work with arrays so guys how we can create a 1D array so creating a 1D array is very basic so you give a reference variable name and you mention the data type with the new operator with the size and you’ll be able to get your array created in the ram area so reference variable with the new integer five will give you an array of five integers right so you need to be having this syntax where we can create an array now when you’ll create an array it will be indexed on the basis of size let’s say the size is five so there will be four indexes so 0 to n minus one so it going to be 0 to four for a size of five now every element in an array is accessible through this index for example when you say my array 0 isign 10 you writing the data in the zero index so thereafter you say 1 is 20 2 is 30 3 is 40 4 is 50 so you are actually writing the data into the array so a basic right operation and same way when you have the array constructed so at the time of construction you can mention the data right so the values can be given exactly at the time of construction so this time you need not to write the data so by default we’ll have the values coming in for your array so guys when we want to access any element in an array so you write down the reference variable name and you mention the index in a square bracket and you will be able to access it for example you say my array one it’s going to access the value 20 so you say my array 4 right so array four over here is supposed to be the value 50 so when you want to update something so you can just mention the index and you can give a new value so here it goes like my array 4 assign 100 so you are going to replace your array 4 as 100 so let’s have a quick practical example on 1D arrays so what I’m going to do is I’m going to create a new Java project project so let’s say a new Java project called array demo so we’ll begin with uh why we need arrays and thereafter we’ll process it further right so I’m going to say arrays with the main mathod let’s say 1D arrays the package goes like cod. edura now consider you want to store the population of a country right so you will have state one let’s say the population count is 52 same way you will have some other states coming in let’s say State 2 state three state four and state 5 right so let us see some populations are coming in for us now having this population stored in five different single value containers right so what are they they are single value containers they cannot hold more than one value so when I’m talking about State one state 2 state three state 4 and state 5 they are the different states right containing the population so I can say State one population count to be more precise right so considering that these are the different population counts for the different states of a country so rather than containing these single value containers what is a solution is to have a multi- value container right so how you’ll create a multivalue container so we’ll write one integer array so I’ll say population I’ll just write down this name as state population which goes like a new integer with five elements right so I gave the size myself that this array should have five elements so when you print out this state population when you run this code here so you will see that we getting some hash code in a hexa decimal format it says some integer array at the 785 e922 so what exactly has happened here so guys in the ram area so whenever you going to run the program so in this Ram structure so you’ll have this stack coming in as a data structure and the second thing is keep for us so I’ll just quickly write so this is Ram allocated this is the stack data structure this is the Heap data structure now we got this guy called population so if you see this state population so I’ll not use the term state population rather I’ll say country population so this guy contains 785 e922 right so country population is containing some hexa decimal over here 7852 e922 so it can be any number which is coming for us over here because it is not generated by us now in the Heap area there will be a storage container which will be created at the same hex code right so this is key value pair I mean to say it’s like hashing as an algorithm so this guy acts as a key where this is the storage container so we got these indexes coming in for your array right so that’s like zero index one index two index three index and the fourth index and by default we get the data as zeros right so we have all the data coming in as zeros so we have everything over here as zero and this guy country population is basically pointing out here now coming here I will first of all read the element in Array the first thing is reading the element in Array so what I’ll do I’ll simply say please print me the country population zero element so when I’ll say zeroth element so here we are with the zeroth element right so when you run this code you get to see that the value is zero so same way if I read it for the first element so you will see it’s going to give me again zero right so this is like reading the element and it’s like read single element so you access the element right so there can be the other way around that’s like read all so I can just put up a for loop I can say start with zero go till country population do length so length will give me the size of the array so what I will do is I will say ciso country population of I is plus country population I so where each and every index will represent a state okay so now when you run this code here you get to see all the values coming in as zero so when you create any array so all the elements will be by default zero so what I can do is so before I access my array I can do a right operation in Array right so WR operation so WR slash update operation so both of them are same for us so I can come here and say that the country population of zero index is 502 same way we have one then the two then the three then the four so you got 765 9987 4 56 and 876 so we are able to write the data and now I’m just going to do an empty line here and we’ll say rereading after write operation so when you run this code here so what you see is once we do a reread operation after writing the content in the array so we see the updated data right so now we have these values coming in 502 765 987 456 and 876 it means that here we don’t have zeros now right so rather than zero so you got the data coming in for us for example this guy will go as 502 now every index represents a state with the population count right so so having single value containers differently so we are having single value containers differently rather than having it in in an array is a more better version now the same syntax over here can be replaced like this so I can say in Array country population goes like this number 502 comma 765 987 456 and 876 so what does this mean this means that so here by default all the elements were zero right so in this declaration when we read so all elements were by default zero but here elements have some default initial value so here elements they have a default initial value so even you don’t write the data so let’s say we are not writing the data here so when you try to read it so you’ll always have the data in the AR now right so we not performing rather any right operation so what you will see is that you have the data coming in before you even do right operation so choice is yours so whatever the way you want to write an array you can do that so you can have an array with all the elements having default value as zero or you just specify the values whatever you want to provide so the same syntax can come up like this as well all right so don’t get confused it’s the same story right so this is an implicit way versus this is an explicit way so choice is yours right so any syntax you want to follow you can follow that so now the next thing is uh update operation so you already have the data so you can use the same assignment operator to update the data right so let’s see this update operation coming into the picture so now when you run the code so before before you had this data and now you are having this data so guys I hope this is clear to everyone right so rereading after the right operation so now this right operation has become the update operation so we can use 1D array anytime with the help of indexes we can perform a read operation on a single element we can perform read on all the elements we we can even perform a write or update operation but everything happens with the help of indexing right so there is one more way to read the array in Java so that’s like your enhanced for Loop or sometimes we call it as for each Loop so any name can be given to this guy so you say for in any element in your country population array you say print me the element so you run the code here so you get to see the data once again so here you don’t have indexes this Loop will start from the zero index we’ll copy the element at zero index into this variable Elm which can be any name of your choice right so it’s just an identifier so we are trading in this Loop so now you seriously want to come up and calculate the population for this country so I can create a variable called count which goes like zero and here I can say count plus assign or let it be simpler count is Count plus the element right and let me come here and say population count for entire country is plus the count so let’s run this Cod here and what you see is the population count coming in now now you might be surprised in a way that this was a bit easier approach storing the values in a single value container and having State one population count so why we are messing around with these indexes even though this looks very easy now assuming that you have to work on 30 States so you’ll be doing 1 + 2 + 3 + 4 + 5 + 6 it’s like a lot of time consuming thing as in development effort is highly so having this one liner where you just mention all the population counts and having a loop as couple of lines and summing up the entire population so when data is having more Dimensions so you need to focus on array right so solving the problems where you have lot of data so you structure it in a better way and arrays they are one of the most easiest data structures to use in your software Solutions so with this let’s now move to the next part so the next part is working with two dimensional arrays right so guys we call them array of arrays right so here we mention the row and column so row column here does not literally means a matrix concept so row column over here means that how many number of 1D arrays you want so the first element means how many 1D arrays and the second means how many elements in 1D array right so it’s basically array of arrays we can represent a matrix using two dimensional arrays so this is like zero arrays zero element zero arrays first element same way first arrays zero element first arrays first element so if you want to access you can say 0 0 is 100 so zero arrays zero element right so you put the data so same way you can put the data for the other elements now if you want you can access any element in a 2d array by mentioning its indexes and if you want to update the data it’s again on the basis of indexing right so guys let us try to have one example on 2D arrays so I’m going to write one new class let’s say 2D array with the main method so to begin with I’ll just say in two brackets I’m going to say world population so considering this world population so I’m going to have the first array for the first country right so let’s say all right now this is first array and let it be the second one so this goes like some second array and this goes like some third array right so this is zero Index this is first index and this is second index now when we are understanding this problem statement so we mean to say that zero represents country one and one represents some country two so just just taking an example so this represents some country 3 same way here this is country 1’s zero country 1’s one one then two then three then four and five and six so this is zero State first state so these are the states now which we are talking about guys right States for country one so these are the States for country one right as in uh indexing so the next is the state for the country two states for the Country Three so these are all counts right so they are the population counts all right so let’s say that you got country one as India and let’s say the zero state is Punjab so we got the population count for Punjab so that is how we are representing it so there can be some other country two there can be some other country three so we have represented the data into this entire array now when I will just try to say world population is is plus world population and size is plus world population dot length or let’s say and length is now when I will run this code here as Java application so what you will see is that it’s an array of arrays at a hash code right and the length is three so I got this guy called world population so I’m just going to take this another example here so we got this guy as world population 785 e2922 some hash code so this world population is something like this so it’s basically having three indexes and you got indexes coming as 2 1 and 0o right so this hash code goes like this and we got reference coming in here now the next thing is we got the 0 1 and two we got this world population coming in now what I’m going to do is I’m going to access the zero Index right so I’ll say world population zero then one and then two right so we will come up here and say 0 1 and two so guys this is array of arrays right so zeroth index is an array first index is an array and second index is also an array so I’m going to say print me the Zero’s length print me first length and print me the second length so zero length is like what seven right because there are seven elements then the next guy and the next guy they have their own sizes so when you run this program here so you get to see the sizes as 7 five and six at the same time what you see is we got different different references coming in some 42705 C6 so we have some you know hash codes so I’m just going to represent these hash codes here let’s say some 40001 let’s say some 3001 let’s say some 2001 so I’m just considering these numbers as hash codes so further we got these arrays so this is like 4,01 array 3001 and 2 so guys I’m just considering these mathematical numbers as hash codes right so this is like further pointing out here this guy pointing out here and this guy pointing out here so what is this concept this concept is array of arrays so world’s population zeroth index is an array right so we get to see this data over here so this data is available over here right so as in indexes so zero Index right so this guy is indexed for us so zero index one index two index then three then four then five and then six so on and so forth guys the others as well so if you say world population zero arrays first element it’s going to be 4 5 6 7 so that is how if I come here and if I say please print me world population let’s say zero arrays zeroth element right so world population 0 0 you run this code here and what you get to see is 1 2 3 4 so guys I hope you understood this point right so when I say one and two so first arrays zero index first index and the second index that’s like 8765 so here you are right so this is like one and two so anytime you want to read the array so this is like read single element right so you want to write the data so write or update they work in the same way right so for example now I will be doing an update operation so I’ll say world population of one and two is some number all sevens so you say see so rereading and now when I will do a reread operation here so let’s run this code so here you are with the number all sevens so same way you can even perform a read all operation so I can write a loop so the outer loop shall work for the world population. length so this Loop’s going to iterate three times because the length is three so from 0 to two because we got three 1D arrays then I got an inner loop which will go from let’s say J as in zero we will say J less than world population of I do length and j++ right and thereafter I’m going to say world population of I arrays jth Index right the print line and print line we’ll do in the next case so let me give one empty line here so here you are so now you are able to print the entire 2D array so guys array of arrays they can be powerful data structures when you have lot of data so you can even create an array of arrays by saying an ARR is a new integer so I want three 1D arrays with five elements each right so three 1D arrays with five elements each so here if you’ll try to read this guy so if you try to read ARR so any guesses guys what will be the output when you read AR so what do you think what will be the output for the AR right so output for the AR would be all zeros right so when you give the sizes you get the default values as zero and when you don’t give the sizes you give the default values so it’s just the basic conclusion to understand the arrays right so giving sizes we need to put the data later hence data initially would be zero so this is how we are understanding this guy array right so giving data first we need not to give any size so that’s like the thumb Rule and guys explore enhanced for loop on 2D arrays right so explore that how you can convert this nested for loop with the help of enhanced for Loop right so that you guys explore so this is how we got something known as two dimensional arrays and let me do one more problem statement so how we can solve this matrices problem so if you can recall your childhood mathematics so we used to do an addition subtraction multiplication and lot of other things on arrays or on matrices so we’ll write one small program here and we’ll try to solve it as an addition problem right so let’s let’s perform an operation on array once again so let’s take a problem statement here to add two arrays so I’ll write one 2D array called a which goes like the first array having one one and one so I’ll have all the values as ones right so same way I’m going to have the other guy called B so this array B I’m going to have the values as twos so it’s a 3 cross three Matrix representation three rows and three columns three rows and three columns so when I have this metrix representation coming in so what I’m going to do is I’m going to print them first right so let’s see Matrix a so I’ll say for INT go with the zero go less than a do length and uh then I’ll write one more for Loop so we got this 2D array so we need to access the elements so you need to come up with a of I do length and j++ so here I’m going to print this guy called a of I and J so this is the representation for Matrix a let’s represent the Matrix B so I’ll say B do length B of I and B of i j so let’s run the code here so this is how the two different matrices are coming guys right now what I’ll do is I’ll come here and I’ll create one another Matrix that’s like C which is a new integer of three and three right so we’ll take three rows three columns and uh what I’ll do is I’ll take one Loop here run it till C’s length and I’ll say C of i j is a of i j so guys we are adding the elements here right and B of I so what we are doing is we are adding this one with this two then this one with this two so on and so forth right and once I’m done with it so I’ll represent this guy called Matrix C here after the addition so all elements they should come up as C so you run the code here so you get to see that the Matrix 3 is coming as all the threes so here we are so one basic mathematical operation on matrices guys right we’ll see sorting and searching in arrays so there are various different algorithms through which we can sort the elements in an array and same way we can even do searching now typically when you are in an e-commerce shopping website let’s say Amazon or any other e-commerce so you want to sort the items on the basis of the price right so that’s like either ascending way or the descending way so one of the practical usages where you can actually apply these sorting algorithms so these are some commonly used algorithms and they have their own you know time and space complexities but we are not going to discuss that in detail here so we’ll typically see how they work and how we going to solve this problem to sort the data in an array so we got bubble sort selection sort insertion sort quick sort and Mer sort as algorithms which we are going to discuss for the day so let’s begin with bubble sort so guys given the Sorting techniques so when it comes to the bubble sort it’s one of the simplest sorting algorithm right so what it’s going to do is it’s going to perform the swapping of the adjacent elements in case they are in a wrong order right so we going to always swap the adjacent elements if they are in a wrong order so we are considering that we going to sort the array elements in an ascending Arrangement so let us see how it’s going to work so consider that we got set of elements as 4 1 10 – 3 and 12 so what bubble sort will do so in case of bubble sort so we’ll start one of the iteration so consider the I iteration so we’ll start from the zero index and we’ll compare the index 0 with the index 0 + 1 that’s like 4 and 1 we are going to compare here so when we compare we find that 4 is greater than one so we swap the elements now the next is where we are comparing 4 and 10 so four and 10 will pass because four is lesser than 10 then we’ll move on to the next adjacent elements that’s like 10 and minus 3 so when we compared them we found that minus 3 is a smaller one so we swap them and same way when we compare 10 and 12 so it’s perfectly fine so let’s pass now in the next iteration so we’ll Again Begin and we’ll now start from the next index of the aat loop so here now we’ll see Min -3 and 4 has been swapped and thereafter we’ll compare 4 and 10 and finally guys the last iteration so on and so forth will finally sort the array so what we are doing we are just comparing the adjacent elements so if one is found to be lesser than the other so you swap them right so let’s try to write a small code snippet on bubble sort and see how it’s going to work for us so I’ll write one small program here so let’s create a new class so I’ll say a bubble sort with the main method so considering that we got the elements of an array so let us take the same use case so 41 10 – 3 and 12 so this is the input sequence right so this is something which we are are looking forward to sort now in order to sort I’ll write one method here so let’s say this goes like static void I’m just going to say sort here so I’ll take array as input so the array which I want to sort and here we’ll come up and say bubbl sort do sort the AR so you’re passing by reference it means that if you sort this reference right so automatically this will be Sol so it’s basically reference concept which we are using here so the first thing first so I’m going to now calculate the length of the array so let’s say length is er dot length so this is the size of AR mores right so we’ll run one Loop so this is let’s say the outer loop which starts from zero and this Loop shall go till less than your length minus one and and thereafter I’ll say an I ++ so it means that this Loop will go from zero so this I Loop’s going to work from the zero index then one then two and then three right not the last one right so it’s less than length minus one right so if the length of my array is five so let’s say the length is five so the outer loop here shall work from 0 to 3 so it’s length minus one so we want to iterate till here now I’ll have one more Loop so let’s say this is the J Loop so J Loops begin with zero and J Loop will run from 0 to length minus of I and minus of 1 and then I’m going to say j++ it means the jth loop is dependent on the I value so if the I value is zero consider that if I is zero so your J will vary from 0 to now length minus i – 1 right so what is the length length is 5 minus 0 minus one that’s like 0 to 4 so on and so forth it’s going to work for the other indexes of I now let us compare in case the AR’s J index is greater than arr’s J + 1 Index right so if if the element is greater we are checking for the adjacent elements now if the adjacent elements are being compared and we find that arj is the greater guy so we’ll swap it right and we’ll use the swapping technique as a very basic swapping technique so we’ll have a temporary variable in which I’m going to put this jth element and thereafter we’ll have AR’s G element allocated with the ARR J + 1 and lastly we’ll have ARR J + 1 having the 10 so I’ll just write down here swap the adjacent elements and this is how our Logics going to work right so we keep on swapping and once this entire swapping is done the loops are terminated so you will get one sorted arrangement of your elements So when you say bubble sort. sort the ER so now if you say for Loop let’s say int element in the AR so I’ll simply see so and I’ll say element with some space so you run the code here as Java application so what you see is the sorted arrangement of your array – 3 1 4 10 and 12 so this is the very first and the very basic technique called bubble sort so we compare the adjacent elements and we swap them so guys let’s move next so for our next sorting algorithm we got something known as selection sort so guys selection sort is also one of the Sorting algorithms and here this guy will sort an array by find finding the minimum element and putting it to the beginning so we’ll keep on repeatedly doing these steps we’ll find the minimum element repeatedly and we’ll just place it in the beginning of the array so that is how our selection sort is going to work right so let us understand this so when we are in the first iteration so we exactly are trying to see the minimum number and we we will find that minus 3 is the minimum number in the first iteration so we’ll put it in the beginning now we’ll shift the next index and we’ll just keep on comparing and we’ll see that one is the shortest one so let it be there so thereafter we’ll move the index to the next position and we’ll see now who is the other small element we’ll find that four is the small element will now come up and put it in the beginning and lastly we are in the sorted set right so selection sort is comparing the number so we are just going to compare the number with all the elements wherever we find the shortest element we put it to the beginning right so let us have one small program with respect to selection sort and see how it’s going to work for us so the way we got bubble sort I’m going to say a new class here let us say goes like selection s with the main method so we’ll take the same use case so instead of having this bubble sort will have selection sort so I’ll create a similar sort method so let me copy this so you’ll have a similar method where we’re going to sort the data right so the structure begins in the same way so the thing is we need to come up and iterate for the same structure we going to iterate from 0 to length minus one so the internal structure it’s going to be a bit different now right so what I’ll do is I’ll first of all assume that the minimum element or you can say that minimum element on the index is the element at the ath index right so the minimum element right so I’ll just write here so assuming minimum element is at ith index so we’re assuming this part now right and we’ll Now look for any element who is a minimum than this so for that I’ll put up a loop which starts as in J’s value with I + 1 and J shall run less than the length of the array so we are iterating over the entire array and if in case we say that ARR of J is less than ARR of minimum index so considering that what we have is we have the jth element less than the minimum index element so what I’m going to do is I’m going to say let minimum index go as J so in the array we are finding the minimum index and once we got the minimum element so minimum index over here means guys we are targeting the minimum element right so here we are targeting the values not the index so we are just capturing the index of the minimum element now once we captured that so there after what I’m going to do is I’ll swap the minimum element with the first element so swap minimum element with first element so what I’ll do now is I’ll take up one temporary variable in which I’m going to store the minimum index so thereafter let’s have AR of minimum index x with ARR of I and thereafter the AR of I will be having the temporary so this is like swapping the element and not the adjacent elements the way we had it in the bubble s so this is a bit different way of dealing with the things but at the same time when you will execute this program of yours so what you find is the data is again sorted for us so how these algorithms are different so they have the different approaches to solve the same problem so they vary in time and space complexity of course but that is not something which we are going to take now so guys this is something known as selection sort right so how we are selecting the element which is minimum and then putting it into the beginning now let us move to the next part so guys next part we’re going to come up and discuss something known as insertion sort now what is insertion sort so when I’m talking about insertion sort so this is very much similar when we are playing the cards so what we do is we pick up the smallest card and we put it in the beginning so here we are going to work in the same way right so we going to pick an element and insert into the sorted sequence so let’s see one iteration that how insertion sort will be working for us so for insertion sort let us assume the same input so when we will compare four and one so you see that over here we got four and one being compared so we’ll swap them and now we’ll move into the guy called 10 and thereafter we see that minus 3 is again a smaller element so we’re going to shuffle it to the beginning so it’s just like the way you sort your cards so finally you’ll get a sorted sequence right so guys insertion sort is something which is sorting the data in a different approach for us so here we are going to again find the smallest value and swap the same right let’s try to write a code snippet on insertion sord and see how it’s going to work for us so let me come here and create a new class so this goes like insertion sort with the main method so let me take the similar method here so we’ll call it sort itself and coming here so we are going to work from 0 to length that’s like 0 to 4 so we’ll take the same sequence and we’ll see how it’s going to work for us so I’m going to say insertion sort do sort s right so let us now write the code to sort the array now I’ll first of all consider that there is a key which is basically ARR of I so we’re assuming that the very first index itself is a key and I’m going to now create one J which shall be your I -1 so basically I want to move the elements of the ARR from zero to this J so that whatsoever are greater than the key to the position ahead of their current position right so let me write the code that’s going to be more helpful for us so here I’ll say while J is greater than and equal to zero and ARR of J is greater than T so run the loop till we have these conditions being satisfied and if the loop is in execution so what I’ll do is I’ll say ARR of J + 1 you just copy the ARR of J and you decrement the value of J by one and once this Loop is terminated come out of the loop and we’ll have J + one index with the key so that is how we are sorting the array over here guys so so in order to sort what we are doing over here is we are moving elements of ARR from 0 to i-1 right but we are moving only those Elements which are greater than key and where we are moving so we are moving them to one position ahead of this current position so if the current position is J we are moving it to J + one exactly the way we do it in the cards right so you’re just moving them one position so guys now let us try to run the same code and see what happens for the Sorting technique over here so what we see is insertion sort has also sorted the array and the technique is modified but the outcome Still Remains the Same so insertion sought in action so guys once now we have since understood what is insertion sort so we’ll be now moving into the other algorithm called quick sort quick sort is not as in that it’s really a quicker algorithm to sort the elements but when it Compares itself to the merge s yes it is quicker so what exactly happens in the quick sort algorithm so guys it’s a divide and conquer algorithm so what we do is we partition our array and then we try to solve the problem so consider the set of elements 9541 72 3 and six so what we try to do over here is we will decide one of the elements in this array which can be serving as a pivot or a pivot so the pivot element is the element which can be either the first element the last element or the middle element or any random element of your choice so it can be any element now the whole idea is to choose this pivate element and break your array in such a way that all the elements left to the pivot should be less than or equal to it and the right to the same pivot we should have greater than elements so we are going to make our pivot to go into the exact position so this way we will be coming up and sorting up the entire array so Shifting the pivot to the right position will be our key success now consider six is the pivate number from the entire list of sequence now consider the ath index or the ath variable and a jth variable so the variable J will be iterating over the array and we will be comparing each and every element to the pivot that’s like six so considering when your J is zero that’s like the number nine so we’re going to compare 6 and N so we know that when you compare the number six and N so 9 is greater than 6 right so we are okay to go with it now we increment the J and we bring it to the five when you compare five and six we find that this jth element is less than the pivot so whosoever is less it should move in the beginning or to the left so what we are going to do is if we find the element lesser than the pivot we are going to move it to the beginning or we are just going to swap number nine and number five and now I am again reiterating on the JF index and I have incremented the I index as well so let’s say initially I was pointing to this guy five but when we did a swap on 9 and five we incremented the variable I as well now the new number with the JF index is four so if you compare six and four so we understood that four is lesser than six so what we’ll be doing is we will be res swapping your number nine and four and then increment I now again six and one there compared and we see that one is less so you again swap but seven is greater you don’t swap but two is what which we know is lesser so what we’re going to do is we’re going to swap your two with the nine so on and so forth so lastly what you will have is you’ll have the elements that’s like 5 4 1 2 and three which are lesser than the six and 9 and seven greater than the six so we get this six exactly positioned after three and before 9 right so guys that is how we are doing this partition and then we are sorting the structure so let’s see a code snipp it on quick sort so I have this code walk through here so what I have is I have the input sequence of the same elements 95 41 72 3 and 6 so we got this sort method here where I’m passing array the zero index the length minus one so these are the initial inputs to this sort method so here we are with the sort method so if you got low less than the high which exactly it is so we are going to call the method partition with the array low and high now partition method is working in the same way so we are considering the pivot as the last index so high means the last index the last element now index of the smaller element shall be low minus one so that’s like we are trating this variable I and we are iterating in the jth loop which will iterate in the entire array so if the arj is less than the pivot we are going to swap AR I and arj and will also increment the variable I and finally once you are done with everything so what we we going to do is we’re going to move our pivot to the right place So eventually entire array to the left of pivot should be less or equal and to the right will be greater so putting the pivate to the correct position that is what we did in this partition method so recursively we are going to sort it and till time we don’t get the correct elements in the list we keep on sorting them so when we run this code quick sort. sort and you see we will have the elements in the correct order that’s like 1 2 3 4 5 6 7 and N so this is what we got As in quick s guys right so guys now let’s have look at the other algorithm for sorting that’s like the merge sort now merge sort is also a divide and conquer algorithmic approach so what we’re going to do is we’re going to divide the array in two halves right so you say it as left and the right one so here what we will be doing is we’ll take one example of the same sequence 4 1 10 – 3 and 12 so we going to divide this array into two different halves so once you divide the array so you keep on dividing the array further so you see once you are dividing the array you divide till we got all the single individual elements and once we have all the single individual elements right so therea we’ll start working on merging these arrays right so here guys will write something known as a merge function which will merge the two halves based on which is greater which is smaller so what we’re going to do is we’re going to merge first of all one and four we’ll see that one is smaller number so we’re going to place it first and then we’re going to bring it four right so so on and so forth we keep on merging the elements and we’ll first of all finish the merge on the left array then we’ll finish the merge on the right array and lastly we’re going to merge left and right array both which will be the sorted Arrangement at the end so in this merge sort algorithm divide the arrays into two subarrays left and right so thereafter you sort the arrays at the end right so let’s have a quick look on how this algorithm can work for us so I already have the code snipper for this so let me just open it so here we are so now typically for a merge sort algorithm how it’s going to work is so we got this function called merge and I’m going to take the same sequence of inputs so that’s like 4 1 10 – 3 and 12 so just give me a moment so 4 1 10 – 3 and 12 right so what we are doing here let’s see now so we got this guy called merge as one method which is supposed to merge to arrays and if you will see over here we got sort which is going to sort the two arrays and thereafter it’s going to merge so I’m going to initiate my program by executing the sort method right so for the sort method I am passing array to be sorted I’m passing the lower index that’s like zero and I’m passing the higher index that’s like your length minus one so this zero index and this guy is the fourth index now in case L is less than R which it is so we are going to come up and say let us find the mid L + r by 2 and we now calling the sort method twice the first sort happens on the AR r l comma M the second sort happens on M +1 and R right so once we sort the left and the right part then we are going to merge both of them so here when I’m doing a sorting so you need to understand that it’s a recursive call so we are calling the method again and again until this condition is satisfied so what happens in the merge part so here what we see is we got two different sizes right so S1 and S2 are the two different sizes for the arrays so we are creating the left array and the right array based on two different sizes so the left and the right array size so what I do is I copy the elements in the left array and in the right array so this is merge over here method so this is going to merge two arrays which we partitioned and you got l R which will be working from your L to M and we have this guy called let’s say R AR so there is subarray one and subarray two right so I’ll just say one and this guy ARR two so the second array is going to work from m + 1 till R now we are copying the elements here so create sub arrays so this is like create sub arrays and here what we are doing is we we are copying elements into sub arrays and now once you have copied the elements so we’ll start the process of merging right so let’s say start merging process here now in the merging process so what we got is we got indexes for the first and the second array so I’ll take the zeroth index to be the initial index and once I have taken that so I take the initial index of merged sub AR aray so that’s like K is L now while your I is less than the S1 and J is less than S2 so what we will be doing is we’ll be further checking if I index in the left is less than or equal to if it is so we going to assign the arr’s K index with the ith index in the left array and then you increment the I other way around it’s the right array which has to be considered so till I will be less than S1 we are going to come up and copy the ath index in the left array into the kth index and then you increment the I and the K so lastly guys if the J index is less than S2 you do it for the same part but you are doing it in the right array so we got something known as merge process and we got something known as sort process so when you run this code here So eventually you will again get the sorted outcome so guys sorting can work in various different ways so we got this technique called merge sort where you keep on dividing the array and thereafter once you have individual elements you start the merging sequence so this is the final outcome that how we going to work with it next part is how we are going to search in the arrays the first one is a linear search so what we going to do is we going to identify an element that whether it is there in the array or not so begin from the zero index will keep on advancing till the last index so once the element is found we get to know the index which index it is and thereafter we return back the index so in the linear search operation so we get to see that there are few inputs to the method so we going to return the index of the element which is found right so considering the use case right so we are planning to have this linear search so we’ll write one small program let’s have it with the main method so I’m going to take the same sequence of inputs which we have been following so this is the array and let’s say the element which you want to search is the number 10 whether the 10 is there or not so I’ll write down this static int search or let’s say this is uh linear search so in the linear search I’ll pass one array and element which I want to search right so this is how we are going to come up with the linear search approach so we’ll get to find the index so by default I’m keeping the value of index as minus one and I will return the index at the end now you just say for in I is z i less than the ARR dot length and I ++ right so you trading in the entire array so less than length is your n now if element is going to match the ARR of I right so if it is going to match the ARR of I so I’m going to say index is I and thereafter I’m going to break the loop so now you come here and say in found index is linear search dot linear search array and the element 10 we know where is the 10 element right the 10 element is at 0 1 and two second index so let us say if I is not equal to minus1 we’ll find the element and uh sorry so this guy is found index so let’s say if the the found index is not less than I mean not equal to minus1 so we got the element in the else case I’ll say C so element plus element not found or the other way around I’ll say C so element plus the element found at plus the found index so this is what we got so now when you run this code here so it say is element 10 found at two Index right so it’s the second index where you have this element 10 let’s say this guy as 12 you run the code it’s going to say at 4 index but if you try to enter something like 120 so you going to get element 120 not found so guys linear search algorithm is where you begin from the zero index and you keep on comparing till the last Index right so so the next searching technique over here with us is binary search so in the binary search what we’re going to do is we’re going to sort the array first right so we should have a sorted set of array and when you are going to find the element so you are dividing this array into two parts so we’re going to divide the array as in the left side and the right side so if you are finding some array in the binary search right right so this is now very much simple approach what we did in a linear search but the only thing is this we’ll be searching the element into a corresponding half so we keep on dividing the array to find the element okay so now let’s say you want to find this element number 79 so what we are going to do is we are going to take the right part of the array so as to search that element we will not into the lower half and into the upper half also we’ll keep on dividing the array again and again so let’s try to write a binary search algorithm and see how we can do a small search operation so this is basically going to save the time so this is optimized on time complexity so let me write a new class and this goes like binary search with the main method so similar to your for linear search I’ll just have this so this is what we got over here as let’s say static int binary search so I’m going to take array as input then I’m going to take something like left something like right and the last one is let’s say the element X so which you are going to uh search now the guy over here is going to check whether R is greater than or equal to l so if R is greater than equal to l then we going to find the mid so the mid goes like L + r – L IDE by 2 so we got the mid part and now so I’ll use recursive technique over here so in case so let’s say if element is found at the same middle index so I’ll just keep a check that if ARR of mid is equal to this guy called X then you just return this guy called mid so I’ll return the middle index itself right now there can be the other possible use cases so let’s say if element is smaller than the middle in case element is smaller than the middle so it means what hence element shall be present in the left part of array so element would be there in the left array and hence what I’ll do is I’ll just put up a small condition that in case AR RR of mid is greater than the X element which we are going to found so here I will again do the binary search so I’m going to do again the binary search but to do the binary search now so I’ll go with mid minus one and I’m finding the same guy X right so we finding the same guy X over here and lastly guys so I’m going to say return me so return me a binary search of er your mid + one right and X so else the element will only be available in the right part of array so this is is the case where element shall be present in the right part of array so if it is in the left so you execute this so return from here else uh you come if this condition fails we’re going to return this part and let’s say if we reach to a stage where element is not at all available right so if the element is not present then what then you should return – one so let’s try to come and say return of minus1 so here I’m going to perform a binary search called binary search and you need to make sure that the array is in a sorted Arrangement right so we’ll say this array over here so you need to sort this array first so what I can do is I can just make it Min – 3 1 4 10 and 12 right so that’s like the precondition array must be sorted first now when your array is sorted so let’s say you need to find the element called four and in the binary search you pass the ARR that’s like the first thing then you pass your zero index so guys let me just take some more inputs here so let’s say the length is ARR Dot length so this is the length of the AR and I’ll pass length minus1 and the element which I want to search so we are searching for this guy called four let’s give a small run on this and let’s try to see what happens so it says element 4 found at second index let’s search for 12 it says at Fourth index and when I say 120 you give a run here it says 120 KN pound so guys this is a binary search operation you keep on dividing your array into sub arrays to the left and to the right and then follow that array in which your element would be present right so greater than or less than condition check so this is a recursion approach through which we are solving this binary search problem so this is what we have over here as in the binary search part a Java collection framework provides an architecture to store and manipulate a group of objects and it includes interfaces classes and algorithm in this figure blue boxes refers to the different interfaces and the gray color rectangles defines the class so here list is an interface and array list link list Vector all these classes implements list as a interface similarly as d Q is also a interface so it extends an inherit Q interface now talking about array list it uses a dynamic array for storing the elements it inherits abstract list class and implements list interface then list interface extends collection and iterable interfaces in hierarchical order so this is about the hierarchy of array list class now let’s see what is array list array list is a part of collection framework and is the implementation of list interface where the elements can be D dynamically added or removed from the list also the size of the list is increased dynamically if the elements are added more than the initial size though it may be slower than the standard arrays but can be very helpful in programs where lots of manipulation in the array is required some key points to note here array list is initialized by a size however the size can increase if the collection grows or shrunk if the objects are removed from the collection next array list allows us to randomly access the list and array list cannot be used for primitive types like in care Etc to access all those we need a wrapper class for such cases now let’s move further and say the internal working of array list first we create an empty array and then go on adding the elements once the size of the array is full that is if the size of the current elements is greater than the maximum size of the array then we have to increase the size of the array but the size of the array cannot be increased dynamically so what happens internally is a new array is created and the old array is copied to the new array so by this automatically the size will be doubled and it will be increased so you can go on adding the elements how much you require so that’s how it works internally now let’s see the various Constructor supported by Java array list first array list this Constructor Builds an empty array list coming to syntax my array is a reference to an array list that holds the references to object of Type e array has has the initial capacity of 10 cells although the capacity will be increased as needed as references are added to the list and cells will contain references to objects of Type e next array list of collection C this Constructor is used to add all the elements of specified collection C to the current array list that is you can add all the specified collection C to the current array list next array list of incapacity here this is used to build an array list that has a specific ified initial capacity and initial capacity is the number of cells that the array list starts with it can expand Beyond this capacity if you add more elements now let’s see a small example to understand how and where these Constructors are used in Array list I will open my eclipse and first create package called edura now I will create a class called Constructor the very first thing that I do before writing the code is I will import util dostar package now let’s begin with the code I will first create the array list of type string I initialize the counter value to zero and using Advanced for Loop I’m trying to increase the count of counter but we don’t have any elements present in the array list so if I try to print the counter value it will not retain any value why because we don’t have any elements present in the list okay now I will create one more array list and initialize the capacity to that I’ll change the name and give it as B and I will initialize the capacity to 1 okay now again if we try to print the counter value it will not print because we have just initialized the capacity again if we try to obtain the value of counter it won’t get incremented why because we don’t have anything in the list now let’s create a string array and add some elements into it after creating a string array I will create a object of array list and then upend a element using ad method so let’s see how to do that so this is how I will add element using add method now I will use Advanced for Loop to print the elements present in the array list now let’s run the program and see what will be the output so here is the output as I have already told it won’t return the counter value because the array list is empty and the counter value will be automatically zero next on creating a string and adding the elements it has retrieved all the elements present in the string even with the one that we have added that is j2w so this is how Constructors are used in ARR list now let’s dive into the various methods supported by ARR list first add method this method is used to add the elements to the array list that is it is used to insert a specific element at a specific position index in a list for example you can create array list and go on adding the elements using the ad method we will demonstrate and see all the methods of array list in Eclipse after knowing the concepts of them next clear method this method is used to remove all the elements from the list that is you can just use Clear method to remove all the elements present in the list next trim to size this method trims the capacity of an array list instance to the list current size that is if you are creating an array list of size 9 and if you’re adding only three elements to that on calling this method trim to size it trims the size of array list from 9 to three that is it reduces the array list size to the number of element that it contains in the array list next index of this method Returns the index of first occurrence of the specified element in the list if that element is not present in the list then it returns minus one suppose in this case if you want to return the index of five and if you write here five then it will return a of two because a of one and a of two but if you try to find the index of three which is not present in the array list then it will return minus one that is it returns minus one if the list does not contain the particular element next object clone this method is used to return a copy of the array list that is on calling this method it clones entire array list so for example if you’re adding two elements in the array and you’re cloning the entire thing then again after clone list it will return the whole element present in the array list next object to array this method is used to return an array containing of all the elements in the list in the current order for example if you have all the elements in the list then it will return all the elements in the list in the correct order next remove method this method removes the first occurrence of a specified element from the list if it is present for example if you want to remove n from the added list then it removes the first occurrence of n if there is one more occurrence of n here it won’t remove that next size this Returns the number of elements in the list that is the size of the list suppose say we have added four elements then it Returns the size of the array list as four now let’s demonstrate all the methods and see how it works and how it is used I’ll create one more class called ARR list now in this example we’ll see how to add the elements we’ll create an AR list of type Al that is a reference and we’ll go on at adding the elements into this now we have added three elements now let’s try to print the size of the array and the contents present in the array let’s execute and see what will be the output so the size of the array list is three and the contents of array is edura Java and arrays now I want to remove Java from the list so what will I do here is I will use a remove method to remove the element from the list now again let’s print the size of the arist after deletions so when you remove Java from the list it retrieved only edura and aray and the size will be decreased to two so this is how we can remove the element we can add the elements and we can retrieve the size of the array list now let’s see how to clone the array list first we’ll make clone list as object and then call the method now let’s execute and see how the Clone list appears so as we have already removed the elements from the list so it it returns only the elements after deletion in the Clone list so if I make whole remove part as comment and execute then it will retrieve the entire elements present in the array list see that is elements in the Clone list are edura Java and arrays now let’s see how object to array method works on executing this this is how the output looks now let’s use Clear method and clear the array list it’s very simple Al do clear and print the elements after applying clear method nothing will be present in the array that is the entire list will be cleared now let’s see how to create a custom array list and add the elements move the elements and retrieve the size of that I’ll create a class called custom array say I want to create a class of student data wherein I’ll be initializing role number name marks and phone number so let’s see how to do that I’ll create a class called student data and initialize variables now I will create a Constructor and add the reference to the these variables now let’s begin with the main method now let’s create a custom array list and reference a variables using add values method I’m adding the values now I will invoke this function and Define it here I’m in working list of add method to add the elements in the list now in order to print the values present in the list I’m invoking a function called print values of list and here I will give the definition for that and now let’s print the values present in the list now let’s execute and see what will be the output that is it displays all the elements present in the array list that is the rle number name marks and mobile number now if you want to remove one of the rows from the array list let’s see how to do it using remove method here I will give list. remove now if you want to remove the row of elements from the array list then you can remove the elements from the list and then print the rest of the elements so let’s see what will be the output so output is like this first it has printed all the elements present in the list then it printed the size of the list and it removed the first occurrence when you use remove method it removes the first occurrence present in the list that is it removes the first value so it has removed the first row that is Chris and it retrieved the the rest of the elements so that’s how you can create a custom AR list and add the elements accordingly now let’s jump into the last topic of today’s discussion that is advantages of array list over array first array list is variable length arrays are a fixed length you cannot change the size of the array once they are created but array list is variable length that is it can grow and Shrink dynamically next size of the array can be modified dynamically when you add the elements into an array the size will be increased and if you remove the elements the size will be automatically decreased next you can add any type of the data Maybe list Union structure Etc not only that it also allows you to add the duplicate elements in the list next you can Traverse an array list in both the directions that is forward and backward directions using list iterator and it also allows you to insert and remove the elements at a particular position so I hope you understood the concept of array list and the difference between array and array list now if you’re talking about Java Springs right so we can process our textual data very easily given a use case so we write a sentence so we can very easily search some words in the sentence we can use an API like contains which can tell whether the word is there in the string or not right so so searching is one of the inbuilt feature in the string API then we can divide our string into you know multiple parts so we can say as a sub string moving ahead we can even create new strings out of the old strings for example the quick brown fox jumps over the lazy dog we can say the quick fox jumps and the quick lazy dog so these are the different strings which we can manipulate our existing strings and we can create the new strings but remember the old string never ever changes it’s always the new string which is created since strings in Java they are immutable now java. lang. string is a class in Java so guys this class is basically implementing few interfaces serializable comparable and Cas sequence so when we talk about the class string it’s a final class which you cannot inherit so every class in Java will be the child of object either you create or it’s a built-in class so it implements serializable comparable and the car sequence so let us see what these three interfaces will be for Strings now serializable is just a marker interface now when we talk about a marker interface guys so it will not contain any data member or method it is basically uh marking the Java classes so that our compiler can come to know about these classes now serializable are the ones for whom we can save the state in some files so there’s a concept called serialization and deserialization so saving the state of an object and recovering the state of an object from a file now comparable is basically that if you have a string and if you want to order uh the data in the string you want to sort you want to compare so we got some methods available with the help of which we can very easily do that for example a method called compare to can compare one string with the other string whether they are equal or not then we got cash sequence interface guys this is a readable sequence of correctors and this is supposed to provide some readon exess and the other thing is that car sequence is basically parent to three classes right string string buffer and string Builder now string is a class which can create textual content for us where this guy is immutable so we cannot change the data once
it is created so you can even say strings they are nothing but their data or their values they are literals and we cannot change them but string buffer and string Builder they are again the car sequences which can manipulate the data within so they are the mutable versions of the strength moving ahead buffer and Builder they are different in a way that buffer is not thread safe whereas Builder is thread safe so my bad buffer is is thread safe whereas Builder is not thread safe right so what is thread safety guys thread safety is synchronization when multiple threads they are going to access the same single object there we need synchronization so string buffer is builtin and it is by default synchronized but the Builder is not synchronized so that is the difference between buffer and Builder now we’ll understand how we can create strings in the map memory so strings in the memory they are created in an area called string pool now when we are talking about string pool so Java string pool refers to collection of strings which are stored in the Heap memory so in the Heap area so there would be a string pool which will be created and as string objects are immutable in nature the concept of string pool came into the picture so string pool will help in Saving the space for Java run type so let us see how string pool is going to work for us and how it’s going to save memory for us now if you want to create a string there are two ways either you can create it as a literal we call it an intern string or you create it with the new keyword we call it an object right so let us have a quick look on how we create a string and how he and how the string pool comes into action so considering we are going to use little L Al to create a string so guys Java string literal is created by just writing the string literal in double codes so how you will do it you’ll say string Str Str is urea you need to use these double codes so when I’m saying St Str so guys St Str is basically a reference variable which is pointing to edura like this so in the string pool we got a literal called edura and Str Str will contain the hash code for that literal and uh this is how we got a relationship mapping now same way when we want to create a new string with the same name let’s say I want to write another string but that will also be Ura so for that what happens so before creating a string literal right so first a lookup happens for the value in the string pool if the same value is already label in the string pool right so a new string will not be created rather the reference of that string will be returned for an instance if I write string s str1 is edura it means what will happen St str1 will also point to the same string so literals they are created once they are not recreated same way when I will say string St str2 is welcome now welcome is not there in the string pool so what will happen a new literal welcome will be created to which s str2 will point so once again a quick review string literals we also call them an interned way of creating the strings in turn way of creating the strings is where a string literal gets created into the string pool once a literal is created it will not be recreated so if you set that string as R is edura so we are not going to come up again for string Str str1 is edura so it’s going to point to the same string literal for a different string literal we’ll have a different you know memory region created so string s str2 is welcome will point to a different literal and hence the string pool so how it is saving the memory by creating literals once right so sharing of string literals because these literals they are the values and they can never ever be modified they’re kind of constants now the way 10 one Z is a literal it cannot be changed same way these are the literals they cannot be changed now uh the other way of creating a string is if you write a new keyword so whenever you’re going to use a new keyword so it is basically going to create a new object in the Heap M so for an instance if I say string s str3 is a new string urea what’s going to happen so there will be a new object created in the heat memory so it’s like the just the other objects which get created in the memory right so it’s always a new object it’s not going to point to the string pool now so guys this is the difference between how we can create a string literal and how we can create a string object so object construction happens with the new keyword and it is always a new object so even if I will say string St str4 is a new string with adura it will be a different object constructed in the memory even though the contents are same but new keyword will always create a new string object in the memory now we’ll see some string Methods so guys we got string class which is a built-in class and we will be exploring these uh methods what are the built-in methods we will also try to explore them practically but let’s first of all have a look on on the list so we got this method called Equals which will check whether the uh given string is equal to the other string or not so it’s comparing the contents in the string now equals ignore case will ignore the case right so whether the upper case or the lower case it won’t matter for us length Returns the length of a string then we can get the character at any index now string is a you know collection of characters so they are indexed internally from 0 to n minus one so Car Act you pass the index and you’ll get the character at that index from the string two uppercase Returns the string in the uppercase lower case will generate a lower case string then replace can replace an old character with the new character and thereafter a new string can be constructed so remember whenever we are manipulating the strings whether the intern strings or the non- intern strings we are always getting a new string now trim is a method which is going to uh remove the wide spaces from the beginning and the ending of the string then contains method will give a quick check so it’s going to search whether a string is existing in a string so part of string exists in a string or not two car array so we can get our strings converted to the character array by calling the method 2 C array then we got is empty to check whether the string is empty or not ends with so we can check that whether the string ends with a specified suffix for example you want to generate an application where you want to list all the images so you’re writing a file explorer app you want to read the files and you want to check whether they are extensions are jpg or PNG so we got ends with right then similar to the ends with we even have starts with then we got concat which can concatenate the two strings right so it’s like appending the strings and regenerating a new string so guys let’s have small demonstration on string Methods so I’m going to create a new Java project so let us name this as strings demo so here I’m going to write a class let’s say strings Java strings I’m going to say a cod. Ura as a package with the main method there are two ways to create a string so I will say string St Str one is hello right so this is known as intered way or we can say string literals so where are they stored they are stored in stored in string pool right now I will say string St R2 is also Hollow so guys St str1 and Str str2 they are two different reference variables but they are pointing to the same literal hello Str str1 and Str str2 reference variables pointing to the same lital so as we saw in our uh string pool example during the presentation part now if I’m going to compare these strings if I will say if Str str1 is equal to Str str2 so here I’m going to say s str1 equal to s str2 in the lse case I will say St str1 not equal to Str str2 so what are we comparing here we are not comparing content that is hello so what we are doing here so we are comparing hash codes of Str str1 and Str str2 hash codes in Str str1 and in Str str2 which will be same for the string Hollow now literally is created once right so Str str1 as a reference variable and Str str2 as a reference variable they are pointing to the same string hello so we comparing the references here so when I will run run this code what you’ll get to see is that they are equal now the other way around is uh where I’m going to say string Str str3 is a new string of hello so what is this this is known as object string object that is we used new operator so here string object is construct in Heap area with Hollow as its contents at the same time when I will say string s str4 is new string hello so guys what has happened St str1 St str3 and Str str4 are reference variables which are pointing to two different objects who whose content is same now that is something which we need to understand so we are basically having these two different strings two different reference variables which are pointing to two different objects whose content is same so when we are going to compare Str str3 and S str4 we are not comparing the content we are again comparing the hash codes in s Str three and Str Str 4 which will be different for the different for the string object containing hello so see there’s a difference now right so if you will compare three with the four so when I’ll compare three and four you will see it is not equal to so this is the first proof of concept and as a conclusion we understand equals to will compare reference variables that is Hash codes and not the real content that is hello so equal to is comparing the references it’s not comparing the content and we also saw that if we have a literal if we create a string literal so there we get to have the same reference for the same strength so s Tier 1 was compared but s tier 3 and S 4 were not compare so how we should compare right so how should we compare strings there are two ways the first way I’m going to write here that if Str str3 dot equals Str str4 so that’s like the equals method it’s going to return me either true or false I’m going to say Str str3 is equal to Str str4 and the else part where it is not equal to Str str4 now when you run the code you see it is equal so remember if you want to compare the strings right so that is the content within right so you want to compare the content within you never ever use equal to operator because equal to operators is working it is working only on the reference comparison where equals as a method is comparing the content within right now the equals method is one thing the other thing is compare to Method you can say if s str3 do compare to St str4 and if this gives me zero right so this is a comparison St str3 compared to s str4 in the else case I can just say s str3 not compared to S str4 so let us run this code here so compared to S str4 and is equal to Str str4 so this is what we got guys right as in the two different you know ifls structures how we can compare the strengths now let us explore some string apis so more on string apis so some string Methods to begin with let us create a spring called s Str which is John Jenny Jim Jack Joe so we got this string John Jenny Jim Jack and Joe and what I’m going to do here is so I will see the first thing we’ll get the length right so I’ll say in length is s Str do length so we can say ciso length of s Str is plus the length now when I run the code here you see it gives us the length as 28 so when I get the length as 28 now there are characters right so I can just come here and say St Str do Car at0 Plus bar + SD do carat length minus one so when you run the code so even before I run the code so I’ll just print out the S Str so let’s say SD R is plus Str Str so I’m just going to print the string so it says Str Str is John Jenny Jim Jack and Joe length is 28 the character at Zer is J and the character at length minus one that is 28 – 1 27 is e so uh string starts with the zero and goes till n minus one that’s like length minus one now considering I will say Str Str do2 uppercase I will say St Str Now or S Str after uppercase is plus s strr so we are very simply trying to say uh that I want to convert the string to uppercase but when you run this code here you see that string is not manipulated so here we see no changes right so why we didn’t see any change so reason is that strings are immutable so when you run this code here so you see no change string Remains the Same so what exactly is happening here so you are getting a new string let’s say S1 so you’re getting a new string generated and when you will say see so S1 is plus S1 so you run the code here you see that S1 is manipulated a new string is created so guys whenever we are talking about string manipulation string manipulation means a new string will be generated but old string will not be modified so that brings in the first understanding that strings are immutable they cannot be changed we cannot modify their content now the next part so the way we got two uppercase in a similar way we got to lower case so I can search in the string I can say if s str. contain John right or let’s say not the John let’s say Jim so Jim is somewhere in between so I’ll simply come here and say Jim is in the string you run the code now it says Jim is in the string so contains method will help us to check whether a string is there a substring is there in the string or not now considering you want to break the string into a small string we can use a substring method I can say string S2 is Str Str Dot substring from the index number five so this is 0 1 2 3 4 and five index is this space right so I will say ciso S2 is+ S2 you run the code now what you see is that uh the guy John is trimmed off from the space till the end we got a new string so this is known as a substring a substring you mention the index so till from 0 to 4 string will be removed and there onwards five onwards you get a new string so even I can uh say string S3 is s dot a substring you go from six to uh let us say 10 so let us see what we will get in S3 so I’ll say S3 is plus S3 so when I run this code you see it is saying J NN now what is six let us see here guys right so 0 1 2 3 4 and this five till here we got the five index so start with six six 7 8 and 9 so 10 not inclusive right right so what is this so starts with sixth index and till 9 Index right so it’s like that is less than 10 so that’s like sub stringing so we can have a string so we can even replace the characters here so what I can do is I can say string S4 is Str Str do replace the character J with the character K so remember always you will get a new string right so now if you see S4 is plus of S4 so if you run this Cod here you see k canny Kim KAC and Co so instead of John Jenny Jim Jack and Joe now the next part here I will uh try to now uh you know get all the characters from the string so I will create a car array CH ER R which is s Str do2 care array so I have just converted the entire string into the array of characters so I got the array of characters from the string now I can say for car CH in ch so putting up an enhanced for Loop so I’ll just do a print not the print line and I’m going to print the CH along with some space that is what I’m going to do so lastly I put an empty print line so when I run the code here so you see the string with the space coming in so this was read as an array of correct s so we got array of characters coming in now let us take one of the use cases where I want all these uh you know names pulled out of this string that is like St Str I want to pull all the names from this string so what I can do is I can say a string array so let us say St Str RR so we will say St str s Str do split on the basis of comma so when need to put in a pattern on the basis of which we can uh you know split the string so thereafter I will say for string s in s Str ER so I’m going to do a ciso on S so when you run the code here what you see is that we got all the strings coming in but here we can see some uh space in the beginning because we got a space in the beginning after this comma right so if you want to remove the space you can just call the method called trim so trim is going to remove the space in the front or in the end beginning or ending right so now you see there is no space so splitting will help us to get the strings out of uh the string on the basis of some pattern right some pattern now moving ahead I’m going to write a string called email which is like John at some example.com and string like let’s say phone which is some phone number let’s say 9 999 and thereafter 88 8 8 and 8 so some string right for the phone number and let’s say there is a password so for this uh the password goes like password 1 2 3 so uh this is what this is data during registration right so while we are registering the user we are going to have this data from the user so you want to validate the data right so we would like to validate the data from user that is whether the data is correct or not right so I can simply come up and say if email do is empty so I’ll put a not here so if email is not empty right so I I can say ciso email is available other than in the else case I can say ciso please provide an email now if email is not empty email is available there can be even one more check that if email do contains atate and email do contains a DOT operator so if it is containing then it’s a valid email right so if I’ll put a not here it means that if anything is missing I can simply say email is available but email is not a valid email in the else case I can see see so email is a valid one so this is how we can you know use our string operations to check whether we get the correct string from the user or not so when I run this code here it says email is available email is a valid one so if you don’t put the email so let’s say email is empty here and you run the code so what you see is that email over here is not provided so it says Please provide an email so same way if you write an email with missing of at the rate so it says email is available all right so I think here I just need to put a check email contains so it should contain this and this right so so email is available but the email is not a valid email so we can put some conditions and check whether the data is correctly formed or not at the same time I can simply come here if phone dot is empty so if phone is not empty right same way the else part so please provide a phone number so here what we can do is we can see phone number is available and I can put one more check if phone do length is let’s say uh not equal to 10 so we are looking for a phone with the length as 10 right and the else part so I can say C so phone number is a valid one right so here I can say but phone number is not a valid number so similar validations right it says phone number is available phone number is a valid one so you miss out the phone number here you run the code it says please provide a phone number so you can get the things in order guys right so if the length is not 10 it says phone number is not a valid number so we are putting some validations here so same way you can put it on password now all these discussions which we have done so we are concluding one thing that strings are immutable so it means what if I create a string let’s say string is a new string and I say hello here and thereafter I will say spring do concat a space and a world right so concat is to append so we can even append the data like uh with the plus operator so that will also pend the data now I will say ciso string is plus the string if you run the Cod here it is just hello so this brings up the conclusion that strings are immutable we cannot change them so it is always a new string which will be constructed if you’re are going to do a concatenation now we got a version called string buffer so here I’m going to say hello now buffer and strings they are similar so we we will use aend instead of concap right so here I’ll say world and now when you’ll say ciso buffer is plus the buffer so what you will see is that in case of string buffer string is appended so data is manipulated in case of string buffer but not in case of string over here so this brings out that in case you want to manipulate the data in the same string right so we got this guy called string buffer which is mutable so mutable sequences of the string they are known as string buffer as well string Builder so the way you got buffer in a similar way we have string Builder the only difference is that Builder is not thread save whereas buffer is a thread save structure so the output shall be same for both of them and the usage is also same so I will say Builder is plus the Builder here so you run the code so you see buffer and Builder they work same way the difference is that buffer is thread save whereas this guy is not thread save so guys all the three versions like string string buffer or string Builder so we are very well aware with the uh you see strings now so we also understood what we need to do in case we need to use the mutable sequences so all three they Implement car sequence it means the reference variable to the car sequence let’s say CS it is let’s say null so CS can point to a string let’s say hello CS can also o point to a string buffer let’s say awesome and CS can also point to a string Builder so that’s like bu so that’s like runtime polymorphism right so this is like runtime polymorphism inaction so this is what we got As in the strings where uh strings they are immutable if you want mutable versions you go with the buffer and the Builder guys we got more many more apis in the string string buffer and string Builder so Explore More from here what is an interface in simple words an interface can be defined as anything which shares a boundary between two components in case of computers it separates two systems and access a boundary which helps in data exchange now what is a Java interface a Java interface can be defined as an abstract type which stores the methods and helps other classes to implement the behavior of the methods which an interface actually stores now you might get a question we have interface for that yeah absolutely with this we begin our next question why we need interface we all know that Java supports inheritance but when it comes to multiple inheritance Java cannot support it it ends up facing ambiguity between two parent classes and fails to provide the required result this particular problem is called as Diamond problem here as you can see there is a super class and this super class is been inherited by two classes called as Class A and Class B now we are trying to inherit the properties of Class A and Class B into a new class which is Class C which practically seems impossible in terms of java now the question would be is it seriously impossible to do it that’s when the interface come to the picture using interface we can achieve multiple inheritance here we are inheriting one class and implementing the behavior of another class confused let me explain with a little example let us consider an airplane which requires both the properties of carrying huge cargo and passengers let us assume we have two planes one is capable only to carry passengers and the other one is capable only to carry cargo now we need to carry both passengers and Cargo in one single plane which seems to be impossible on the basis of how the Java works as it feels it cannot access the properties of two different parent classes at the same time but you can make it possible by making Java feel that it is inheriting one plane and implementing the methods present in the other one it is like building a commercial plane which takes both the passengers and cargo luggage interface is like making a bigger plane which could do both the tasks without interfering with the components of one another instead just borrowing the methods which are present in the interface class now let us get practical first let us understand what was the problem in multiple inheritance here I have defined the first class class A and then the next class which is Class B and finally the class C here I’m trying to inherit the properties of Class A and Class B together in the class C by using extend keyword as you can see the editor is throwing an error which says that it is not possible to inherit the properties of both the classes now let us find the solution for this the solution is none other than using an interface here in this solution I am creating an interface I’m having the same messages which I had in my earlier example both the messages present in class A and Class B and similarly I have also defined the interface which has both the methods hello and welcome now let us run this program and see how does it work as you can see it is accessing both the methods and printing the message present in both the classes Class A and Class B now let us try a different example in this example I am declaring four methods addition subtraction multiplication and division now let us enter into a class here I’ll be trying to access all the four methods and print the output now let us try to run this program and see how the output appears as you can see the program has been successfully compiled and now it is asking for two integer values to perform the first operation which is addition the output has been successfully generated and now it is asking for two more integer values to perform subtraction the difference is been displayed now it is asking for two more integer values for performing the multiplication operation the output is clear now let us perform our final operation which is division as you can see we have our result here now let us understand the interface nesting as you can see I have nested an interface by the name inner interface inside another interface which is the outer interface and then I’m trying to generate a Fibonacci series using the method which is present in the inner interface which is other than the inner method using this method we will be generating the Fibonacci series let’s try to run the program and see the output as you can see we have our FIB series printed here and this process was being executed from the nested inner interface method now let us try to see an example for nesting by nesting an interface inside a class here I have nested an interface called edureka interface in inside a public class which is edureka class and inside the edureka interface I have a method called nested method using which I’ll be performing a string reverse operation let us execute this program as you can see the string I have provided is edura and after the operation you can see the string has been successfully reversed now let us have a one short quick revision about how to declare an interface so this is the syntax for declaring an interface where you will be using an interface keyword followed by the name of your interface and inside the interface you can declare your methods by default all the methods which you declare in interface are considered to be public with this let us find out the few differences between class and an interface the first difference is multiple inheritance interface was designed to provide multiple inheritance where on the other hand classes cannot the next difference is data members interface does not have data members all it includes is methods which decrease the probability of confusion during the implementation process on the other hand classes include data members which mean to say that the user must be careful while using the data members to avoid ambiguity the next difference is Constructors interface does not have Constructors while on the other hand classes take up the advantage by including them which will help them to set the values to the members of an object and the next one is complete and incomplete members interfaces comprise of only methods which make them have only the signature methods in them while on the other hand classes include both data members which are also called as abstract members as well as methods which are known as signature members the next one is access modifiers interfaces does not have access modifiers by default interfaces take up public as their access modifiers whereas classes provide private access modifiers which are not available in the interface the next one is static members interface cannot have any static members whereas class has all its members as static with this let us get into the major advantages and disadvantages of interface first let us begin with advantages we can achieve multiple inheritance in Java we can easily break up complexity and enable clear dependency between the objects we can achieve Loosely coupled applications through an interface don’t just be on the bright side interfaces have some disadvantages as well Java interfaces make the application slower when compared to the competitors like python which support multiple inheritance the next one is Once An interface is included in an application it might be used once in a while or it might end up being used multiple times at a larger scale with this let us discuss about the key points about Java interfaces the first one is can we instantiate an interface well we cannot create an object of an interface hence we cannot provide instances in an interface the next one is abstraction the major key advantage of interface is abstraction because none of the methods declared in an interface have a body the next key point is implementing an interface the keyword Implement is used in a class to implement the methods of an interface the method in an interface must be provided with an access modifier as public by default the methods declared in an interface are also considered as public class must Implement all the methods declared in an interface or else it must be declared in an abstract class let us see an example about implementing an interface here I have defined an interface and declared two methods into the interface method one and Method two the first method is used to find out a square root of the given number and the second method is used to print a message now let us try to execute this program as you can see it is asking for an input now let us provide a number to find out its square root as you can see the square root of the given number is four now let us try to execute a different example where we’ll be implementing the methods from two different interfaces as you can see this is my first interface and here my first method is to find out whether a given number is an amstrong number or not and later let us see a second inter interace where I have declared a method to find out if the given number is prime number or not now let us try to execute this example and see if the program can Implement both the methods from two different interfaces or not as you can see the class edureka 2 has successfully implemented both the methods from interface one and interface 2 and displayed the output I have given three as the input for finding whether it is prime number or not and the result is it is a prime number similarly I have given 153 to find out if it is an Armstrong number or not and the program provided the output as it is an amstrong number with this let us continue with our key points the next one is access modifiers in an interface interface can be declared as private protected and transient all the interface methods by default are abstract and public variables declared in interface are public static and and final by default interface variables must be initialized at the time of the Declaration otherwise the compiler will throw an error inside any implementation class you cannot change the variables declared in an interface let us discuss each one of these points practically here I have defined an interface by name try here I’m trying to declare an integer type variable a using int a is equals to 10 which is valid and similarly you can do it by using an access modifier public which is same as the previous one and you can also declare this variable by using public access modifier and making it as static and final the variable can also be declared by using final keyword and also the static keyword all the above stand the same now let us see the next point which we discussed in our access modifiers we discussed that the variables which we declare in an interface must be assigned to a value here I’m trying to declare an integer type variable X without assigning it to any value now let us try to run this program and see if there is an output or not and I’m trying to access the same X here in the main class and let’s execute this program as you can see there is an error which means that we were supposed to assign a value to the variable which we declared in the interface with this let us move on to our next stage of key points the next one is extending an interface an interface can extend any number of interfaces but cannot Implement them whereas a class can Implement any number of interfaces if there are two or more same methods in different interfaces then the class can Implement all the interfaces but one single method is enough to perform the operation a class cannot Implement two interfaces that have methods with same name but different return return type the major advantage of using an interface is that variable name conflicts can be easily resolved by using the interface name let us see this practically as you can see here I’ve defined an interface a with the method display and similarly I have also defined an interface B with the same display method inside it now I’m trying to implement both the interfaces A and B in my class same and I’m trying to access the display method let us try to execute this program and see if this runs or not as you can see the program has been successfully compiled and the output has been generated which says displaying data now let us discuss the next Point here I’ve defined an interface a which has the variable X of integer data type storing the value thousand and similarly I have also defined another interface with name B which has the same variable x with storing different value now in my main program if I try to access the variable X then it might provide me an ambiguity but if I use the interface name then I can successfully access both the variables and display the data present in them without facing any of the ambiguity now let us execute this program and see the output as you can see the value of x in the first interface a was th000 which is displayed here and the value of x in the second interface which is 2,000 is also being displayed here I used the interface name a and interface name b in the print statement provided here a data structure is a way of storing and organizing the data in a computer so that it can be used efficiently it provides a means to manage large amounts of data efficiently and efficient data structures are key to designing efficient algorithms next we have two types of data structures that is linear and hierarchical so what is linear data structures linear data structures are those whose elements are sequential and ordered in a way so that there is only one first element and has only one next element there is only last element and has no previous element while all the other elements have a next and a previous element understood like you can have only first and the next element and there is only last element but has only one previous element so there cannot be any multiple previous elements or multiple next elements okay but all the other elements have a next and a previous element note that there is only one previous and next elements simple So based on these categories linear data structure are being divided into stack q and Link list now talking about the stack stack is an abstract data structure it is a collection of objects that are inserted and removed according to the last and first out principle that is Leo objects can be inserted into a stack at any point of time but only the most recently inserted that is the last object can be removed at any time so you can see here this is a bottom element and this is a top element when you push the element into the stack it goes into the bottom and the last element that is the top element can be popped out so once the top element is popped out the next element which is available in the stack can be popped out but the bottom element cannot be popped out first understood so this is how it works that is it is an ordered list in which insertion and deletion can be performed at only one end that is the top it is a recursive data structure with a pointer to its top element it supports two fundamental methods that is push that is you can insert the element to the top of the stack and pop remove and return the top element onto this stack so if I have to give you an example it can be reversing a word to check the correctness of a parenthesis sequence implementing back functionality in browsers and many more now let’s see a small example of Stack so I have created a class called stack and the maximum capacity of the stack is 1,000 and as I told we need an element called top right because it’s a main thing so that’s a reason and then I’m initializing the maximum size of Stack so there are two conditions first is empty so if the stack is empty then return top less than zero because there is no element in the top when stack itself is empty then there is nothing right that’s a reason and then I’m creating a Constructor for stack and initializing the top size to minus one because nothing is there next what I’m doing I’m pushing the element into the stack so if top is greater than equal to maximum size minus one then print stack Overflow return false else insert the element to the top of the stack and initialize it to the variable that is X which is this one next say that so this element which is the element that you have inserted into the stack is pushed into the stack okay then return then again I’m creating a method called pop that is removing the element out of the stack so if top is less than zero then say back underlow else int X is equal to delete one element from the stack that is a of top minus minus then return X again I’m creating one more method called Peak if top is less than zero then say stack underlow else return the element at the top of the stack and return send it to X that is the element which you have taken it over here simple now I’m writing a driver code that is the main method I’m initially izing a stack and creating a object of a new stack and sending elements push 10 push 20 and push 30 and then when all these elements are inserted into the stack if I want again I can you know say push 4 so when I use S do pop so what do you think will this element will be popped out first or this element obviously this element right so now let’s run and check for the output so you can see first 10 was pushed into the stack 20 was pushed 30 was pushed into the stack and then 40 but when I used s. pop the last element was popped out so if I don’t have this element I’ll just save this now see the last element which is 30 is popped out from the stack right so this is how you can execute your stack and these are the operations that is performed on a stack so this is how it works now talking about the next data structure that is q q is also another type of abstract data structure and like a stack the Q is a collection of objects that are inserted and removed according to First in first out principle that is elements can be inserted at any point of time but only the element that has been in the queue the longest can be removed at any time so you can see here it has two ends that is front end and back end that is the front front end and the rear end so if you insert an element it goes to the front and that can be popped out that is removed but in case of Stack it is last and first out in case of Q it is first and first out it supports two most fundamentals that is NQ and DQ NQ means you have to insert the element at e that is at the rare of the Q and DQ means remove and return the element from the front of the queue so whatever element you insert at the rare end will go to front as soon as you inserted more right so simple that can be taken off from the Q end so Q’s are used in the asynchronous transfer of data between two process that is CPU scheduling dis scheduling and other situations where resources are shared among the multiple users and served on first come first serve basis so these are some of the situations where Q can be used okay so now let’s take a an example and understand how it works so this is very simple I have created a class called q and I’m creating a string of Q and assigning it to a link list so what I’m doing is I’m using q. add and I’m adding all the four elements and then displaying the elements present in the Q so when I say q. remove of three it will display the elements present in the que and the Q size and says whether it contains the element two or not if yes it displays that let’s run and check the output so first when I print this it displays the size and let me tell you one thing this is a inbuilt function so that is the reason when I’m using add it is being added automatically so then what I did I removed the element three so you can see here I can remove any element it’s not that the element which is there at the last or the element that is there at the top or nothing like that you can just remove the element from any corner and then when I remove the element and I print the Q it says only the remaining elements that is 1 2 and four next Q size is Q do size that is three and then whether does it contain the element two in the Q yes true if I say element three in the que it should say false because I have popped it out right so let’s see what it says it says true because initially in the Q it was present so if I now say say element 5 then run so when I say Q do contains 5 it should say false because it’s not there in the list right see it’s telling false so this is how you can perform the operations on the Q the next data structure is link list a link list is a linear data structure with the collection of multiple nodes where each element stores its own data and a pointer to the location of the next element The Last Link in the link list points to null indicating the end of the chain element in the link list is called a node the first node is the head and the last node is a tail so there are three types of Link list one is singly link list that is unidirectional where it contains only the information of the next node so when it comes to W link list it contains the information of the next node also the pointer to a previous node and when it comes to Circular link list head points to a tail and the last node points to the first element of the first node that is the last element of the last node points to the first first element of the first note so if I have to tell an example so imagine a link list like a chain of paper clips and they link together you can easily add another paper clip to the top or bottom it’s even quick to insert one in the middle all you have to do is you have to just disconnect the chain at the middle add the new paper clip then reconnect the other half a link list is a similar way of doing all these operations let let’s take a small example and understand this in a better way so I have created a class called link list example and node head is a head of the list and I have created a class called Static node the inner class is made static so that main can access it that is the main method can access it so I have the data and the next node and the Constructor for the node is int D because data is equal to D and next should be assigned to null now the next step is to insert a new node so for that what I’m doing I’m creating a static method for linkless example and I’m inserting linkless example list and int data and I have to create a new node with the given data so what I’m doing I’m creating a new node with the data and assigning the next node to null because that is mandatory so if the link list is empty then make the new node as head so if link list is empty that is if list do head is equal to null then make the new node as head that is new node is equal to head head else Traverse till the last node that is node last is equal to list. head and then insert the new node again insert the new node at the last node and finally you have to return the list by head okay now this is a method to print the link list so current node is equal to list. head and the link list contains the elements that is being present in the current node and the list that is already being inserted so when I have to travel to the link list I’ll check whether current node is not equal to null if it is not equal to null then print the data at the current node using the statement or else go to the next node in the main method I’m creating a object of a new link list and I’m inserting the values into the list in sequence then finally I’m printing the list okay so now let’s run and check the output so see the elements are being inserted in the sequential order so this is how it works so this was all about the linear data structures now moving further we have hierarchical data structures which comprise of binary tree binary Heap and hashmap as well so binary tree is a hierarchical tree data structure in which each node has at most two children which are referred to as left child and the right child each binary tree has a group of nodes that is root node left sub tree and the right sub tree the root Noe is the topmost note and often referred to as main note because all the other nodes can be reached from the root and left sub tree and the right sub tree is also a binary tree and binary tree can be traversed in two ways that is depth first Travers veral that is in in order pre-order and post order and breadth first traversal that is level order traversal and the complexity is Big go of N and the maximum number of nodes at level L is 2 ra to the power L minus1 and binary search applications include it can be used in many search applications where data is constantly entering and leaving also as a workflow for compositing digital images for visual effects used in almost every high bandwidth router for storing router tables also used in Wireless networking and memory allocation also used in compression algorithms and many more so this is all about the binary tree now talking about the Heap it’s a complete binary tree which answers to the heat property in simple terms it is a variation of a binary tree with the property is like a tree is set to be complete if all its levels except the possibly the deepest are complete the property of the binary tree makes it suitable to be stored in an array it follows Heap property that is a binary Heap is either a Min Heap or Max Heap Min Heap is for every node in a heap node’s value is lesser than or equals to value of the children maximum binary Heap is for every node in a heap the noes value is greater than or equal to values of a children and popular applications of binary Heap include implementing efficient priority cues efficiently finding the K smallest elements in an array and many more the next concept is Hash tables imagine that you have an object and you want to assign a key to it to make searching very easy to store that key value pair you can use a simple array like a data structure where keys that is integers can be used directly as an index to store data values however in cases where the keys are too large and cannot be used directly as an index a technique called hashing is used in hashing the large keys are converted into small keys by using hash functions the values are then stored in a data structure called a hash table a hash table is a data structure that implements a dictionary ADP that is a structure that can map unique keys to values in general a hash table has two components one bucket array and the hash function a bucket array for a hash table is an array a of size n where each cell of a is thought of as a bucket that is the collection of key value pairs the integer n defines the capacity of the array next hash function it is any function that Maps each key K in our map to an integer in the range 0 comma n minus1 where n is the capacity of the bucket array for the table when we put objects into a hash table it is possible that different objects might have the same hash code and this concept is called as Collision to deal with a collision there are techniques like chining and open addressing so these are some of the most Basics and frequently used data structures in Java now that you are aware of these you can start implementing them in your Java programs so I hope you understood the concept of linear and hierarchical data structures what is link list a link list is considered as a data structure similar to any other data structure like arrays stacks and cubes the link List have three major parts head tail and node every node in the link list is interconnected using the address of the next node before we get started with the link list let us understand the terminology of array before using an array we actually reserve the memory blocks in the memory to store the data in order to process them for example I have reserved an array of integer data type and I’ll be storing five elements into it the name of my array is my array and the addresses for the array are 0 1 1 2 3 and 4 so now let us try to add the elements into my array the first element is 10 as you can see the first element is stored in the index zero of my array similarly I’ll try to add four more elements into my array which are 2030 40 and 50 as you can see the data is been successfully inserted and the insertion order is been secured each and every element is been inserted into the array in a sequential order and now we can access them using their index numbers but in case of Link list this doesn’t happen unlike arrays they do not work with the completely reserved sequential collection of memory instead they choose the random blocks from the Heap and store the data into it and provide access to the data whenever needed the best part is once the use of Link list is done and if you won’t need it then you can actually dump the memory blocks back into the memory Heap which makes them reusable once you provide the data into the link list it will borrow the particular number of memory blocks from the Heap based on the data typee you provide for example two or four bytes for each block of an integer data type and four bytes for each block of a float data type and 16 bytes of data for each block of double data type and so on each block it selects will have a memory address along with it and a space for data to be stored once the data is stored then the last memory block will replace the address with a null value which indicates the end of the link list using the interconnection between the notes the link list behaves like an array and displays all the data in the form of a sequence now that we have understood what exactly a link list is let us discuss about the types of Link lists the link lists are majorly divided into three types the singly link list the doubly link list and the circular link list a singly link list is a standard link list which mainly consist of two Fields the address space to store the address of the next node and the blog for storing the data as you can see this particular node is the head node and this particular node is the tail node this is the block which stores the address of the upcoming node and this block stores the data we can Traverse in one single Direction in a singly link list the next one is the W link list the W link list is completely similar to a singly link list but the only difference is that the nodes in the W link List have three Fields namely the address note for the next upcoming note the memory block to store the data and finally the block which stores the address of the previous node as you can see this particular Noe is the head node this particular note is the tail Noe and these notes are the intermediate notes which are lying in between the head node and the tail node as you can see this particular block of this node is pointing to its previous node and this particular block of this node is pointing to the upcoming node and this particular block is designed to store the data which you provide into it this makes the dou link list Traverse in both the directions now let us move into circular link list the circular link list is a singly link list but the only difference is that the final note address block is not ended with a null value instead it points to the address of the head node as you can see in this particular link list the address of the first block is pointing to the next one and the next to the next one followed by which we will reach the tail node in the tail node the address here is not null instead it is pointing to the address of the head node that’s what it makes as a circular link list now let us discuss some important features of Link list the important features of Link list are first one is q and DQ interface the link list implements q and DQ interface therefore it can also be used as a q DQ or a stack the next one is it can contain all the elements including duplicates and null the the thirdd one is link list maintain insertion order of elements the next one is Java link list is not synchronized that means in a multi3 environment you must synchronize concurrent modifications to the link list externally we can use collections. synchronized list to get synchronized link list link list class does not Implement Random Access interface so we can access elements in a sequential order only we can use list iterator to iterate the elements through the list now that we have understood the features of the link list let us move into the methods that we can use in the link list there are more than 40 methods that we can apply in link list but here to save time let us discuss the crucial methods required to actually work with link list here as you can see I’ve used the link list method which is provided in Java and I’m creating a link list and then I’m trying to add the string type values into my link list using the link. add method and find finally we shall also use collection method which is previously described in Java to add few more elements which are of string type into our link list and try to append them in the tail section of the link list let us try to execute this program and see how does it work as you can see the output is been printed here the first data which we tried to insert into our link list was welcome to edureka and after that we tried to append the data of string type into the end part of our link list which happens to be the tail and the link list after appending the string data type at the last is welcome to Eda an online technology training center now let us try to insert the data at the head part of the link list so in this particular program I’m making use of the link list method which is previously described in Java and I’m adding the elements welcome and Eda which are string data type into the link list and in the next section I’m using collection method and I’m adding few more elements into the link list at the head section of the link list now let us try to execute this program and see how does it work as you can see the output has been successfully generated and the data of the link list before appending the data to the Head section was welcome urea and after appending the data to the Head section we have welcome to the most popular online technology training center edureka now let us execute add method in this particular method we are just appending new elements into the link list similar to the previous methods I have created a link list using the link list method which is previously programmed in Java and I’m trying to add up the elements into it as you can see in in this first section I’m having few elements called hello world message from Eda and after that in the second section I’m trying to add two new elements which are new and element let us try to execute this program and see how does it work as you can see the output has been successfully generated and the link list before appending the new element to it is Hello World message from urea and after appending the new element we we have Hello World message from edureka and the new elements which are new and element now let us try to append the data using add method by using the index followed in the link list as you can see in this particular example I’m trying to add two new elements which are U and welcome at the index locations 2 and four respectively now let us try to execute this program and see how does it work as you can see the output has been successfully generated and the output before adding two new elements are how are question mark to edura here I’m adding you and welcome into this particular link list in a designated location which is 2 and four so after adding two new elements this particular link list is making a sensible statement which is how are you question mark and welcome to Atura now let us try to execute clear method as you can see in this particular example I have created a link list and I have also added some elements into the link list which is edura online training institute after that I’ll be clearing the link list using the command list. clear once after I clear the list the link list becomes completely empty after that I’ll be using the add method again to add up new elements into the link list so now here the link list will be completely erased in the first half and after that once if I try to insert new elements into it then it will take up the new elements and add them into the previously existing blocks without having the previous data in the link list now let us try to execute this program and see how does it work and understand it in in a better way as you can see the data has been successfully generated and the data which was present in the link list before clearing was edura online training institute once after the data has been cleared successfully the new elements are been added into the link list which are now tied up with nit War Angle now let us try to execute clone method in this particular example I’ll be using clone method the Clone method is nothing but you cloning the existing link list now let us try to execute this program and understand this in a better way as you can see the first link list is example for clone method I’m using clone method and I’m trying to duplicate the first link list which has the same data as you can see which is example for clone method now let us try to execute index method as you can see in this particular example I’m using index of method so here I have inserted some data into my link list which is using index off method so what I’ll do here is I’ll be using list. index of method to find out the index of a particular element so here I’ve chosen using element and Method element to find out the index of those particular elements let us try to execute this program and see how does it work as you can see the output has been successfully generated and the link list was using index of method now the index of the element called using is zero and the index of the element method is index 3 now let us execute offer method as you can see in this particular method I have created a link list and added the elements BMW Posh and Mercedes and I’m using offer last method to add the final element which is Jaguar to the link list so let us try to execute this program and see how does it work as you can see the output has been successfully generated and the elements in the link list before using offer last where BMW POS and Mercedes and the elements after executing the offer last method is BMW Posh Mercedes and jaguar where the element Jaguar is included into the link list at the last section which happens to be the tail now let us execute offer first method in this particular example I’m creating a link list which will be having the elements C language Java and cin and finally I’ll be using the offer first method where I’ll be including the python element in the head section of the link list now let us execute this program and see how does it work as you can see the python element is included here at the head section now now let us try to execute pop method in this particular example I have pushed in two elements which is a and b and here I’ll be using the pop method to pop the last element which is pushed into the stack and after that I’ll try to push a new element which is C into the stack and finally we’ll print the stack which is existing right now let us try to execute this program as you can see the last element which was pushed into the stack was B and after popping it we have the elements C and A which are existing in the current stack now let us try to execute the push example as you can see this particular example is similar to the previous one here we are just pushing the elements into the stack using the stack push method as you can see the output has been successfully generated and the elements which we have pushed into the stack are 100 200 and 300 now let us try to execute a remove method as you can see in this particular example I’m trying to insert four elements into the list which are apple banana and grape and here I’m using list. remove method to remove one element from the link list which is the first element which happens to be apple now let us try to execute this program and see how does it work as you can see the elements before removing the element Apple are apple banana grape and pineapple so once once after I remove the first element the remaining elements are banana grape and pineapple now let us try to execute the set method in this particular example I’ll be using list. set method here I’m trying to set two elements into the link list which are kiwi and orange at the position two and three as you can see this is the element kiwi and this is the element orange and I’m trying to set Ki into the position number two and orange into the position number three let us try to execute this program to understand this in a better way as you can see the output has been successfully generated and the elements before inserting them into the second and third position are apple banana grape and pineapple the objects grape and pineapple which were at the positions 2 and three are replaced with kiwi and orange now let us try to understand size method size method is not a complicated Method All it does is shows the number of elements which are present in an array now let us try to execute this program and find out the size of the particular link list as you can see I’m using list. size over here and I’ll be finding out the size of this particular link list now let us try to execute this program as you can see the link list is apple banana grape and pineapple and the size of this particular link list is four now let us try to convert an array into the link list as you can see in this particular example I’m trying to add the array which is courses which has Java PHP Hardo devops and python elements into a link list so here I’m using for Loop into which I’ll be adding the string s Elements which are courses into the link list which is a course list using the add method now let us try to execute this program and see how does it work
as you can see the elements Java PHP Hadoop devops and python were actually the elements of an array called courses and using the add method we have added the elements of an array into the course list which happens to be the link list and here the output has been printed successfully which happens to be the output of a link list now let us try to convert a link list into an array in this particular example I’ve used add method to add the Java python devops Hardo and AWS elements into a link list called as course list now we’ll be using to array method to add all the elements which are present in a link list into an array now let us try to execute this program and understand this in a better way as you can see the size of the link list was five the elements of the link list were Java python Hadoop devops and AWS which are now included into the array called as numbers which which is displayed as follows Java Python devops hadu and AWS so these are the elements which are present in the array called as numbers so we have successfully converted a link list into an array now let us discuss the major differences between arrays and Link lists the arrays are not resizable because the size of the array has been defined at the Declaration section itself but on the other hand link lists are dynamically resizable the next difference is the ARs offer more methods compared to link list while the link list are concise to few methods compared to arrays the third difference is the arrays have insertion addition and removal operations done in a faster way while in link list you have to Traverse from head to tail the random axis is not provided by link list so these operations are comparatively slow in link lists the last difference is the AR consume more memory because hardly the aray memory which you allocate is been reused but in terms of Link list the memory which you use can be dumped back into the Heap and it is readily available for reuse so Aries consume more memory and the linkless consume less memory let’s understand what is a hashmap in Java hashmap is a part of Java’s collection since Java version 1.2 it provides the basic implementation of map interface in Java it stores the data in key value pairs to access a value one must know its key hash map is known as hashmap because it uses a technique called hashing so what is hashing it is a technique of converting a large string to a small string that represents the same string a shorter value helps in indexing and faster searches hash set also uses hash map internally it internally uses a link list to store key value pairs so the important features of hashmap are it is a part of java util package it extends an abstract class that is abstract map which also provides an incomplete implementation of map interface hashmap also implements clonable and serializable interface it does not allow duplicate keys but it allows duplicate values that means a single key cannot contain more than one value but more than one key can contain a single value hashmap allows null key also but only once and multiple null values and this class makes no guarantees as to the order of the map in particular it does not guarantee that the order will remain constant over time it is roughly similar to hashtable but is unsynchronized so these are the various features that makes it the popularly used data structure next talking about the internal structure of hashmap it contains an array of node and node is represented as a class which contains four fields that is inh K key V value and node next next it can be seen that node is containing a reference of its own object so that is the reason it is called a link list so very simple it compris of a node which compris of a key and value and it has int hash and node is having the reference of the next variable as well so this is all about the internal structure of hashmap now talking about the performance of hash map it mainly depends on two parameters that is initial capacity and the load Factor so capacity is the number of buckets where the initial capacity is the capacity of the hashmap instance when it is created the load factor is a measure that when rehashing should be done and rehashing is a process of increasing the capacity in hashmap capacity is multiplied by two and load factor is also a measure that what fraction of the hash map is allowed to fill before rehashing ing when the number of entries in the hash map increases the product of current capacity and the load factor is also increased that is it implies rehashing is done if the initial capacity is kept higher then rehashing will never be done but by keeping it higher it increases the time complexity of iteration so it should be chosen very cleverly to increase the performance the expected number of Valu should be taken into account to set the initial capacity most generally preferred load Factor value is 75 which provides a good deal between the time and space cost and the load factors value varies between 0o and one based on these two factors that is initial capacity and a load Factor performance of a hash map is measured now let’s move into the next section and understand what is a synchronized hashmap as it is already told that hashmap is unsynchronized that is multiple threats can access it simultaneously if multiple threads access this class simultaneously and at least one thread manipulates it structurally then it is necessary to make it synchronized externally it is done by synchronizing some object which encapsulates the map if no such object exist then it can be wrapped around collection synchronized map to make hash map synchronized and avoid accidental unsynchronized access so you can see that I have used collections. synchronized map and created a new hash map so by using this a map m is synchronized iterators of this class are fail fast if any structure modification is done after the creation of iterator in any way except through the iterators remove method in a failure of a iterator it will throw concurrent modification exception so this is how you can make a map as synchronized now let’s see some of the constructors that are widely being used hashmap provides four Constructors and access modifiers of each one of them is public first one hashmap it is a default Constructor which creates an instance of a hash map with initial capacity 16 and load Factor 75 next hash map with in initial capacity this also creates a hashmap instance with specified initial capacity and a load Factor 75 next hashmap with in initial capacity and Float load Factor it creates a hashmap instance with specified initial capacity and a specified load Factor next one that is a last Constructor hash map which has arguments of type map it creates instance of hash map with same mappings as a specified map so now let’s write a small program and understand how does do the hashmap work so I have created a class called hashmap and inside that I have a main method and you can see I’m using hash map and I’m passing the parameters like string and integer and I’m mapping it with the object of a new hash map so first when I print the map it should say this map is empty because nothing is there in the map right so then I’m using the put method to insert the elements into the map that is ABC 10 m 30 and XY 20 then the when I print this it will say the size of the map that is three then next I will check whether a map contains a key called ABC so this is the keys and this is the value of the respective key right so when I check if it has a key called ABC then I’m using a map dog to display the value of ABC so the value for key ABC will be whatever is present in this right then again I’m clearing the map and again printing the map now I’m using a method called print I’m passing the arguments for map means it should contain the map of same mappings so if it is empty then print map is empty else return the elements and that is the key value pairs present in the map so let’s run and check the output so first what it said it said map is empty because I’m PR printing the map without entering anything in that so it will go to the print method and check whether the map is empty or not yes it is empty so it will retrieve the result so next this statement got executed and it’s telling the size of the map his three because it has the key value for three different categories again it will print the map so this will again go to the function definition and print this statement because now the map is not empty so there’s a function call over here and now size of the map is map do size what is the size three so it is displaying the size of the map as three and is printing all these elements now value for key ABC is 10 so that’s what I’m checking over here that is get the key for ABC and print its value so if I do it again like you know m n o again change it over here as well and and here as well okay so it will print the value will be 30 so finally after clearing the map again it’s telling map is empty now let’s run and check the output it’s MN o you can see that the value for the key m o is 30 right I hope you understand this so this is how you can configure your hashmap and map it accordingly so now talking about the complexity of hashmap it provides a constant time complexity for basic operations that is get and put if hash function is properly written and it disperses the elements properly among the buckets iteration of hashmap depends on the capacity of hashmap and the number of key value pairs basically it is directly proportional to the capacity Plus site and capacity is the number of buckets in the hashmap so it is not a good idea to keep a higher number of buckets in hashmap initi so this is all about the time complexity now let’s have a look at the various methods that are widely being used in a hash map first void clear this is used to remove all the mappings from a map next Boolean contains key that is parameter will be object key this is used to return true if for a specified key key mapping is present in the map and again Boolean contains value of object value this is used to return true if one or more key is mapped to a specified value next method is object clone this is used to return a shallow copy of the object of the mentioned hashmap next Boolean is empty used to check whether the map is empty returns to if it is empty next object get object key this is used to retrieve or fetch the value mapped by a particular key set key set this is used to return a set views of the key in size used to return the size of the map next object put parameters will be key and value this is used to return a particular mapping of key value pair into a map next put all of map M this is used to copy all of the elements from one map to other next object remove object key this is used to remove the values for any particular key in the map and the last one is collection values this is used to return a collection view of the values in the hashmap so these are the various methods that are widely being used in the hashmap let’s understand what is generics in Java generic is a term that denotes a set of language features that are related to the definition and the use of generic types and methods Java generic methods differ from regular data types and methods so before generics we use the collections to store any type of objects it can be either a generic or non-generic object now generics Force the Java programmer to store a specific types of objects so basically this is all about what is gener now let’s move further and see why do you need Java generics if you look at the Java Collections framework then you will observe that most of the classes take parameter or argument of type object so basically what happens in this form they can take any Java type as argument and return the same object or argument it can be either a homogeneous or heterogeneous that is not of a similar type so sometimes in the Java application the data type of the input is not fixed the input can be an integer a float or a Java string in order to assign the input to the variable of the right data type prior checks had to be conducted in the traditional approach after taking the input the data type of the input was checked and then it was assigned to the variable of the right data type when this logic was used the length of the code and execution time was increased So to avoid this genics were introduced so on using generic the parameters in the code is checked at compile time automatically and it sets the data type by default so this is where you need the concept of generics in Java as the execution time and the time that you invest in writing the code will also be decreased so now that you know what is gener in Java and why do you need it let’s move further and see some of the types of gener so basically there are four types first generic type class and you have interface method and Constructor first let’s understand what is generic type class a class is set to be generic if it declares one or more types of variables so these variable types are known as the parameters of the Java class let’s understand this with the help of an example so here you can see I have created a class with one property X and the type of the property is object correct so what happens once you initialize the class with a certain type the class should be used with that particular type only for example if you want one instance of a class to hold the value of type string then programmer should set and get only string type since I have declared the property type to object there is no way to enforce this restriction a programmer can set any object and expect any return value from the get method since all Java types are subtypes of object class so it’s very simple right so here I’m creating a method for set and get and I am using the this keyword for reference and then when I return the value of the X it can be any type but all the Java types are subtypes of object class so I can set a property for integer and can return string anything it can be so this is how it worked the next type is generic type interface an interface in Java refers to the abstract data types they are allow Java Collections to be manipulated independently from the details of the representation also they form a hierarchy in objectoriented programming languages so let’s take an example and understand this so here I have created a interface for gener and I’m doing two operations for T1 and T2 so for T2 what I’m doing I’m performing the execution I’m passing two variables that is T1 and X and next what I am doing I’m performing a reverse execution of whatever I have performed in the above statement so when I create a class for generic and implement the interface whatever I perform the execution will be reverse in the next execution suppose say while performing the execution and passing a string variable and that can be easily converted to a integer variable when I’m reversing the execution so basically all that matters is the type of the object and there is no way that I have to enforce a restriction or anything like that it can be a string integer double float anything so I hope hope he was able to understand how genri can be applied to interfaces now let’s see what’s next the next type is generic type method so generic methods are much similar to generic classes but they differ from each other in only one aspect that is the scope or type of information is available inside the method only generic methods introduce their own type parameters so let’s take an example and understand this so in this case what happens if you pass a list of string to search in the method it will work fine but if you try to find a number in the list of a string it will give compile time error yes right because see first I’m using Advanced for Loop I’m trying to check the element present in the list if the list is an string then it will match because always list is a string like list can be a string it can’t be a integer so when I try to find a number in this list it will give error right so that’s how I have coded this program and that’s how the generic type method tells you that is they introduce their own type parameters there is no way that I have to define something or user have to define something there’s nothing like that it’s like they Define their own type of parameters so this analogy is similar for Constructor as well so if I talk about the generic type Constructors the same goes here as well so basically a Constructor is a block of code that initializes the newly created object a Constructor resembles an instance method in Java but it is not a method as it does not have a return type the Constructor has the same name as the class and looks like how I have written in the code so here in this example Dimension class Constructor has a type information as you can see that so basically you can have an instance of Dimension with all the attributes of a single type only for example you have a class Dimension that is of a type T and I have created three variables when I create a Constructor for all these three values you will get the length width and a height by using the this reference because I’m giving this this do length is equal to length this do width is equal to width and this do height is equal to height so you cannot get any other parameters apart from this in this regard that is you can have an instance of Dimension with all attributes of a single type there won’t be any different types over here so this is how you can use type Constructors so now let’s see a small example of generic and understand how actually it works so here I have created a class called test one and I have passed two Vari that is T and U T is a type of an object o1 and U is a type of an object O2 o1 and O2 are object of type T and U correct so now for this I’m creating a Constructor and then I’m giving this reference that is this do object 1 is equal to o1 and this do object two that is O2 is equal to O2 and now I want to print the objects of T and U so I’m basically creating a method called print and then I’m passing these two variables in this and after that I’m creating a class called generic and inside the main method for the test one for object T and U one will be the string that I will be passing and the other one will be integer so you can see here that I have not created any specific integer or string variable instead I’m just passing the type of an object that is T and U to be a string and an integer correct there’s no restriction or I don’t have to enforce anything over here so I’m going to create a new object for that that is test even and pass the variables as adua and integer value will be 10 so when I give object do print this object is nothing but this reference it will call the method or the object from this print so what will happen it will display the elements present in the o1 and O2 so the elements present in o1 and O2 is nothing but the edua and 10 so when I execute this let’s see what happens I’ll run this as a Java application and let’s see so you can see here that in the output screen it set edura and 10 which means there is no type restriction over here it’s very simple as you saw all that refers to is a type of the object like all the Java types are subtypes of object class and that is the reason I’ve taken object class and referred all the elements as objects and then pass whatever I wish to that is a string and an integer and then I print it so this is how it works now let’s see what is generic functions so we can also write generic functions that can be called with different types of arguments based on the type of the arguments passed to the generic method and further compiler handles each of these methods so let’s see how it works so I have a class called test in this I have created a method that is generic display and pass the element as St element okay so now I’ve have made this as static and I’m using the generic type t Okay so next when I’m giving system.out.print Ln element. getet class. getet name plus element okay so you can see here that in one single print statement I’m trying to get the class get the name and also the element so let’s see how this one single line of code works so inside the main method I’m calling generic method with in argument okay so generic display is nothing but this method right so the T element that is the type of element is integer so it is 3 4 5 6 correct so next I’m again calling the generic method with string argument that is I’m calling the method that I’ve created above and I’m passing the element of type t as a string and after that we’re double so you can see here that there are three different types of elements that is integer string and double and all these are of different data types right so when I say get class. get name plus element it will say the class is this and the name will be the integer type and the element will be the value yes let’s execute and then you will understand what actually that statement does as I told you element. getet class. get name is equal to element right so element is Java do Lang is a type of the class do integer is a type of the name first one is integer so element. getet class. get name is equal to this value so same goes for next also element that is Java do Lang is the get class do string is get name and Eda is a value same goes with double as well so you can see here multiple types of arguments was being passed at one single instance so this is how the generic function works as you can pass n number of arguments by just referring to it as a type T there is no specification there is no restriction that you have to enfor it on all that you have to do is create a object of a type generic and then go on adding the values simple yes that’s how generic works now let’s move into the last part of the session and understand some of the advantages of genri and Java first code reusability you can compose a strategy or a class or an interface once and use for any type or any way that you need next type safety as you just saw that whenever you use different types of arguments and when you casted in different types of arguments it was very safe right there was no hampering of the code or there was no destruction of the code or there was no any type issues when you try to cast the code or when you use various types of code there was no hampering between those codes so obviously it this type safety individual typ casting is not required basically whenever you recover information from array list every time you need to typ cast it but T casting at each recovery task is a major migraine so in order to eradicate that approach genics were introduced as you just saw you can use various data types and there is no casting of that required because you can use all of them at once and all that refers to as an object so that’s why I think type casting is not required next implementing a non-generic algorithm it can calculate the algorithm that works on various sort of items that are type safe as well it can be a generic or non- generate no matter what it will Implement everything let’s understand what is file handling in Java so file handling implies how to read from a file and how to write to a file in Java and Java basically provides the basic input output package for reading and writing streams and also java. inputoutput package allows you to do all the input and output tasks in Java so in order to use a file class you need to create an object of the class and specify the file name or directory name as shown below so first you will write import java.io file that is used to import the file class and then you have to create the object of a file and specify the file name simple so let me tell tell you one thing Java uses the concept of stream to make input and output operations on a file so let’s Now understand what is stream in Java so the stream is a sequence of data it can be of two types bite stream and character stream now talking about the bite stream it mainly incorporates with bite data when an input and output process happens with a bite data then it is called the file handling process with bite stream now talking about the character stream it it is a stream which incorporates with characters when an input and output process happens with a character then it is called as the file handling process with bite stream so these are the two types of streams that are available now let’s move further and have a look at the various file methods that are useful to perform Java file operations first can read this method is used to test whether the file is readable or not next can write this method test whether the file is writable or not and next you have a create new file which creates an empty file and next delete this command is used to delete the file exist this test whether the file exist or not and next you have get name which is used to return the name of the file and you have get absolute path and this is used to return the absolute path name of the file and next you have length and it Returns the size of the file in bytes now moving further you you have list this method is used to return the array of the file in a directory and you have mkdir which is used to create a directory okay now these methods are used to perform various file operations now let’s see what are the various file operations that are present in Java so first you need to create a file then once you create a file you need to get the information out of the file after that you have to write the information to the file and then you have to read the data from the file correct so now let’s understand all these things in a much better way with the help of an example first create a file in this case in order to create a file you can use a create new file method okay and this method returns true if the file was successfully created and it returns false if the file already exist okay so here is an example for creating a file so first I have created a package and inside that I have a class called create file as I have already told you I need to import the file class so that is the reason I’m using this package okay and next in order to import the input output exception class to handle the errors I have java. input output. iio exception okay so next after that I have created a class called create file and inside the main method I’m using two blocks that is try and catch so inside the triy block what I’ll do I’ll write a code that has to execute and the catch block so if there is any error that is going to occur in Tri block it will be handled and in this case most expected error can be the io exception so that is the reason I’m using a catch block to handle that okay so inside the tri block let’s see what I have written so I have written file my object is equal to I’m creating a new file in the specified directory if I don’t give the path if I just give the name of the file that is file f.txt it will by default go go and store this file in the location where my Eclipse workspace is so I don’t want to do that I want to create a file in a specified file location and that’s a reason I’m giving this and now if my obj that is my object do create new file then if the file is being created with this object then it is telling file created and get the object name that is get name so get name will be what file F not txt right else if the file already exist it will say file already exists and if there is any exception it will be handled in the catch block so now let’s run and check the output so you can see that it’s telling file created and it returned the name of the file that is my obj doget name that is file fn. txt correct so yes that’s how it works now let’s cross verify this I’ll go to my D drive I will go to file handling and you can see and you can see file f created correct so in this location itself I have created the file so if I run this program one more times let’s see what happens so it’s telling file already exist because one time you created a file it will be present in that particular location so it will say file already exist cor right so this is how you need to create a file so the next step is to get the file information so here again I’m importing the file class and then I’m creating a class called file information and inside the main method I’m creating a new file okay and I will check if this already exists then it should print the file name get file name that is my obj doget name and then it should again print the absolute path of the file and for that I’m using get absolute path method and then I’m using if it is writable it will print can write if the file is readable it will say can read and the file size and bytes will be my obj do length Okay else if the file does not exist then it will print file does not exist so you can see that I have used all the methods that I have explained you before that is get name get absolute path can read write and length right so let’s run the program and check for the output so you can see that the file name is file 1.txt the absolute path is it’s in this location that I have already showed you just now for writable and readable it’s telling true because yeah it is readable and writable and the file size in bytes is zero so I have one more file here let me show you that I have a file called new file 1. text okay so inside that I have written some text so it means it consists of a text right so when I say the file size in bite you has to return the length but here it is telling zero because I have not written anything into that file so now if I change the file name let’s see what it will return for the statement let me run and check it once again so you can see that it return the file name absolute path it is readable and writable and the file size in bytes is 52 correct so if you have written anything in the file then it will on the file size or else it will not simple so this is how you need to get the file information next let’s see how to write to a file so here I have created a class called Write to file and inside the main method again I have two blogs that is try and catch and here I’m using the my writer method so here I have used the file writer class together with its right method to write some text into the file let’s Now understand how actually works so I have used a file writer and I’ve created a object of the writer and this is a path where I have saved my file and this is where I want to write some data into the file right then I’m using my writer’s write method to write this particular context in the file and after that I have to close it so once I close this I will say successfully rot to the file okay if the data has been written into the file then it will say I have successfully written the data into the file else it will throw an error and will be handled in the catch block let’s now run and check the output so it’s turning successfully wrot to the file now let’s cross check this so you can see that it has written the data into the file that is Java is a prominent programming language of the Millennium if you want to do any editing over here you can do which means is writable and if I want to read the data from the file I can read it as well right correct see so simple it will even ask whether to save or not if I say save yes it will get saved very simple right so that’s how you need to write a data to the file now that you have written the data to the file you know that you can go to the particular file location and check whether the data is been written into the file or not but how does Java know that right so now let’s write a Java program to read the data that you have written into the file again I’ll create a class called read from file and inside the main method I will write file my opj is equal to new file and this is the path of my file and then I’m using scanner and my reader by because I want to read it that is a reason and I’ll pass the parameter as my obj my obj refers to the file which is this one right and next while my reader do has next line so if it has next line or if there is n number of data that is being present in that it will read everything that is the reason I want to check whether it has a next line ifs again string data is equal to my reader. next line and it will print the data and after everything it says my reader. close because I have to close this and finally if the file has not found then it will throw an error and will be handled in the catch block simple now let’s run and check the output so you can see that it return Java is a prominent programming language of the Millennium which I had written from this thing right so from the right method and this I manually type so it will again print the data that has been present so this is how you need to read the data from the file I hope you understood how to create a file how to get the information from the file how to write to a file and how to read from a file so these are the various file operations that you can perform on a file so that’s how it works and that was all about the file operations what is a Java thread so guys a Java thread is a lightweight subprocess now in an application so we have one main thread so when our application is uh running so operating system is going to create one process so same way over here Java virtual machine will take care of your Java applications so process proc would be created and each and every process will have a main thread so thread is a lightweight subprocess so here it is the smallest independent unit of a program it contains a separate path of execution and every Java program will have at least one thread that is something known as the main thread so main is nothing it’s an execution context where the certain jobs will be executed one after the other in a sequence now if you want to create a thread in Java so we got this thread API from the java. Lang package itself you need not to even import it so it’s by default in the Lang package once we create a thread it will have a life cycle so how it’s going to work right so a thread can lie only in one of the shown States at any point of time so typically guys we’ll have a thread with a state called new so when you create a thread its state is New then we move into the runnable then into the running and finally the thread will be terminated in between a thread can have the waiting state which can uh iterate between your runnable and running so let us have a look onto uh individual states what exactly is what state so having a new state means that we are going to initiate a new object of a thread you can even say that the thread is just born right it’s just like creating an object of a thread in the memory thereafter once a thread is created we start the thread so once we start the thread the state is changed to the runnable state right so that it can run and finally your thread is now running so running means it is executing a run method which is the method we have to override from the thread class right and we even have the yield method that can send them to go back to the runable state again what is baiting State when a thread enters a state of inactivity so thread is uh not performing any action it is waiting for some other thread to give back the data or it is sleeping or it is blocked at certain scenario or a use case so that is known as a waiting State your thread is not currently resuming the tasks finally the thread is terminated so when your thread has completed its task right so it is terminated now let us take one example of this thread consider that you are going to play one audio file in a media player right so let’s say you have a media player and you’re going to play an audio file now the moment you tap on the button to play that audio in your phone or in your PC right so a new thread is created and you see that fin the thread starts proceeding so your song starts to play so from the runnable it enters into the running State and it keeps on running till the song is not finished right so that’s like the terminated so in between you just go for the pause right that’s like where your thread is now doing a weight operation so when your song is automatically finished or you stop the song that is the terminated state so one of one of the just an analogy that how the thread is going to work for us same way there can be a use case that you want to download some image from the server now threads are typically used when we have to perform a long running operation right so there we create this thread downloading an image can be a long running operation because it is dependent on the network speed now when you want to download an image so you create a new thread so in the background what we will do is we’ll start fetching the bytes from the server for the image right and uh in the running State your thread is continuously fetching the data there can be a state called waiting let’s say network connection has been disconnected so our thread can wait until the network connection is you know reestablished and terminated would be a state when the image is properly downloaded so couple of examples demonstrating how life cycle of the thread is supposed to be so now we will look into how we can create a thread so guys if you want to create create a thread right you need to understand the reason why you want to create a thread so we by default will have a main thread in our application that is represented by the main method so what is a main thread right so typically whenever you run your Java application or any application you will write your code in the main method now the code in the main method is executed as a main thread itself right so main method will have the instructions written within it and all those instructions are being executed as a part of the main thread in a sequence one after the other now what will happen if you are going to do a long running operation within the main itself it can take time right so the below written instructions in the main method they will be blocked because of a long running job right now that is where your operating system it will start giving messages to the user that this application is not responding would you like to wait or kill this application so this is what we need to understand right so when we have long running operations we need not to put the load on the main method or the main thread we need to create a separate thread so that is what we going to understand now so creating a thread is like what now we have two different ways by which we can create the thread either we extend from the thread or we can implement the runnable interface right so guys having a thread class so we’ll we’ll just say extends thread any class name extends thread you overwrite the run method you create the object of your thread class and we invoke the start method which will internally execute the run method same way so here you can see a bit of code snippet coming in so there can be a class called my thread extending the thread we have a run method which will do some job and in the main method you create the object of the thread and you just say start so start method will internally execute the run method the way we got thread class in a similar way we do have something known as runnable now many of times uh we are already into inheritance right so let’s say your class is inheriting some other class now it cannot inherit thread at the same time because multiple inheritance is not supported in Java so what we got we got runable interface so if you are already extending some class you cannot extend the thread class but we got a runnable interface which can be implemented rest of the structure Remains the Same right so you create you override the run method create the object of the class and invoke the start method so guys here we go right so your thread class will Implement runnable so let’s now do a little bit of coding here and understand that how it’s going to work for us right so I’m going to write a new Java project we’ll see how we can create threads using uh the thread API and the rable interface so I’m going to see threads demo let’s see next and say finish so we got a small Java project created here in the SRC I’m going to write a new class and I’m going to say threads with the main method or I will say this as app with the main method right so app means application Here app with the main method now when we have this uh main method coming in so guys uh we will come here and say that main method represents main thread right so main method represents main thread so whatever we write in here will be executed by main thread and threads always execute the jobs in a sequence so whatever the job you going to give to the thread they’re going to execute in a sequence for example I will write down one of the job it goes like application started and thereafter I can have a job called application finished so in between I can have let’s say a small job it will print some documents for me right so I’m going to say that for INT of let’s say document one till the document number 10 and document plus plus so I’m printing some documents right so let’s say this will be some code snippet right so some code to print the documents right so this guy is printing some documents ments for us so I will write down the ciso statement here so printing Document Plus the doc right so whatever the document we are printing so I’m just putting up here now when I will run this program it is all ceso statements it’s nothing complicated to understand I hope so so your application started we printed the document one till the document number 10 so we printing these 10 documents in a loop so you see everything is happening in a sequence so what I’m trying to say is that this goes like your job one consider this entire snippet as job two and this goes like let’s say some job three so we are not getting job three before the job two or job one after the job three so what is the output output is a sequential output right now that is what a thread is so what is a thread thread is an execution context so what does this mean this means that it’s going to execute your code in a sequence threads always execute code in a sequence right so one after the other so this is one of the demonstration regarding the main thread which is nothing represented by the main method now what I will do is I will write one class here now this class goes like some my task which extends not extends let’s say my task so my task is going to execute a task for me so this will execute a task for me here what I’m going to do is I’m going to say C so so even we’ll put up a loop here and this Loop goes like a similar Loop so printing the document number document right so here I’m going to put some different D limiter so that we can understand printing document number this from printer one right so this is from let’s say printer 2 and coming here I’m going to say this is your printer one so this is how we going to come up and understand so my task over here is having a method which is going to print the document but this guy will print the document from the printer tool and this guy over here is going to print the documents from the printer one so within the job one and job two I’m going to introduce this job called my task so my task is a new my task right and coming here I will say task. execute the task if you will see now what we have done we have made my task as job two and this guy has job three and this goes like job four now when I will run this code what you will find is that application started printing of documents started so printer 2 is in use and thereafter printer one is in use right so as per our discussion main is executing everything in a sequence and to your surprise you need to understand this point here that till this task is not completed below written jobs they are blocked I need to now mention this point till job two is not finished below written jobs are waiting and are not executed so this is something which we need to understand because of sequential operation here right so we are we are seeing a sequential operation so that is the reason till job two is not completed below mentioned instructions or the jobs they are waiting now in case job two is a long running operation right so in case job two is a long running operation consider this guy is going to print several documents right there can be some several documents which we are supposed to print now till these several documents are not printed right in case job to is a long running operation that is several documents are supposed to be printed right so this is a use case which so in such a use case os/ jvm shall give a message that application is not responding right or we will have some you can say Behavior some sluggish behavior in the apps now what is meant by this sluggish behavior in the app it means means that we will be able to see some kind of apps which are hanging right so you see that apps they are going to hang right so even I can say apps app seems to hang now why app will seem to hang because your main thread is blocked right so the only Point here is that your apps they might seem to hang they will have some sluggish behavior in case you are doing a long running operation within the main thread now this is the use case where we need a thread so I think the use case is clear right so what I’m going to do is so this my task you come up with this my task in the same way so let me comment down this code part so instead of having it a normal class you make it a thread you overwrite this run method with the public because run in the parent is public so you need to override it so this guy is is override it here for us right the run method so I get the same operation being performed but this goes in the run method and my task is now a thread right so I can very simply understand that my task is a threat because inheritance makes this relationship to come up as is a relationship right so my task is a trade so guys this is certainly clear to everyone I hope so so in the next part of this is like what now so you won’t say execute the task so rather we will come here and say task dot start so start method internally calls the run method right so start shall internally execute run method now let us reexecute the same code and see what is the outcome so we see a similar output here right but if you can observe application finish is coming somewhere in between previously it used to come in the end so I’ll give a rerun again now I see a different output right application started sometimes printer one is being used sometimes printer 2 is being used and there after lot of times printer two then sometimes printer one and then the app getting finished so again rerun this application you see again a different output so every time when you will execute your code over here what you will see is a different kind of an output right why now the outputs are mixed for us because along with the job three job two is executed parallely right what I can say now so now Main and my task are executing both parallely or con concurrently that is the reason you are able to see some a mixed output for both of these threads so guys when you write a thread thread’s going to work parall to your main thread right so now my task is also known as a child thread or sometimes the terminology can be a worker thread so child thread or overcut thread right so this guy is going to perform certain operation which will not affect the performance of the main method or the main thread right so we are having this main thread which is not supposed to be getting affected by the operation of my task because my task is executing separately main is executing separately within the same process of course so they are not interfering in a way that it has to be waiting for one guy that it should stop it should finish its execution then the main will resume so we are getting the things executed in a parallel operation now the same thread called my task can also be created so considering that you have a class called someca right and I’m just going to commment down this guy now so considering that we have this my task extending CA and thread both now this is not allowed in Java multiple inheritance is not supported right this is an error why because multiple inherit isn’t supported so what we will do so we’ll come here and we will say extend CA but don’t come up with the thread you can say implements runnable so that that’s just one basic change here rest everything Remains the Same so guys in case your class is already a child of some other class right so if you are already having this inheritance implemented so you won’t be able to write comma thread multiple inheritance isn’t supp in Java so you can anytime come up and say implements runnable coming here you are now going to do it in a different way right so let us see how we can create the object so you can say runnable R is a new of my task so you write a polymorphic statement the reference variable of the interface is pointing to the object which implements it then I will create a normal thread object I will say thread task is a new thread within which I’m going to pass this runnable reference and then I will say task. start so this is a bit of change when it comes to runnable versus your threads so you run this code here so it’s going to work in the same way for us right so it’s again a thread so printer one or printer two right so they are they are now the mix outputs mixed outputs they definitely show that our jobs are getting executed parall so main is not getting affected now right so that that is how we are able to understand this point so every time you will run this code you might end up in looking the different outputs why different outputs because execution of threads is not in our hands it is in the hands of jvm jvm can perform time slicing it can give some time to the main threat sometime to the my task right so that’s how we are able to understand and the threads in Java guys I hope you have understood it so now we shall be proceeding towards the next part so the next part over here is to differentiate between thread class and the runnable interface right so guys there is some common things and some dissimilarities so over here in thread and in runnable so a unique object is created for both of the cases right so memory consumption of course increases because we have a separate thread running in the same process then class extending the thread cannot extend any other class because of the multiple inheritance but here runnable helps us to perform this same uh use case so if you are already extending you can Implement a runable so thread class is extended only if there is a need of overriding the other methods of it so if you are actually inheriting the thread class so you might be looking forward to override its other method as well but in case you don’t want to do that runnable is the best use case right because runnable you can only have this run method which you can override then having thread we got tight coupling and runnable is loose coupling so of course guys when you have a loose coupling dependencies they gets reduced and is a better use case to use so moving ahead now so I hope tread versus runnable is is good to go we saw how to create a thread what is a thread and how it is helping the main thread to accomplish the jobs so what is this main thread once again main thread Revisited guys main thread is the important or the most important part of any application or a Java program so whenever you run your application your main thread is executed so every program will have this main thread and Java main thread is needed so that we can spawn the child threads we can create child threads we can start them you you have seen that we created my task we started the my task right so it must be the last thread to finish the execution that is the main thread stops the program terminations so it’s it’s going to terminate the program so when your main thread is finished so it is basically a termination of your application itself right so Java main thread guys how it’s going to work let’s see that part now so typically jvm is going to start the main thread and some other demon threads at the same time right so when you run your application the main thread and the demon threads they are started by the jvm your main thread can further start multiple child threads for example child thread a child thread B and the threads can further start the other threads for example thread a can start the thread C so if we talk about our example here so there can be my task there can be your task for an instance we can have uh some other guy called your task right so this guy is working on some printer three right so we we can have these multiple threads which can be spawned in the main method itself so here I can just say thread your task is a new thread in between I can pass a new of your task and then I can say your task. start right so it’s one the same story either you write this polymorphic statement or you directly pass the reference so these two uh instructions can also be you know written in a way of a new thread and in a new thread you pass a new of your task and then you simply say the start right so you can conclude it in a single statement in case you want if you don’t want to have the reference uh to the thread so these threads right so they can be multiple threads here and there so now we see multiple threads in action right so if you want you can have your threads in a lot of threads executed from the main thread itself even what what we can do is from uh these threads we can execute some other threads that is that is what we were trying to understand and one more thing any thread can be marked as a demon thread so you can just say task. set the demon as true right so what is this demon thread demon thread is a thread which is going to be executed by the jvm whenever the application starts right it’s going to initi it’s going to uh execute the thread along with the main thread if you see the image that is a bit about how the main thread is going to be execute so now next part is multi-threading in Java so typically multi-threading begins when you have more than one thread in your process so of course if along with the main thread a new thread is getting into execution that is a perfect example of multi-threading itself but what we are going to do is we are going to take up some use case that in case there are couple of threads or multiple threads other than the main thread so how they going to work and what can be the uh you know scenarios which we can observe when they are executed so what is multi-threading so guys multi-threading is the ability of a program to execute more than one threads concurrently where each thread is handling a different task at the same time right so that the available resources can be utilized in the most optimal manner so let’s say there’s a main thread and Main thread is going to start some child threads and there can some switching between these child threads right because they are going to perform the jobs and your time slicing will be coming into the action where some jobs of thread a will be finished some jobs of thread B some jobs of thread C right so there will be a switching between these execution of the threads so let us see one demonstration where multiple threads can be introduced so I’m going to write a new Java program so a new class so this goes like my uh let’s say sync app with the main method so this time I’m going to perform a separate uh operation right so consider that here your application started so this is your beginning of the main thread and this will be the ending of the main thread right so that is how we are considering so main is a thread now we understand it right so main is representing main thread all always remember this guys so in order to prove this what I can do is I can uh just try to say in I is 10/ by 0 right and I will run this code here as Java application so what you see is it says there’s an exception and the term which jvm is using is thread main at line number 11 if you see this line number 11 is divide by zero error that’s like arithmetic exception right so what I’m getting is is thread main right so jvm says main method as thread so that is one of the proof of concept what I’m trying to say that why main is representing the main thread right now there is a class called printer so printer is supposed to print the documents so I’ll have this guy called print documents right so printer is supposed to print the documents how many documents you want to print right so in begin let’s say int some number right so I’m just going to take some number here so I will say for INT isign one go till this number and say Plus+ so there there can be even more details in the print document but I’m just taking one of the examples here so I will say ciso printing Document Plus the I so we are going to have this document printing uh done for this IE I can even take one of the name right so I can take doc name and this can go like number of copies what is the name of the document which you want to print and how many number of copies you want so I’ll take this number of copies goes less than equal to number of copies right and printing instead of the document I’m just going to have this document name so I think this is one of the use cases which I wanted yeah now having a printer object so I’m going to write a printer object printer printer is a new printer this is one of the printer object and if I want to print the documents right so what I will do is I will say dear printer please print me the documents I want uh 10 copies for a document called ishan’s profile.pdf so I want I want the 10 documents for ishan’s profile.pdf so when I will run this code here so you see your printer is printing uh the copies so it has clearly said 1 to 10 right now why we should be getting the documents printed here in the main in the main method in the main thread we can have a separate thread right so I’m going to write a separate thread So This Thread goes like uh let’s see my thread which extends thread and I’m going to override this run method always remember guys you can any time have your runnable interface or this thread whatever the way you are comfortable right so here in the my thread I’m going to have this guy called printer PF I’m going to have a reference to the printer in the Constructor so I will take printer P here and I will say PF is p so in the run method here I will say PF do print the document so I need 10 copies so this is like John’s profile or let’s say John’s profile is the name so now so once I created uh the printer object I’ll create the object of my thread so I will say my thread MF is a new my thread and I’m passing the printer over here you see we have one object of printer right how many objects of printer I have created so we have only one single object of printer right only one single object of printer so we are giving the reference so my thread is having reference to the printer object so since my thread is having reference to the printer object so printer is copied to the p p is copied to the p and you are doing a print documents here so I will say MF dot start now what will be the benefit the benefit is that printing is happening in a separate thread that’s like my thread so now when you run this code you see application started application finished so main thread is okay to go with it right and the jobs are getting executed for uh John’s profile by my thread now consider along with the my thread you see you you got this my thread I’m going to write your thread which is very much same all right it’s it’s it’s exactly the same story so instead of John’s profile this is fana’s profile which we want to print right so uh the way we got my thread in a similar way I’m going to say your thread let’s say VF is a new of your thread so it’s going to work on the same printer so you see my thread is having a reference to the printer object your thread is also having reference to the printer object but guys what is the use case or the scenario scenario is that we have multiple threads working on the same printer object now this is a very difficult use case so you see printer is now going to be shared between two threads if I start both the thre threads now so I say yf. start as well right so you see what’s going to happen so we are getting the documents printed so you will run this code so any time of any point of time what you will see is that the outputs they going to get mixed up for us right so let me just keep on running this part here so you see the outputs they are getting mixed up now so 1 to n for the John then 1 to 10 and then the John profile so it it’s totally you see the output coming here now right it’s all mixed up can you imagine such a scenario in a real time envirment so let’s say two people they want to print the documents in the printer can you uh imagine printer printing document one from the first fellow and then the document two and then document three then four so it’s all mixed up right so rather what printer will do printer will take the commands from the multiple people multiple computers but it will print one after the other so this is one of the use cases which is not good to go guys right so this is this is certainly not what we want so what is this this is known as asynchronization threads are running parallely now there can be a use case there can be a scenario where multiple threads so if multiple threads are going to to work on the same single object we must so we must synchronize them so they are not they are not supposed to be executed in the sequence so what I’ll do is I’ll introduce one more uh method here in this for Loop here so I will say a thread dot sleep for let’s say 500 what is this thread dot Ste guys Sleep Method will temporarily pause the execution all right so I’m going to select this guy and say surround with tri catch because Sleep Method will throw an exception now when I run this program here so what do you see is along with some delay the output is coming up for us right so let me run this code once again but this output is not at all acceptable since my thread and your thread are working parall on the same object so it is printing the documents sometime s for my thread sometime for your thread which is not a real life use case this is implemented something in a wrong manner right so what I can do is immediately after the start method I can say mf. join so what does this join method is going to do so it will again throw an error so we’ll surround it with the TR catch block so now what you will observe is synchronization coming into the action let me run this code what you see is after putting the join all the documents are printed from the my thread and then it is your threat in execution let me re-execute the program for you people so guys you see your John’s profile till John’s profile or John’s papers are not finished Fiona’s paper were not started that is what we are able to understand as synchronization that is by having this join method coming into the action so if you have many people who are going to you know uh get this printer utilized you cannot put
join on each and every uh you see method call on on every thread so what I can do is I can come here and I can just mark my method to go as synchronized so what is synchronized method now so when your thread is going to execute this method called print documents it will acquire a lock we call it an intrinsic lock right now once the lock is acquired no other thread can access the print documents so rather than having the join function call what I’m doing is I’m marking My Method as synchronized so if multiple threads are going to access the same method again and again so what we are going to do is we are going to synchronize them then and now when I will run the code what you see is the same output coming in for us right what is the benefit here the benefit is now we need not to put join method calls on each and every thread right so we got this synchronized uh method itself we can come here in our thread we can say a synchronized block instead so synchronized method was acquiring the lock on the method right so no other thread can access it if one thread has acquired the lock so this is acquiring the lock as a block now no thread can execute or access the printer object till this block is not finished right so this synchronized block has to go in your threads so there are two different ways by which we can Implement synchronization using the synchronized keyword so the output will again remain the same for us now where is is synchronization needed in multi-threading we need synchronization in multi-threading when both the threads or multiple threads they are working on the same single object now that is the use case where you need to implement synchronization so guys I hope this is clear to everyone what is the synchronized keyword so now let us come back so guys the way we have synchronization in a similar way we have some something known as a thread pool right so thread pool will manage the pool of worker threads and contains a queue that keep the tasks waiting to get executed so there there will be a Que Now we will have lot of tasks right for the application which we have to do and a pool can be maintained for these threads which will be executed automatically by this API called thread pool so explore this part so what are the various thread math guys so in order to create the threads we got a thread object and then say start right so we can join the thread there’s something known as a thread do sleeve there can even be an interthread communication so guys we have wait and notify as methods and a thread can be marked as a demon thread you just say set demon as to what’s a demon thread it’s going to get executed along with the main right so when the jvm is going to start the app it’s going to start the main as well as the demon threads let’s understand what are regular Expressions a regular expression is a sequence of characters that constructs a search pattern when you search for a data in the text you can use the search pattern in order to describe what you are looking for so for example you have a regular expression like this as shown in the slide and you can see that the cap rep represents the start of the line and a set which is enclosed within the square brackets represents letters numbers underscore hyphen everything it compris of all the alphabets numericals and special characters as well and also if you want to write a regular expression which is of 3 to 15 characters long then you can enclose it within the curly braces as shown here and the dollar symbol implies the end of the line so this is the basic regular expression where where you can understand how you have to start writing a regular expression and how you can include the alphabets the patterns everything within the square brackets and how to represent the length of the characters in flower braces and finally the end of the line right so a regular expression can be a single character or a more complicated pattern it can be used for any type of text search and text replay of operations a regex character can be simple ABC or it can be a combination of simple and special characters like AB into C or it can be example with braces which includes a d star D plus anything so I hope you understood how actually it looks like now with this let’s understand what is Java regex so a Java regx is an API which is used to define a pattern for searching or manipulating ating the strings it is widely used to define the constraint on strings such as password and email validation so you can see in this below GIF over here that it is trying to search for a regx that is a regular expression and it’s trying to figure out whether it is able to match the pattern or not so there are different methods of using Java regex so let’s move ahead and look at the different categories of regular Expressions the first on the list is matcher class this class is used to perform the match operations on a character sequence so this is used to match a character sequence so it compris of various methods the first one is Boolean matches this is used to test whether the given regular expression matches or not next Boolean find this method is used to find the next expression that matches the pattern so once you get the matches the then it will go ahead and find the next expression which will be able to match the pattern or not if not it stops there and then it will again go ahead and find the next one next Boolean find in start so here I’m passing the parameter called inst start and by doing this it will help to search the next expression from the given start number so you have one more method called string group again this is used to return return the math matched sequence so when you get the proper match sequence by using the Boolean mattress and Boolean find then you have to return the match sequence in order to do that you need to write the string group method next in start this method is used to return the starting index of the regular expression and similarly int end is used to return the ending index of the regular expression and you have the group count which is used to return the total number of the math sequence so these are the methods of match class now let’s move ahead and have a look at the various methods of pattern class pattern class is a compiled version of regular expression which is used to define the pattern for a regex engine so again this also compris of various methods first static pattern compile and here I’m passing the parameter as string regex okay this method will come file the given regex and Returns the instance of a pattern I will tell you how exactly all these methods work with the help of an example after this for now let’s understand all the different methods next you have a matcher match which compris of a parameter called car sequence input so this is used to create a matcher that matches the given input with the pattern and the matcher is the one which is the previous one which comprise of a Boolean find buan search in start end and everything and this matcher is used to create a matcher that matches the given input with the pattern so suppose say you have a pattern that comprise of a special characters along with the numericals and alphabets so what it will do it will try to match the given input with the pattern so for that reason you need to use this method next method is static Boolean matches string regex so this works as a combination of compile and match methods next you have string split this is used to split the given string around the matches of a given pattern so after that you have a method called string pattern and this is used to return return the regular expression pattern now let’s see a small example of how exactly it works so here I have an example in this I’m going to check both categories that is match and pattern as well so first what I’ll do I’ll just import the package for regex and then I’m creating a class called regex example and inside the main method I’m giving the pattern as pattern. compile Dot and Dot that is a starting index and the ending index so it implies I can use anything as a starting index and I can use anything as a index but the thing is it should comprise these x and x and between so for that I will use the matcher which is used to match the given pattern right so inside this matcher I’ll write a and b so what it will do it will match the given pattern so this is the pattern and this is the matcher I’m using both the classes that is the matcher and the pattern so I will check whether the given pattern will match the given input string or not and if the string matches the given reg X then it will say match do matches and it will display the output so now let’s run and check for the output okay so it’s telling string matches the given reg X and as I already told you it will always display the Boolean result that is true or false so it is telling true so now even if I give something like this so what do you think will be the output let’s run and check for it so you can see again it’s telling string mat as a regx pattern but then if I remove One X from here and then I write X over here so it does not match the given pattern right so obviously it will say as false so you can see here it’s telling false right so I hope you understood how to write the pattern and how to write the matcher for the given pattern and remember remember one thing it always displays the output in the form of a Boolean that is either true or false so what happened here in this case internally it uses pattern and mature Java regx classes to do the processing but obviously this reduces the code lines and pattern class also contains the mature method that takes the regx and input string as argument and Returns the Boolean result after matching them so this code works fine for matching the input string with a regular expression in Java so that’s exactly how it works now let’s move further and see the next category that is regex character class so again even this comprise of various methods like AB C so it compris of ABC which implies a simple class that compris of a b or c next negation of ABC this comprise of any character except a b or c that is a negation next you have a to z and capital A to Z which impres a range that includes small A to Z and capital letters from A to Z next it has a through D or M through P that is a union that is a through D or M to p and next you have d e or F which is a Intersection For A to Z and next you have a through z except for B and C that is is AD to Z that is a substraction but you have to negate B and C okay and the last one is a through z and not M through P so these are the various categories of a character class let’s again take a small example and understand whether this works fine or not so now let’s check how this works so again inside the main method I’m using a pattern do mat method to check whether the given set of characters matches with the given pattern or not so first it compris of X Y and Z so you can see here all the character set comprise of the simple class that is ABC that is XY Z so when I pass WB c d it will obviously written false because it is not among X or Y or Zed and now if I just pass X it returns to Y because inside this class it comprises of X Y or Zed right and again if I try to pass double x 5 Y and 1 that it returns false because X and Y comes more than once so that’s the reason it will return false now let’s run and check for the output so as I have already told you it returns false true and false so this is the given character class right right and if I try to match the pattern that is out of the character class then it will obviously return false so this is how you can write an example for character class and check whether the given set matches with the input pattern or not now let’s move ahead and understand what are regx quantifiers the quantifi specify the number of occurrences of a character so again even this compris of various methods for example X followed by a question mark it implies X occurs either once or not at all then you have X+ which implies X occurs more than one time and x with a star that is a multiplication symbol implies X occurs zero or more times and if you have a x followed by an N within the curly braces it implies X occurs n times only and if you have a n with a comma then it implies X occurs n or more times and and if you have a parameter like y comma Z then it implies X occurs at least Y times but less than Z times so these are the various methods of regx quantifiers and let’s see even how this works so inside the main method I’m simply printing this thing that is quantifier and now I will try to check whether the pattern matches or not this symbol in the quantifier implies it should occur either one or it should not occur at all right so when I say A Y and Zed followed by a question mark and inside that if I just pass a parameter a it will say true which implies a occurs only one time next in the same category if I write a three times it says false because a comes more than one time so as I’ve already told the symbol implies I either once or not at all again in the same category of class if I write this it will again say false because all these alphabets comes more than one time so that’s the reason again even for this case which says a m n t it is false because m n t is not under this category and a comes twice that is the reason and this should be true because a y set again does a y set as well okay next plus gtif fire implies what it should occur more than one time so a y z plus implies it should occur more than one time so it says true because a comes once even if I write 3 a again it says true because a comes more than one time and even if I write this pattern again it says true because it comes more than one time and even if I write this it says false because mmt is not a matching pattern okay that is M and T are not a matching pattern so this implies it should OCC either zero or more number of times right so when I give this pattern followed by a star which implies and if I write the matcher this it says yes because a y and Zed occur either zero or more number of times so let’s execute and check the output so you can see here the results with respect to the above correct so as I’ve already mentioned you quantifier works with Star Plus and question mark it implies either it should come one time or it should come zero or more than one time or it should occur more than one time so depending on the type of the quantifier you can give your matcher and it will check whether the given pattern matches with the quantifier or not so this is how it works so the last category on the list is regex meta characters so the regular expression meta characters work as short codes so dot implies it can be any character D implies digit capital D implies non-digit s represents any white space and capital s represents non-white space character W can be a word character and caps W can be a non-word character B can represent a bound boundary and capital B represents a nonword boundary so out of all this you can understand that it just represents what a short code right so let’s also check an example of how exactly this works so inside the main method I have written metac characters D so d means digit right so in D if I give ABC it will say false again and in D if I give one it says true why because digit comes only once and in the same day if I give triple four and three it says false because digit comes more than once and inside the D if I give a combination of digit and a character again it says false right so now in case of meta characters capital D so if I give a meta character capital D and if I try to write a alphabet that is a character it says false because capital d means a non-digit but it comes more than once so if I give in the capital D as just one it says false again because it is a digit again the same thing goes with here as well because these are the digits so in this Capital matter character D if I give a match M it is true because it is a non-digit and it comes only once so a meta characters D with the quantifier so if I give D and followed by a star and if I pass ABC then it says true because it is a non-digit and it can occur zero or more number of times so in these cases what happened I just use a single meta character and I tried to pass a string so that was the reason it was telling false now if I give this it obviously says true because it is a non-digit and also it can occur more number of times so here only if I give D+ so it will say true only so this is how it actually works so that was all about the meta characters now let’s move further and see a small demo where I will tell you how to find the given pattern out of the string and also I will explain you how to verify the email validation okay so I have an example over here this is used to find a given regex pattern and it will also check whether the given string match is with our given pattern or not so I have a class called demo and inside the main method I’m using scanner SC is equal to new scanner of system.in I am using a scanner class because I want to read the input from the user so first what I’m saying inside the Y Loop I’m telling enter the regex pattern and I have to obviously use this because I want to scan for the next line if there is anything as such then I’m using a patterns pattern class to compile the given regx pattern that is is the user input pattern and then I will use the matcher class to match whether the given input string will fall under this given matcher or not if not it will say match not found if it will find the pattern with the help of a matcher doind it will say found the text whatever is entered by the user at the starting index of what is the start of the index the matcher group is used to return the Matched Patterns group and the ending index and finally it will retrieve the matcher do end means the ending point so it will say found the text at the group starting at the index the location where it started and the location where it ended if it is not found then it will say matcher is not found so let’s execute and check for the output so it’s asking me to enter the regex pattern so what I have to enter either I have to enter a part of it or I can enter the full thing so I’ll will do one thing I’ll just type YouTube channel right so you can see it is telling found the text YouTube channel the one which I entered starting at index 19 and ending at index 34 so now check 1 2 3 4 5 6 7 8 8 9 10 11 12 13 14 15 16 17 18 19 so it is starting at the index 19 and it ends at index 34 which is this thing right so again if I enter the pattern edura and I’ll keep it as small it says match not found even the cas sensitivity also matters no matter you give the same string again the K sensitivity also matters a lot so if I give welcome it says it is starting at the index zero because this is zero and it ends at the index 7 correct so this is how you can match the pattern with the given input string so this is all about the Searcher and the finder now let’s see a small example of email validator so I have created two classes here one for email validator and the other one is for the testing of a email validator so in this regard I’m performing a email validator test that is unit testing so inside the email validator I need two classes one is a pattern and the other one is a matcher so the email pattern that I’m going to give compris of all this that is this is the starting index as I already told you and this is the ending Index right so it should comprise of all these things plus these things and there should be a add symbol because it’s an an email address followed by again a digits and small and capital letters and again the same thing and it can also comprise of more number of digits and finally it has the ending pattern right so inside the email validator I’ll try to match with the given email pattern and I have a Boolean validate final string hex so this is used to match the hex of the given parameter and finally it Returns the matcher and now I have the email validator testing so here I’m using data provider to provide the data and this will be the unit test case which I will be running as a testng test so if you wish to know more about what is test NG how exactly it works what is unit testing you can check out the videos on our YouTube playlist and you will get Hands-On on even those topics as well so now you have a public class email validator test yeah I’m going to create a object of a new email validator and using the data provider I’m providing the valid email address that compris of a string followed by a add symbol and then it comprise of the domain followed by a particular domain it can be net it can be doom. go anything right which implies it has to comprise of this followed by at if it is Gmail so it has to compile Gmail dot again com com test anything so these are the email address which is valid and I again have a invalid email address so you can see if I simply give us Eda it is not a valid email address right so the email address should comprise of this pattern if not it is a invalid email address again here Eda followed by a do and gmail.com again it is a invalid so again you can see after a gmail.com again it compris of something that is also a nonvalid email address comprise of star percentage so many things right so these are not a valid email address so what I’m doing I’m using ADD test annotation to test the valid email address so here what I’m doing I’m passing the valid email provider so what happens is it will check both the valid and invalid email address and it will display the output so the data provider is used to provide the set of the data and from there you can validate the email address so I’m writing two test one for valid email provider and the other one for invalid email provider so whatever is present in this I’m sending it to a variable Temp and then I’m validating that and finally I’m checking if the result is true then I’m using assert equals to true and if the result is false I’m giving assert is equal to false so let’s check the output so I’m going to run it as a test NG test and let’s check for the output so you can see here first the valid email addresses till here right so these are the email addresses which are valid and that’s true and now talking about the invalid email addresses it starts from here and it is false why because that’s not true that’s reason it is false and it will also return the string for valid email test and the invalid email test so both on the default test and suit the test that was executed was to and there were no failures because whatever I have written the code was working perfectly fine and that’s a reason so even if I have to check the result of running class email validator test you can check all these the tests that was run was two one is valid and one was invalid and this is the class name which is followed by a package on both default suit and test the test was run Within These many seconds yes so this is how you need to validate the given email address and check whether it is invalid or invalid that’s exactly how it works and I hope you got a brief idea about what is regular expression how you write a regular expression what are the different categories of regular expressions and how to configure your program and check whether the given regular expression or a pattern matches with the given input string or not and how to validate a email address as well let me tell you what is socket programming in Java so Java socket programming is used for communication between the applications that is running on different Java runtime environment it can be either connection oriented or connectionless so basically socket and server socket classes are used for connection oriented socket programming I also told you that it also has a connectionless programming and that is achieved with the help of a datagram socket and datagram packet so basically the client in the socket programming must have two information one the IP address of the server and the other one the port number so in order to connect to a server from the client and if the client wants to send a request to the server then it should know the IP address of the network and the port number which the server is operating on so this is all about the brief of the socket programming now let’s move further and understand what is a socket a socket is one endpoint of a two-way communication link between the two programs that is running on the network the socket is bound to be a port number number so that the TCP layer can identify the application that data is destined to be sent so basically a connection will always happen between the server and the client port and obviously when a client sends a request server has to wait for the client request then the server has to accept the request and then establish a connection with the client and processes the request and send the response back to the client so this is what it does and for all these things what you need you need a socket which is an endpoint for a two-way communication between the two networks or the two programs that is running on the same network so I hope you understood this now let’s move further and see some of the methods of socket and socket server classes the first method for socket class is public input stream get input Stream So this method will Returns the input stream that is attached with this particular socket next output stream and this method will return the output stream that is attached with the soof and next you have public synchronized vo close if you use this particular method it will just close the socket that is a connection the next one is Socket server this will return the socket and establish a connection between the client and server because as it is a socket of the server end it will obviously have to return the socket and establish the connection because that is what it is doing right when a client send the request and if the server will not accept the request then there won’t be any connection between them so that’s what what a public socket accept does and after that you have one more that is public synchronized void close and this will obviously close a server so these are few methods of socket and socket server classes having understood this now let’s move further and understand the client side programming so what do you think a client side programming and a server side programming as so basically when a client wants to connect to a server or if a client has a request at a server should accept and a server wants to send back the response then what happens you need to First write a client program for which you need to send a request to the server and you have to write a server s side programming so that your client will get the response back from the server by accepting the request so that’s why we need the client and the server s side programming and this is achieved with the help of a socket which will help you to connect between a network and which will act as a Interlink to to help you to connect to a network between the client side and the server side to connect to one another machine we need a socket connection as I have already told you a socket connection means the two machines will have the information about each other’s Network location that is the IP address and the TCP port and the java.net docket class represent a class so in order to open the socket what you need to do you need to create a object of a new socket and pass the IP address and the port number okay so that’s how you need to First establish a socket connection using java. net. socket and provide the IP address and the DCP port number and after that you need to communicate over a socket connection and the streams are used to both input and output the data so that’s what is communication with the client where you use the streams to input and output the data and after that you have to close the connection by using public synchronized void close simple so this is all about the client side programming and now I’ll also tell you what is serers side programming and then we will see a demo how to establish a connection and how the client sends a request and how the server accepts a request and how it responds back everything before that I will explain you what a serers side programming so after you close the connection using the client the socket connection is automatically closed explicitly once the message to server is sent and now the first thing is I have to establish a socket connection and write a server application you need two sockets a server socket will wait for the client request when a client makes a new socket and a plain old circuit is used for communication with the client and after that you have to output and communicate with the client through socket so you will use the get output stream method after finishing everything it is important to close the connection by closing the socket as well as all the input and output streams now let’s take an example and understand it’s working so here I have two programs that is the client and the server so first I’ll tell you about the client I have imported the package that is import java.net dostar because I want a network connection that is the reason I’m importing that and after that I’m importing the java.io dostar because I want the input and output streams that is a reason so first what I will do I’ll initialize a socket I’ll initialize the input stream and the output data stream so for that what I’m doing I’m just writing it as private socket soet is equal to null I’m initializing all the variables to null because I want to use it in the later part and after that I’m creating a Constructor for this class that is client and I’m passing the address and the port number that is the IP address and the port number and now what is the first step I have to establish a connection so in order to establish a connection what I’ll do I’ll give socket I’ll create object of a new socket and pass parameters and the arguments as address and port and as soon as it does that I have to print connected and now for that I need to take the input from the terminal so for that what I’ll do I’ll give new input data stream is equal to system.in and after that out is equal to it has to send the output to the socket so that is the reason I’ll use this so any exception then it has to handle and after that I need a string to read the message from the input tab that is the reason I’m using it in this way and one more important thing over here it keeps on reading unless and until over is displayed on the screen so I can write as many number of lines as possible unless and until this over will be displayed on the console so inside that I’m getting line is equal to input. read line and I’m outputting that again after that I’m sending the request I am establishing the connection I’m communicating with the server finally I have to close the connection so I have to explicitly close all these connection that is the input data stream the socket and the output data stream so these are the variables for that and I’m closing all these connection and finally inside the main method I’m just giving the IP address and the port number so this is all about the client but before the client has to say connected I need a server program which has to wait for the client to get connected right so let’s now see about the server program again the same thing but here instead of the output data stream I will get the server socket because I told this is a server site program and I need a server socket for this that is the reason I’m using this and then I am creating a Constructor of this and passing the variable as in Port so I’ll create an object of a new server socket and pass the variable as port and I’ll say server has started waiting for the client then client get connected when I go back and connect the client by passing the address and the port number server says client accepted so after that what I’m doing I’m writing the string unless and until until the over will be displayed so this line will take the input from the get input stream okay and it will read the string line from that and after that I have given input because I need to do input. read line and out. WR UDF so here what I’ll do inside the triy block it will say read the input that is given by the client and then display that after that again I have to close the connection and create an object of a new server with the port number here I’m passing everything here just I’ll give the port number because client is connected to a port and server is connected with both IP address and the port number so that’s how I’m writing this first I’ll execute this server and then it will wait for a client and then I will execute the client and it will say connected and then I’ll start writing anything then server will say client accepted and it displays the request that client has sent and it will rever back the response to the client I hope you understood this now let me first run server so you can do the same execution by opening your command prompt or your terminal but as I’m using eclipse and I have a inbuilt option to execute it like this so I’m doing it on my Eclipse itself so it is telling server started and waiting for the client now what I’ll do I’ll execute the client so run as Java application so it’s telling client accepted so there are basically two consoles it’s telling connected and it is asking me to type whatever I want I’ll go on typing even though I wrote so much it still did not display overr right so it has the ability to enter as many number of lines and you can send as many number of requests that you want to the server right so now when I check the server it’s telling client accepted it’s displaying what all I wrote It’s displaying like hi everyone I will welcome to tra YouTube channel I hope you’re understanding the socket programming in Java and so many things right so yes you just saw first the server started it’s telling waiting for a client and then when I connected with the client it told connected and it just took the string arguments from whatever I was passing from here right and then the server told client accept it and it displayed whatever request I’m just going on typing over there again if I write something else also it will again display in the server screen I’ll just say enter and you can just see that on the server screen right so that’s how it basically works and it will get connected to your client it will send back the response and it will display all the client request and respond back so that’s all about the client and server side programming using sockets in Java so this is how you can actually establish a connection using the socket because it’s Interlink between the two programs that is running on the same network right who is a Java developer Java developer is a computer software developer a programmer who integrates Java programming language into the development of mobile and Computer Applications web development and other sorts of requirements needed at both client and server end now with this let us move on to our next topic which is how to become a Java developer to become a Java developer there are basically three stages in the first stage you have to earn a college degree the first stage requires you to complete a qualification in computer science with a focus on software development this could be any degree related to computer science and information technology or you can either choose Bachelor of engineering or Bachelor of technology in the field of computer science or information technology in the next stage you need to get certified with Java the second stage requires you to complete an online or an offline course specializing in core and advanced Java trying out online examples is a good way to develop your specialization in Java and in the third stage you need to get experienced the third stage needs you to look for a placement or an internship program while studying this will provide you with relevant experience as well as guidance and mentorship from experienced software developers and finally you become an experienced and professional Java developer with this let let us move on to our next topic which deals with the Java developer skills overview when you Google for the skills required to become a Java developer you have a lot of skills showing up now we shall categorize the skills required for Java developers into two variants firstly the Java developer skills Technical and later the soft skills of a Java developer firstly the technical skills the technical skills required for a Java developer are he must be well known with core Java the core Java includes objectoriented programming techniques as well as the design patterns in Java abstract classes in Java interface and serialization followed by that we have om omm stands for object relational mapping so in this skill you need to be well vered with hybernate Java persistence API Eclipse link open jpa and after that you have the Java build tools Java build tools are the most crucial skills required by every Java developer some of the most important build tools are maven and gradal followed by that we have web Technologies a Java developer should be well ver with CSS HTML jQuery and JavaScript followed by that he or she must be exposed to Java web Frameworks like MVC play Java server faces and next to the Java web Frameworks we have application containers the most trending application containers are jbos JY web spere and web logic and next we have Java testing tools test NG junit and selenium are the most trending top testing tools for Java and later we have big data the Java developers must be well vered with dbms Hadoop SQL and jdbc next we have Java e components the most important Java e components are servlets Java beans Java server pages and finally the code Version Control which is GitHub don’t worry we shall discuss each and every one of them in detail for a better understanding in our next topic which happens to be the skills required for for a Java developer firstly we shall discuss core Java the most basic and essential skills required to become a Java developer is the co Java Co Java skills are the building blocks of every successful Java developer The crucial Co Java skills that most recruiters are looking for are firstly the objectoriented programming skills object-oriented programming approach introduces class and object style of coding that deals with the concept of inheritance encapsulation abstraction polymorphism the main Moto of object-oriented programming is to bind the data with the functions together and improve the code stability and safety followed by that we have design patterns design patterns in Java are the standard Solutions followed to solve routine problems faced in software designing life cycle every design pattern acts as a blueprint that allows customization to solve any given design problem in any code during the development of software modules followed by Design patterns we have abstract classes in Java abstract classes in java help the developers to achieve abstraction abstraction in object-oriented programming reduces code complexity by showing the relevant details of the objects used in the program and enhances code readability followed by abstract classes in Java we have inheritance Java inheritance is an advanced level of achieving abstraction in Java programming language the interface in Java enables a better and efficient way of achieving abstraction followed by this we have serialization serialization in Java is a concept that deals with a conversion of objects into a bite stream and transport the Java objects from one Java virtual machine to another and recreate them to the original form serialization enables developers to meet various factors in real-time programming with this let us move on to the next stage where we shall discuss about the Java build tools depending on the task assigned developers need to use a specific tool for every particular task for a Java developer understanding the terminology of build Tools in Java comes handy as Java build tools are the programs that automate the creation of executable applications build tools that one must know are Maven and Gradle followed by this we shall discuss the web Technologies web Technologies provide a simplified and faster way to create Dynamic web content having a better grip on web technology is important as it helps to understand the technique of establishing communication between multiple computer systems via markup languages it gives a way to interact with host for the information like websites and it involves HTML jQuery and CSS at the most followed by this we shall discuss Java web Frameworks to build a mobile application with best features and limited code Java web Frameworks are the best-in-class solutions they support the development of web applications including web services web resources and web abis in a standard way to build and deploy web applications on worldwide web some of the best-in-class Frameworks are spring MVC and play followed by this we shall discuss Java application containers Java application container is an application program in which the software building blocks known as the compartment can be run application containers are designed to provide multiple functionalities such as to provide user authentication logging or establishing a connection with the database topnotch application containers are JBoss and jti with this let us move on to the next stage where we shall discuss the Java testing tools Java Tes with an interface where you don’t have to actually launch your application onto a web browser this support multiple test activities from planning requirements creating a buildt test execution defect logging and test analysis some of the major testing tools that a Java developer should be well versed with are selenium and test NG with this let us move on to our next topic which is Big Data big data has become a trillion dollar industry and hand handling such a huge amount of data has become close to Impossible by traditional data processing software learning Big Data technologies will help the developers to analyze and extract information from complex data sets some of the powerful Big Data Technologies are Hadoop and Spark now with this let us move on to the next topic for our discussion which is Java e components Java e components or Enterprise components the Java Enterprise components enable developers to write server site applications one of the most most common challenges that an Enterprise developer faces is to how to handle requests coming from web-based clients to ease this challenge Java Enterprise provides the Java serlet and Java server pages apis that enable methods for logging activities using cookies on a uses browser and simplify these kind of issues and provide the best solution some major Java Enterprise components are cets Java beans and Java server pages with this let us move on to the next topic which is code Version Control control code Version Control allows developers to keep track of their work and helps easily to explore any changes they made in their data coding scripts comments Etc that is much smoother and easier to implement with this let us discuss the second stage of java developer skills which are the soft skills soft skills are people skills communication skills character and social intelligence among others soft skills enable people to navigate their environment work well with others perform well and achieve their goals now the first soft skill that we will discuss today is the communication skill good communication skills include active listening where you have to pay close attention to the person who is speaking to you and try adapting your communication style to your audience and convey your message in a better manner followed by this the next one is open to learning knowledge is never ending successful Java developers should always be open to learning new upgrades in the technology and keep themselves updated the next one is teamwork teamwork is a collaborative effort of a team to achieve common goal and to complete a task in the most efficient and effective way the next one is work ethics work ethic is a belief that hard work and dedication have a moral benefit and an inherit ability virtue or value to strengthen character and individual abilities the next one is interpersonal skills interpersonal skills are the qualities and behavior of a person used to interact with others properly the better the interpersonal skills the better the growth in man’s career now with this let us discuss the last part of this session which is salary details of a Java developer Java programming language is one of the most demanded ones in the it Industries let us now discuss the salaries offered to Java developers as you can see for a beginner the salary package lies between 3 to 8 lakhs per anom and similarly for an experienced candidate 8 to 13 lakhs perom and the maximum salary offered to a Java developer who is experienced for more than 8 years approximately 28 lakhs perom or greater than that as well the projects that I will be discussing today are ATM machine which is based on core Java Concepts text editor that is based on swings and applets and the signup form which will make use of servlets and JSP Concepts without wasting any further time let’s get started First ATM machine all of you know what is ATM and how it works but implementing the same using cach our Concepts is something interesting so let’s see how to do that here we will be developing the code for user account details bank account and then further we will perform few operations like deposit the amount withdraw check the balance Etc basically it’s based on code Java Concepts and it’s developed using Eclipse so all that you require is your Java install that is your jdk and JRE and you just need to have Eclipse installed on your machine let me tell you one important thing that is I have set the Privileges for account number and password that is you can see on the screen that I have given two account numbers and passwords while running the code if you give the account number and password as mentioned on the screen only then you can do the further operations else it will just display a message saying wrong account number or pin now let let’s see how it works and how the code is being developed so basically when you run the code this is how your console appears and it asks me to enter the account number that will be the one which I mentioned on the screen and the password is going to be this thing enter so when you enter this it will ask you to select the account you want to access that is whether your checking account your saving account Etc so first I will say type f that is checking account so in the checking account the operations that you can do is you can whff the balance you can withdraw funds you can deposit the funds so let’s see how much balance is there in my account it’s zero is it now I want to deposit the funds in the checking account so how will I do that again checking account option three which is deposit funds so it’s asking me amount you want to deposit from checking account so I say I want to deposit some 10,000 enter so you can see here the new checking account balance is 10,000 correct again I will choose checking account and now I want to withdraw the amount from the checking account so I’ll say option two and I’ll say I want some 5,000 from that account so you can see here I withdrawn 5,000 and the new checking account balance will be 5,000 so this implies I withdrawn 5,000 from the account again I will choose option one I will view the balance so it says 5,000 is remaining correct now we’ll go to savings account and again view the balance and do the same operations balance is zero again same thing I want to withdraw some funds like say 4,000 it says 4,000 and now I want to withdraw some funds say some 5,000 let’s see what it says when the amount that we want to withdraw is more than the amount which is in the bank account it says balance cannot be negative correct so when you try to access more amount than which is there in the bank account like the savings account it says balance cannot be negative similarly you cannot just enter the negative values into this now say I want to just withdraw some 2,000 and it says the new saving account balance will be 2,000 so basically this is how you can do operations like same way you do it on your ATM machines and now I want to just say I want to exit so suppose if I enter invalid account number say I’ll enter something like this and I’ll give the pin something it says wrong customer number or pin number that is I have set the Privileges only for those two account credentials so that I can access using only those two numbers you can even include more account numbers and pin I’ll show you how to do that so basically this is all about the working of ATM machine let’s take a look at the code now so here in edura one package I have created three Java files one is for account one is ATM and one is option menu so now let’s see why we have three files for ATM and how it works first we’ll see option menu so you can see here option menu extend account class that is this Java class I’m just reading a money format that will be in decimal and then I’m creating a hashmap of integer and then I’m creating a variable of type hash map and giving a reference for that so basically the first thing that I want to do is I want want to validate the login information that is customer number and pin number as I have already told you that I have set the Privileges for two numbers that is these two account numbers and pins if you want more you can just copy this data. put paste it and you can change like whatever you want you can add more number of privileges like this so the first step when you execute it will just say welcome to ATM project and enter your customer number correct so first what you will do you will enter either of these customer numbers and then it will ask for pin number I’m reading the customer number and pin number using menu input. next int so in case if you enter some characters it has to catch an exception correct so what it will do it will say inv valid characters and it will ask you to enter only numbers because I have set the Privileges only for numbers so in this for Loop I’m trying to check whether the entered customer number and pin number is correct or not if it is not correct it will print saying wrong customer number or pin number that you already saw in the output so after that if the entered credentials are correct then this method will execute that is the get account type in this get account type I have mentioned these choices that is select the account you want to access checking account saving account Choice Etc and then using the switch case I’m using get checking get saving methods if you press exit it will say thank you for using the ATM bu and and the default choice if you press the choice that is not correct it will say invalid choice so here is the get checking and I have defined the method over here that is get checking so what all we had in the get checking method view balance withdraw funds deposit funds exit correct now I’m reading everything that is account balance using money format withdraw input deposit input and everything will be in get account type method correct and obviously case 4 will be your exit so it will just print saying thank you for using the ATM by now similarly for savings account that is view balance withdraw funds deposit funds Etc again we are using switch case to print the saving account balance saving withdraw input saving deposit input everything so this is all about your option menu class now we will see what is there in account class so here it is just require to set the customer number and set the pin number that is first to set the customer number and return customer number and then you set the pin number and return the PIN number so basically account class is to retrieve all the details that is being set in option menu that is your checking balance saving balance your withdraw input deposit funds everything that is being mentioned in option menu class so you can see here that I have checking balance method and I’m returning the same and again I have saving balance so here you can calculate the checking account withdrawal that is checking balance equals to checking balance minus account and then it will return the same that is we saw that when we want to withdraw 2,000 from 4,000 it will say the new saving balance will be 2,000 similarly the same thing will be here that is saving balance minus amount like that so similarly you can calculate the account deposit the saving account deposit that is the balance plus the amount that you enter suppose say the saving balance is zero and if you enter 2,000 so it will add and it will return the balance similarly the same thing with this as well that is account withdraw input and customer saving account withdraw input as well and then it will just check the deposit amount same thing for savings as well and I have initialized all these variables as private because I want them to be local to the class so this is how it works and now coming to the last file that is atm. Java so here this class extends the option menu and option menu extends account so what ATM should do it should obviously extend option menu and I’m just creating an object of option menu and just trying to get the login from option menu so when I execute again it works same it will last same thing again if I enter something it says wrong customer Pinner account number as I have told if I enter something else apart from the numerics it says invalid characters only numbers that is the exception that I have thrown so this is all about the ATM project I hope you understood it now let’s move further and see the text editor so here I’m making use of java swings that is I will be using J text area menu bar J menu bar Etc and all the menu items will have action listener to detect any action and as I have told it makes use of java applet and swing Concepts and similarly all that you just need is a Java installed and the eclipse ID we can say like we can perform all the operations like we perform in your wordpad or your Notepad and it’s very efficient so now let’s see how it works so first let’s execute and see how it works and then I will explain you the code so you got a text editor here you can see you have file and it consist of all the operations like new open save exit and you have edit option like cut copy and paste you have font like bold plain italic and you have size like up to 28 and you have font type that is Roman helvetica IAL corer Century Etc and also you can set the background and foreground color and you can undo and redo the operations now let’s see each of them how it works so I want to say like welcome to edure YouTube channel and enjoy learning now suppose I want to change a font of this I’ll capture everything like control a and then I’ll give font like bold so you can see here it became bold say suppose I want it to be italic you can see even that became italic as well I want to increase the font size like 28 it got done I want to change the font type to Century even that happened say I want helvetica I want times Roman even that happened say I want a color to give for that like background color in something like say I want red okay you can see the background color is red so I want to remove the background color now now we change the font color to be say I want to enter some more text like I did as Java projects and I want to undo that I can just press contrl Z and it goes on removing all that thing and control 5 for whatever I have deleted you can see it’s going on also you can create a new file that I just did also if you want to open something that is is already present you can open from the libraries also if I want to save this I can save it like however I want in the downloads or in desktop whever you want you can save the file by giving save it it will be saved I can enter something and again if I want to save it it will be saved like applet one similarly you can even check that whether it is being saved or not so in desktop you can see it is being saved as applet and applet one so basically this is all about your text editor as how it works like you can perform all the operations like edit font file color undo redo everything Etc sounds interesting let’s see what is the code behind this now so here you can see a undoable text area that extends the text area and Implement State editable why Implement state editable is because we have defined the editable class in which we can edit all the options like I showed you on the text editor so you can see here I have given the key State as undoable text area key and then I have declared the current edit and undo manager and the first undoable text area I have defined it in various ways the first thing it is zero parameterized and then in the next I have defined some parameters like string and I have given it in super as well and then I have used rows and columns and then I have used string along with rows and columns and then string rows columns and scroll bars as well so in various ways I have declared this undoable text area Constructor so if in case something happens you are stuck and you cannot undo some operations that you have perform then automatically the exception will be catched here and next same for redo as well if you cannot perform any redo operations then it again catches an exception you might be wondering why it need to catch an exception correct it’s just because to maintain the normal flow of execution so that your further operations will not be interrupted and next to store the state and restore the state that I have given I’m using the key State as a variable and for the snapshot method I’m giving like condition if the text is being changed then use undo and add edit to edit the current state and now I’m declaring the init undoable and giving some new reference variables for undo manager and current edit and I’m adding the key listener for new adapter and then I’m using the focus listener to focus the event that was being captured and similarly for text listener as well if the value is changed it has to say that the text is being changed and now you can see there’s a text editor class which undoable text area has extended in this I’m declaring few parameters like frame file dialog font Etc and now here comes the text editor parameters like say corer at style it’s size everything and here I have used the option menu bar that is times Roman helvetica aial Century Etc and I have given one one parameters for each of them and then using the add method I’m adding all of them like appending it to the menu and we have to use the action listener to detect any action that is being performed so similarly for bold plain italic menu that all we saw and again using action listener we are calling that event and then I’m declaring all the sizes over here that you saw L till 28 and appending it using the ad method and to detect them I’m using add action listener even for new open save exit again using action listener for all them and for cut copy paste edit options as well for background and foreground color and for color for undo Redo for everything it all Remains the Same and then I’m implementing the action listener class to invoke that method correct like for undo and redo and similarly for file name Untitled for select menu everything so whatever the options we have seen here they all have to implement the action listener class so you can see I’m detecting save else what happens the action will not be detected you can see again for exit as well for read file everything and even cut copy paste for everything we have to use action listener classes even the size class implements action listener like for size 10 size 12 for 14 16 18 similarly till 28 that’s all and then I’m extending an applet class and implementing the action listener even for this in bold I want corer font everything and even in plane I want the same thing so as you can see if I type anything here so it is by default corer correct so that’s what is here that is in get action command in bold plane and italic whatever it is the first thing is corer correct and then comes the type that is times Roman helvetica corer aial Black Century everything and then again I’m am choosing the color that is the background or foreground colors and then I’m implementing the main method and setting the size of the text editor to 800 and 600 so that’s how it works like you can perform any operations on text editor and do rest everything now let’s move further and see the sign of form which is developed us using surf GSP and web development tools like HTML CSS Etc so I’m just going to create a basic sign of form and all that you need is servlets Java server Pages Apache Tomcat server and cascading style sheets and eclipse for Enterprise Edition and it’s very easy to develop as I’ll be showing you how so first let’s run the output and check and then I will explain you the backend code make sure that you run on server my Tomcat server is starting now so this is the sign up form that we have created you can enter the name I’ll give some email like 13 or older is my option so here in the sign up form you can see your name email password your age I’ll give some biography like I am a footballer singer swimmer Etc like just my Hobbies I can give my education everything you can give like it’s not mandatory that it should be the same thing and the job role have so many options in web mobile business and others so I’m very interested in iOS Developer so I’ll give that and interests are in development design business everything and when I sign up it says hi Cris welcome to Eda because the sign up that I have done got saved so where will be the output like or where you can see the details that you have entered in the back end in this console tab you can see the details that you have entered that is your name your email ID your password your over 13 your biography your job role your interest Etc so that’s all was there in the form so you can see here in this form these are the basic information that is being given so now let’s take a look at the backend code in the sign up I have created five files like HTML for creating a form CSS file to add some beauty or makeup to the form that we have created we have seret class files like request post form and person one. Java class and then to retrieve the data from the servlets we have the JSP file and also we have the web.xml file to add the mappings to the serlet and we have JSP file to retrieve the data from the servlets so for this front end that is your sign up
form we have used HTML you can see here that I have linked with CSS as well that is for giving some makeup to the file that is you can say beauty to the form that you have created I’m giving form action as request post form and Method will be post so here you can see in the label you have created like name email password age your under 13 or above 13 whatever it is and then for your profile or your biography you have created one more label tag and giving the text ID is equal to bio and name is equal to user bio and for the job roles there are so many so you have created a first label for job rooll and the first opt group label will be web in web you have so many options and again you are closing that and opening one more op group label that will be your mobile your business your SEC your other so same things and then for your interest like this one you can can see you have check boxes over here correct for that check boxes we have given the Class Type value everything like for development for design for business everything and last it will be the submit button that will be your sign up so this is how your index.html file will be and now coming to main. CSS file for each and everything I have given the paddings like the font family the color the maximum WID the margin background everything even for the first thing that will be the H1 I have aligned it to Center you can see here I have aligned it to Center and that is an H1 even for that I have given the specified color and the F family as well and coming down for form as well and for all these things I’m using a select type for background border font size height margin outl padding B color everything even for the Box Shadow as well you can see there’s a shadow for this box it’s not just a simple one and even for the check boxes for buttons that is present as well for field set for legend TXS for label for number TXS everything so this will be your main. CSS now let’s take a look at the serlet classes so first what I’m doing here is I’m extending a HTTP serlet class correct and I’m using a do Post method and declaring parameters for request and response and I’m requesting all the parameters that is your username email password age biography job and for your user interest again the same thing and then I’m creating a object of person and trying to retrieve all the details and then I’m trying to request and set the attribute of my person and then using the dispatcher I’m trying to request the get request dispatcher from JSP and obviously in the dispatcher forward you will be having a response and request both of them so as I have created the object let’s see what was there in the person in this it’s nothing but it will retrieve all the details that is I have made everything as private because I want it to be a private to the person class and this class is called as a being class I’ll tell you why I have made a Constructor of person one and then using the parameterized Constructor I’m trying to reference and retrieve all the details you can see like for get name method I’m returning the name and set name I’m retrieving again for get email and set email methods for get password for get dat set AG for Bio job roles interest everything this is nothing but uh defining a Constructor and retrieving the details and request post form is essential to send a request and response and then person one. Java is essential to retrieve the details and then as I have told it is requesting a dispatcher to login one so in the login 1. JSP class I have imported the bean class that is edura person one why because edura is my package and person one is my class and then I’m giving the scope as request and similarly as I have imported the bean class and similarly to redirect it to the next page I have used a small icon and you can say that it says welcome to urea so this is all about the GSP and then now coming to the last file that is web.xml you have to add mappings to the file you can give serlet name like anything but make sure you give the serlet class name very properly that is it should be like edura that is your package and your request post form which is your class name this should be very correct and then for URL pattern that is request post from URL this should be same as the one which you give in form action tab that is your request post form URL or else it will result in an error so this is all about the sign up F I hope you understood how it works so let’s just start with something known as the basic questions which are asked to the candidates in the entry process so the very first is the difference between three terms that’s like jdk JRE and jvm so as a Java developer you must have a fair knowledge what exactly are these three terms right so guys let us understand now so Java virtual machine is basically an abstract machine it’s a software which is already provided by the platform so it provides the runtime environment whenever you are writing the Java source code it gets compiled into the bite code so jvm is that there which is going to execute your bite code now other than that you got JRE which is a runtime environment now it’s basically where JV is going to use the JRE so JRE set of libraries required by the jvm in order to execute your code jdk is one development kit required by the Java developer so it consists of various apis for you through which you can write your code so just for an instance right so jdk will contain your various packages coming into uh for example java. iio java.util all these API is the set of Library the information that comes from your Java development kit other than that it has various tools also available for example Java and Java C right so Java C is a tool which is used for compilation whereas Java is for the execution of your bite code so these tools are also part of jdk so let’s switch on to the next question what is synchronization this is one of the hot favorite questions whenever you talk of threads so we do have this term known as synchronization so synchronization is something where multiple threads if they going to access the same object right so there is only one resource which multiple threads they want to access you need to come up with something known as synchronization so guys what is synchronizations here we’ll take up one example let’s say we want to book a movie ticket and it’s going to be one seat which has to be booked by multiple people right so let’s say one corner seat in the last row has to be booked by multiple people so multiple people over the web will treat them as multiple threads they are looking onto a single object on a single resource that’s like the last row last seat right so whosoever will first of all try to block that seat will be given an excess and no other person can thereafter block that seat so synchronization is very much line to this concept when you got multiple threads which are going to work over a single object you need to use a keyword known as synchronized with the help of which you will be able to acquire the locks on your objects so synchronization is a process which going to keep all the concurrent threads in the execution to be in a synchronous mode one after the other the lock Acquisitions going to come up into action synchronization will avoid the memory consistency errors due to any inconsistent view of the shared memory let us understand the difference between processes and threads now so synchronized word came up and we started off something known as thread so let us understand what exactly is process and what is a thread now so guys in order to come up with process and thread let’s just have one visual coming in let us say you got this layer as an operating system right so we’ll say that this is one operating system it can be any OS now right it can be Windows Mac Linux any of the flavor so when you’re going to run the program what OS will do OS will create a process right so this process will be created by the operating system whenever you are supposed to execute your application so other than that what it does is it will all also give you some you know storage space where Ram will come into action right so further the ram can have various data structures coming into it for example you can have the data being stored in the form of stack or the Heap right so that’s like the storage concept let us say I got one program which I need to execute so whenever I’m going to execute my program so the running instance of your program over the operating system is nothing but it’s a problem process within the process we have one guy known as main thread so main thread is what this is the guy which will execute some instructions or you can say some sequential tasks which you mention in your main method right so whatever the statements you are writing in your main method they are nothing they are these tasks which are executed one after the other via main thread within the process so guys a process is running instance of your program over the operating system and a thread like a main thread is running within the process so we must understand threads are available within the processes and processes are running on top of operating system there might be a scenario that a particular task like I’m just going to highight this task over here so this might take a longer time right so let us say this particular task will take a minute or so because it’s going to fetch the data from the server now so in this context right so these three tasks they will be blocked right so when I’m talking about these three tasks the yellow States so they going to get blocked now so what we can do we can bring down one more thread and we’ll say that this is one user thread or child threat so we got various other terminologies for this guy right and will offload the heavier task over here of the main thread to the user threa in this way what we are able to do is we are able to Outsource the heavier task to some other trade and we will be coming up with a concept of concurrent programming that is what we want to achieve now right so let us understand what has happened over here guys so let’s see this part now so process and thread they are two different concepts but we must understand now any executing instance of a program on top of your operating system is nothing but it’s a process so on operating system we got multi-processing whereas thread is something which is a subset of the process now so within a process you got multiple threads so multiple processes on OS level multiple threading on process level when you talk about the communication so one process when it wants to interact with the other process we call the processes as interprocess communication where threads within a process they can directly interact with each other when we talk of the control statement so processes can only EX exercise control over the child processes whereas threads can exercise considerable control over the threads of the same process any change in the parent process will not affect the child process whereas if there is something where the main thread is getting affected the other user threads or the child threads they might get affected if you talk of the memory structure so processes they run in the separate memory space each and every process will have its own memory space space whereas threads share the same memory space which is being allocated to the process by the operating system so guys once again process is controlled by OS whereas threads are controlled by the programmer in a program right or you can say by the process itself if you talk of the dependency level processes are independent where threads they’re going to get dependent because if you can notice this image right over here so we created this user thread and there is a dependency that this task has been outsourced to this user thread by the main thread so dependency of the main threat over the user threat relies and vice versa right so it can be based on our Logics even so let us move to the next concept now so the next fundamental is what exactly is a repper class now this is also one of you know the hot favorite question which is always asked what is repper class what is meant by the term boxing or the auto boxing so let us see this part guys so repper classes they are the way where we can convert the Java Primitives into the reference types that’s like the objects so each and every primitive type has a repper class defined and it’s in by default they are available in java. L package you need not to import any package so for Boolean we got Boolean right for car we got corrector and for INT we got integer for double so on and so forth guys so repper classes are the means by which you are able to convert your Primitives into the references so let us understand what exactly is this conversion of Primitives into references let us say I got this i as 10 so we call this guy as a single value container because I can contain only one value it’s not an object now it’s a primitive type you want convert this primitive guy into an object you say integer I sign new of integer and you mention this guy I as a part of Constructor so what we have done we have boxed so it’s like constructing the object now constructing the object so that’s what we have done guys over here right so this particular statement over here is known as boxing on the other way around when you say in J assign IR do int value so this concept is known as unboxing right extracting the value from object so you must understand this concept over here boxing versus unboxing which is achieved with the help of rapper classes other than that you can also say integer SCF assign I so this is known as autoboxing right so this instruction is translated internally by the compiler as in integer KF assign new of integer where we got this guy known as I right so this is auto transation you need not to write the whole statement so you just mention the partial statement or the implicit statement we call call it as autoboxing and if you write down let’s say l assign K right so this is known as Auto unboxing so important question again what is boxing versus unboxing and thereafter what is auto boxing versus Auto unboxing so the major reason why we do boxing or unboxing is to convert Primitives into the objects now if you’re talking about objectoriented programming structure right so we are always thinking of objects now so if you are able to convert Primitives into the objects it means that you are strictly and truly following object oriented programming structure so we got one way of doing it and now you can also pass by reference The Primitives so that’s one more uh way of coming up like why you do a boxing part so we can pass the variables by references now right because here you are getting the references to the objects all right so let’s come back now to the next question number five that’s like what are the keyword final finally and finalize and what is exactly the purpose of it so there are now the three different keywords right so even the final term is something which means the last thing but they have a different meanings in different context now now final is a kind of a constant so if you mark a variable as final you can’t change its value so here if you can see a very small snippet right so a is 1,000 and you try to change its value the compiler will not allow you to do so so final is a keyword where you are able to mark your variables as constant you can also Mark your classes to be final in that context you cannot inherit from that class you can also Mark the methods to be final in this regard your methods they will not be overridden so final can be used with three of the concepts final as a variable final as a class and final as a method finally is the other context where we use it with the exception handling techniques now so what exactly is the place where we will be coming up with finally so many of times when you are writing the exception uh hand code with a try and a catch Clause there might be a scenario whenever the exception will come the statements mentioned within the tri block they will not be executed below the statement where the exception will come right so let’s say there are 10 instructions in the try and on the fifth instruction in the try you get an exception so below 6 7 8 9 and 10 instructions they will not be executed you need finally block to mention such instruction which must be executed either exception comes or it does not so finally is that piece of block which will be executed whether the exception is coming or it is not coming for example if you want to close the database connections now exception is there or not but we would like to close the connection at any cost right so you mention all such statements in your finally block so the next part is finalize so guys finalize is a kind of a Destructor so whenever the object will be removed from the memory by the garbage collector so this finalized method will be executed so you can explicitly try out this example where you can say system.gc right and you need to just mention your references to be pointing to the null and thereafter your finalize will be executed so we can just have a small example on this right so what I can do I can just demonstrate this so let’s say we got this class known as finalize demo right and I’m just going to make this method finalize over here so I’ll say ciso object finalized right so here we go now what I’ll do I’ll create the object of finalized demo so I’ll say finalize demo FD reference assign new of finalize demo so here we created an and thereafter I’ll say the ra to go as null it means it is not pointing to anything now so later I’ll say system. GC so GC is called to the garbage collector and it’s going to destroy the objects which are no longer required so now you can see over here so let me run it as a Java application it says object finalized why is it coming because it’s acting as a Destructor call so anything which you want to do before your object is removed from the memory right you can write it into the finalized Method All right so let’s go to the next concept it’s a difference between string buffer and string Builder right so before we jump onto the string buffer and string Builder we must understand they are both similar Concepts when they are compared with the string class so string is is immutable version whereas string buffer and string Builder they are the mutable versions right so let me Define this part what is meant by mutability versus immutability consider you got this string sdr1 which is a new string having hello and you got this one more guy known as string Builder you say Builder sign new string Builder and you mention hello similarly you say string buffer let’s take this guy as buffer you say buffer assign new of string buffer again hello so I have taken up these three strings let us say St Str Builder and buffer and now what is next I will be appending the data in these strings now so you say St str. concat so in string you need to say the function function as concat so I’ll say hi and similarly let us concat it into the buffer and the Builder so I’ll say Builder do append so in the Builder the function which we use is append and same goes with the buffer so buffer and Builder they are quite similar now later when I’ll do a ciso on St Str and similarly the Builder and the buffer part let us say Builder and then finally the buffer so the buffer here we run the code you see one major difference over here is that you get hello so nothing happens when you concat the data into the SDR right but in case of Builder and buffer the data is concatenated this is why because strings are immutable whereas buffers and Builders they are mutable this is also one of the very B beautiful query first of all so guys buffer and Builder they are the mutable sequences whereas string it is immutable you cannot change it even though you are going to perform an operation so what is happening over here whenever you concatenate the data you will be getting a new string right so you need to store the data into a new string so concatenation results the data coming out as a new string the old string string is not changed so significant difference between buffer and Builder now we’ll be discussing string buffer operations are thread safe so it means that by default when you are going to use buffer it will be synchronized you need not to worry on top of multiple or concurrent threading now whereas Builder it’s not thread safe string buffer is to be used when multiple threads they are going to work on the same string whereas Builder is supposed to be in a single threaded environment other than that Builder is quite better as compared to buffer over the performance part because there is no synchronization overhead so you can just try to write out this nippet over here which will be able to help you to come up with the timing difference and you will be able to see that Builder will outshine the buffer in terms of performance all right so let us understand the difference between Heap and and stack so stack and Heap they are two memories which are very much famous when you talk about the Java runtime right so Java runtime the ram we got these two major data structure stack and he so first of all let us see how this stack and Heap uh will come into action right so let us take one example guys so I’ll just remove this Snippets all right so let us understand the stack and Heap into action when we are talking about about the ram allocation so this Ram will be divided into two parts the first part is the stack and the other part will be the Heap so this circle is representing the Heap memory so both of them are a part of ram now right so both the data structure they are part of ram we got stack and Heap so let us understand this point of stack and Heap how the data will be stored and where it will be stored I’ll just take up one basic example from the eclipse now whenever you will be creating an object so for example finalize demo I said FD ref assign new finalize demo this is known as object construction statement right so this is object construction statement so here what we are doing we are trying to create an object with the help of new operator and to be very much uh more precise I’ll take one class like point right and we’ll Define some X and Y as attributes within this class point right and I can have one function like show point which can just display me the data of point so I can say point is plus the value of x let us say a hyphen plus y right so that’s like a point now so how I’ll be creating the object of point now same way you created the finalized demo you say point P1 reference assign new of point so how this statement will be represented in the memory so guys for this statement to be represented in the memmory what will be going into the stack what will be going into the Heap let’s have a close look onto that part now P1 ref over here will reside into the stack like this right so this guy is P1 ref it will be created on some memory location so let us assume it’s 4,01 it will be a hexadecimal address but I’m just assuming it to be one address over here as 4,01 so this memory location this container P1 ref is created out over here what is next the next part is an object which will be constructed in the Heap which will have two compartments the first compartment is your attributes that’s like X and Y and the second compartment goes like the methods show point so this is like the attributes and the second compartment is for your methods now what is happening over here so this object has no name now right so this is having no name on the Heap you don’t have any name for this guy but you can definitely have an address over the M let’s say this is 601 so this object is constructed at 601 so P1 one ref will have the address of your object and this guy P1 ref is doing nothing but it is pointing to this guy 60001 so we say T1 ref as a reference variable because it is referring to the object available at 60001 it’s not a kind of a pointer now right in order to prove this uh prove this concept we can just say C out of P1 ref when I will do a sis out of P1 riff let’s say P1 riff is plus the value of P1 riff now I’m going to run the code you will understand that P1 riff over here is showing me some address of an object of type point right since we got in the package cod. Eda so it says that code. edao at memory look so this is the memory location 7852 e922 which P1 ref is holding for your object so now once we are good to go what is available in stack what is available in Heap for this instruction right so guys anything for which you use the new operator that will be constructed in the Heap so Heap is that memory location where we use use the new operator and new operator is used to create the things dynamically when I use the word dynamically it means at run time it means anything which is constructed dynamically at run time in your program it will reside in the heat right so that’s what the new operator will help us to do now let us have some more differences between stack and heat so guys stack memory is used only by one thread of execution whereas Heap memory is used by the all parts of the application if you talk on the excess level objects stored in the Heap are globally accessible whereas stack memory cannot be accessed by the other threads memory is like Leo whereas the Heap memory is basically the tree structure now right so the memory management is based on the generation Associated to each object so here what we try to store the data is in the form of ke value pair so each and object will have a hash code now so that acts as a key for your object then you talk of the lifetime so we got existence until the end of execution of the thread whereas Heap memory will live from the start till the end of the application execution and your garbage collector can anytime free this m space if you talk of the Usage Now when an object is created over the stack so now please guys in case of java every object is dynamically constructed so there is nothing like objects being constructed in the stack right so we are just giving a general overview of Heap and stack over here not typically inline to your Java these are the general differences now in Java your each and every object will be constructed dynamically in the Heap space not in the stack space so in the stack space you will be getting the references to the objects now right so guys whenever an object is created it is always stored in the Heap space and stack memory only contains the local reference variables which are pointing to the objects in the heat so let us move towards the next basic question that’s like the difference between the array list and a vector so these are the two data structures these are the two collection apis in the Java do util package so both of them are quite same the very major difference is that array list is not synchronized whereas Vector is synchronized so guys when your data structure is not synchronized so the performance will be a bit more better as compared to the other one so that’s why your RLS will behave faster in terms of performance as compared to your vector if an element is inserted into the RLS it increases the size by 50% whereas Vector they don’t do it so but they just double the the size of its array right and rs does not define the increment size whereas in the vectors you can Define how much size the vector should increment when it has reached its limit other than that rlist can only use iterator for traversing whereas in Vector right except hash table Vector is the only other class which can use enumerations as well so you can enumerate over the vector with the help of enumerations we can also you know iterate within the vector so that’s that’s like some of the differences which are highlighted over here similarly the other collections uh hashmap and hash table so this is again a relevant question which is asked in the interviews many of times as a basic question so hashmap and hash table again the first difference is the synchronization right and your hash tables they are synchronized whereas hash Maps they are not synchronized hashmap allows a null key and a null value whereas hash table will throw a null pointer exception if you’ll try to add a null key or a null value other than that since a hashmap is not synchronized it’s going to behave faster as compared to the table and we can make the hashmap as synchronized by calling the collection synchronized map API so it’s not like that we cannot Mark the hash M synchronize we can come up with our own Logics as well right so guys hashmap Traverse can be done through iterator whereas table can be enumerations as well as iterator hashmap will inherit abstract map class whereas hash table is totally working on the dictionary class now the next concept is the difference between equals and equal to operator now this is one you know as a new Java developer many times we’ll do this thing we’ll do this big mistake by comparing the strings with the equal to operator so unlike your other languages here you need to use the equals method to compare the strings now right so guys let us understand this concept first of all I’ll just try to demonstrate it by writing one example so let us say you got one string s Str one as new string so just recently we had this discussion that this is an object construction instruction so s Str one is a reference variable whereas the string object will be constructed in the Heap so St str1 is having one address right so let me write down this thing Str str1 is a reference variable it is having the address of an object similarly I’ll create one more Str str2 right so Str str2 is also a reference variable it is having the address of some other object the difference over here which we need to understand is that there are two different objects which are containing the same value hello right so objects are containing the same value hello and S str1 and S str2 they are the two different references and having the different values so that’s why if you’re going to compare it using equal to operator right so it’s going to say Str str1 let me just finish out the program and in the else part I’ll just say not of equal to right now you will observe that s str1 is not equal to Str str2 the reason is very similar because you are comparing references now so double equal to we are comparing references right so that’s one important difference for us to understand now when you need to compare the objects you don’t use double equal instead you use this method known as dot equals right so you say let us compare the strings using equals method so here I’ll say equals and not equals so we don’t compare strings using the equal to operator that’s very risky it’s it’s one big mistake you compare the strings with the equals method equals meth method is not comparing the references it is comparing the values within the objects right so that’s what we are able to understand comparison of references versus comparison of values so you can take up this program guys over here if you can see right just go ahead and try to run this execution we got one more program over here let us predict the output for this program so in the main method you are calling the method one with the input as 11 so you pass this 11 over here from here you are invoking the method two by passing 11 into 11 and in the method two you are passing method three which is division of 11 and then in the method three you are subtracting 11 and finally in the method four you are adding of 11 so guys finally we’ll be getting the result as 11 itself right because 11 11 into 11 it’s going to be 121 divide by 11 it’s going to be 11us 11 it’s going to be 0 + 11 it’s again going to be 11 so try out this program right and see to it if you can get the same output or not so these are some of the basic questions right highlighted by us which are very important and crucial from the interview perspective next we’ll be jumping on to the objectoriented programming structure now this is one key area which company or an interviewer is looking and uh expecting as a developer you should be quite good on these Concepts because the advanced concepts or any of the application development model it relies heavily on object oriented programming structure so let us see what we can have in the objectoriented programming structure so the very first question as in question number 12 is the difference between abstract classes and interfaces so let us see some of the differences again guys this is quite theoretical information right uh but I would like to take one very small demonstration on abstract class versus interface because it is very important to have a very fair knowledge and this concept is linked with your runtime polymorphism so let us understand this concept so I’m going to create one class shape and we’ll have this uh method known as a draw right so let’s have a draw method and you say see so drawing a shape now this is something which even we teach in the traditional language like cc++ I mean Native languages so this is the same concept carried forward we got a shape class and we got a draw method so what you going to do you’re going to create the object of shape as assign or let us say shape s and then say s sign new of shape and then you can say s do draw so the output is very much simple you get the mathod drawing a shape but I want my shape to be be either as Circle rectangle or polygon right so what I will do I will just come up with a class known as Circle so I’ll say this guy’s Circle shall extend something known as shape right and in a similar way I’ll also try to come up with something known as rectangle and lastly I’ll say a polygon so shape has three children now and each and every child will be redefining the draw method with the respective shapes right so here we are now this is very well understood that whenever you’re going to redefine the method so the concept of overriding will come into action right so this is overriding and now if you say Circle C and C assign new of circle and you say c draw you will always get drawing a circle because overriding has come into action what I want to do I don’t want to do this concept right it’s it’s a basic concept now that whenever you’ll create the object of child always the definition of child will come into action as a concept of overriding what I want to do I want to say reference variable belongs to the parent and the object belongs to the child now this is known as polymorphic statement so how it is a polymorphic statement now the guy shape s is pointing to Circle so shape is now behaving as Circle let us assume that now this instruction is equated it’s very well equated the equation is true reason is that circle is also a shape circle is a child of shape so technically their type is same now right so I’ll say s do draw so I’m saying s do draw what you’re going to observe is you get drawing a circle now which is very well true because there are two definitions One belongs to the shape other belongs to the circle and when you say s do draw you’ll be getting drawing a circle so you will be giving the preferences to the children over here and the parents definition they again going to get overridden what I’ll do now I’ll say s is now a new of rectangle right you say s do draw and then you say s is new of polygon and then you say s do draw so every time you are able to achieve s do draw drawing the different different shapes right so this is what we call as in runtime polymorphism the same method draw over the same reference variable is we are able to draw different different shapes dynamically at runtime so guys this beautiful concept is known as runtime polymorphism right and what we need to understand from here is that the guy draw in the shape method is useless having this concept over here that s is a new shape so having the object of shape and executing this guy s do draw makes no sense it’s not a pretty good sense right drawing a shape makes no sense shape has to be Circle rectangle or the polygon so what we need to understand from here is we need not to have the object for this class and we need not to have the definition for this guy draw so you can change the architecture of your program and you can bring down one more class shape mark this guy as abstract and mark the method Within your class also as abstract so an abstract class is a class for which you cannot have objects now you can’t create the objects right so here you can see it’s an error other than that the method can also be marked as abstract which means you need not to have definition so guys when a class is marked as abstract you cannot create the objects but runtime environment will create the object right so see so I say shape is constructed very very important difference which I’m going to highlight today so when you say the Constructor over here right so you are able to create the Constructor it means the objects can be constructed for the shape but you cannot create it runtime environment will be able to create that you cannot create if you will try to create create it it’s going to give you an error right so the same problem statement is solved drawing a circle drawing a rectangle drawing a polygon but before the construction of the child object the parent object is constructed by the runtime environment so we say this is object to object inheritance right so what is happening over here inheritance is happening here from object to object so the parent object is constructed by the runtime environment and then the child object is created so abstract class is a class you cannot create the objects but the runtime environment can do so and it can have abstract methods which have no definition so no definition for this guy who has to Define this guy the child has to mandator define the definition for the draw draw so if the child is not defining the draw method it’s going to throw an error so let’s try to see this so you try to comment out this code you can see now it is giving you an error so if there is n number of abstract methods in the abstract class you need to redefine them in the children now we can understand this part that this shape has helped us to improve the concept of runtime polymorphism but this is again which is like a parent is writing some rules which are supposed to be defined by the children now there’s a relationship known as parent and child relationship so abstract class shape is when extended by the circle it’s a parent child relationship for example the parent is giving is just making a rule that breakfast has to take place at 800 a.m. in the morning Now The Childrens they need to Define this Rule and they can come up with their own definitions okay we’ll come up with a breakfast at 8 A.M but I’ll have uh snacks I’ll have bread and butter or anything right so that’s like a parent and a child relationship and from basic shape class we came to an abstract class shape with some you can say there were some problems over here that we didn’t want the object to be coming up and we didn’t want the raw method to take place right so we achieved a better way of coming up with runtime polymorphism through abstract classes now I’ll come up with the best way so I’ll say one interface shape with the method as white draw so guys this is the best way to achieve runtime polymorphism now so what I will do I will not say extend shape but I will say Implement shape now this is the difference which we must observe over here so rather than doing an extension I am doing an implementation and in the interfaces by default the methods are public abstract so it is by default like public abstract wi draw and in the interfaces if you will observe now so this Constructor is significantly an error it means that neither you nor the runtime environment can create the objects of shape right so it’s an error right so for the interfaces neither you can create the objects nor runtime environment can create objects it means this is not object toob inheritance there is nothing like parent and child relationship over here what is the problem over here this is the kind of traffic police or the police department is imposed osing the rules on us to wear a seat belt and now we need to Define that rule right so traffic police is imposing a rule to follow the traffic lights and it is up to us that how we Define that rule so it’s not a parent and a child relationship kind of a concept it’s not parent object and the child object concept right I hope you got the example and you are able to correlate the fundamental between the interfaces versus the abstract classes now since this method is by default public so in order to redefine you need to always have a higher excess or the same excess right so this is how you have achieved one more refined way of runtime polymorphism right guys so what we have understood let’s come back and now summarize the whole Concepts so abstract class and interfaces there are the two different concepts but we can accomplish runtime POC morphism with both of them one being the parent other one being one implementation right so guys an abstract class can provide complete default code or just the details that have to be overridden whereas interface it will not provide any code so it’s just the signature there cannot be any definitions in the interfaces whereas abstract classes they can have the definition so we can only extend a single abstract class whereas a class can Implement several interfaces so this is not multiple inheritance it is multiple implementation Right Moving ahead now abstract classes can have even regular methods whereas interfaces they cannot have now the instance variables in the abstract class they can exist but an interface it cannot have any instance variables its variables are by default static variables right in abstract class is you can use public private protected so on and so forth whereas in interface by default the visibility is public or none right so it is by default public somehow if you mention nothing it is by default public now so here we can have Constructors here you cannot have Constructor it means that you don’t create the objects but runtime environment will create here neither you can create nor the runtime envirment can create abstract classes are faster as compared to the interfaces they slow because it requires extra IND direction to find the corresponding method in the actual class right so that’s what we got some of the theoretical differences after the Practical implementations so polymorphism I hope is now very well clear right so guys polymorphism means more than one forms where a mobile phone can serve the purpose of camera remote MP3 player and alarm clock so on and so forth right so polymorphism can can be characterized into two parts one is at the runtime one is the compile time so guys runtime polymorphism is where you are coming up with this parent and a child relationship again we saw this math example shape Circle polygon and rectangle right so what what happens in the runtime polymorphism you create a parent class and then you create a child class child class must override the method of the parent class and thereafter you do an upcasting by saying the reference variable of the parent can point to the object of child and whenever you will execute the method you’ll be able to see the method execution happens for your child so what is the difference between overloading and overriding so guys overloading is concept linked with a compile time polymorphism whereas overriding is linked with the runtime so in the definition part math method overloading means that the same method name should have different inputs or the different arguments right every time they must be different now so in method overwriting the signature should exactly be same so here return type will not make any difference but here everything should be exactly same if you talk of the behavior method overloading is basically adding or extending the methods Behavior whereas overriding is changing the existing behavior of the mathod now right so here we are trying to add the functionality here we are trying to change the functionality so compile time polymorphism versus runtime polymorphism different signature versus same signature and when you are talking of The Inheritance it may or may not need inheritance in method overloading whereas overriding is only linked with your inheritance so this is one significant difference guys if you can see right so this we have already observed the overriding part but in the overloading part if you can see over here the add method with the two inputs of type integer and two inputs of type double so this is one uh significant example right so guys uh this is like overloading and this is like overriding right so you can just I think this is done wrongly so overriding is this example overloading is this example all right so if there is any method which is private or static so can you just try to overwrite such a method so guys the answer is no you cannot do so so private method will not be inherited so it makes no sense to override it or to redefine it whereas static method it belongs to the class so you cannot override a static method right so it’s basically what we call it as in a class to class overriding which is known as hiding right so here the concept is known as hiding so if there is a static method in the parent class and if you want to create a method in the child class to override the static method it should also be static and that concept will be referred to as hiding now so what is multiple inheritance and does Java support it so guys multiple inheritance is one class extending more than one classes so this is not supported in Java so if you can see there is a diamond problem which comes into action that if there is a class A right and B and C class they are inheriting the a class and there is a Class D which is getting inherited from B and C so two copies of a will be coming into the last class so this kind of problem is not solved in the Java it needs the virtual Concepts to come into action since there are no virtual keyword or any other you know pointer support a in Java so we cannot solve this problem now right so Java multiple inheritance is not supported so one more query now over here right what will be the output of this program so if the parent is having this method F which is marked as static and one method bar which is a non-static method and there’s a parent child relationship where we are hiding a method versus overriding a method and you are executing these method calls right so guys the output will be so since if you can see over here so this parent. Fu and child. Fu then parent. barar and child. bar right so you’ll be able to get all these four outcomes I’m am Fu in super in child then child and then child right so just try to execute the code and get the behavior similarly we got one more program so guys this is where we got multiple Constructors and you created the object for the a so by default default Constructor will come into action but this over the reference function call Will execute the Constructor over here and this over here will execute the Constructor over here so you will get how are you then hello and then the height right so this as a Constructor execution will happen over here as a function call so you’ll get the output in the reverse order now right so one more program guys what’s going to be the output for the program so it’s basically one miscellaneous program where you got a block and a static block so guys a block is executed when you create the object of a class whereas static block is executed when the class is loaded into the memory so the idea is to Define you guys the role for the static block and a normal block so a block over here if you can see is executed when the object is constructed and static block is executed when the class is loaded into the memory so just try to run this program and come up with this output guys all right guys so now let’s understand seret right so this is where we’re going to pursue with the Enterprise Edition concepts of java so we have left out the core part of java and now we are moving into the advanced part of java so serx is also one of the Core Concepts when we talk of the Enterprise Edition of java so let us understand what exactly is a Ser right so that’s like what is a serlet so serlet is one Java program which is executed over the server now that’s like one very basic definition to what exactly is a server so what happens now whenever you’re writing an Enterprise application you need to have some code which is executed by the server so if the client is sending a request via HTTP or the https request will come to a server and the server will execute your Java program and it’s going to send back the response to the client now the client can specifically be browser or it can be a mobile application or any other kind of a client di right so Java serlet is a server site technology which will extend the capability of web servers by providing support for dynamic response and data persistence we got Java x. serlet and Java x.l. HTTP package which provides the various apis for writing the serlet program now any serlet program should implement the seret interface along with the life cycle methods where you can manage your cod snet as most web applications they are accessed using the HTTP protocol so we got a class known as HTTP serlet and we got a corresponding hierarchy for the same so over the web we use two of the major methods one is the get one is the post so what is the difference between get and post so guys get and post we got two major methods how we can send a request from a client to the server other than that we also have various other methods like put delete PR so on and so forth so these are the two important methods get is when you need to have limited amount of data which can be sent right because the data is sent as a part of URL now so post is when you have a large data and you need to send it across the body so it automatically comes up that the data is not visible as a part of URL and uh it is more secure in in terms of post request right so security is more because the data is not not exposed in the URL other than that you cannot can notot bookmark the post but the gets can be bookmarked we got item po versus non itm poent so guys what is item Port when you send a request you get a response you again send a request you again get a response and you compare the two responses whether they are equal or not right so it important so this guy get is more efficient right and it is more used than the post right where now it depends right so efficiency is like get is more efficient undoubtedly but it depends upon our requirement where you need to use what okay so let’s say you want to do a sign in so obviously we need to send the username and the password to the server and you cannot send it across the URL even though you can send it but you need to encrypt the data before you send it right so that’s like the differences between get and post now what is meant by the session management right so guys session is one term which means the time interval between the client and the server so we have techniques to manage the data within the session so that’s like the session management now so what are the various methods so number one we got the user authentication then the hidden form Fields Cookies URL rewriting and we got HTTP session API also to manage the session so session is a conversation State between the client and server and it can consist of multiple requests and responses between both of them now HTTP is a stateless protocol you cannot manage and maintain the state so that’s why we need to use some fundamentals through which we can come up with this right so guys every session will have a session ID which will be passed between the client and the server during the request and response and you can use various different techniques so to name few we have mentioned them right now we also have two apis known as serlet context versus serlet config so what is the difference over here so Ser context and config is where we need to extract the data which is stored somewhere as in part of your web.xml deployment descriptor so we will consider that part now so serlet config is a single object where serlet context is on a global level now right so it’s like local parameter associated with a particular serlet whereas we got a global parameter so both of them are the key value pairs right mentioned within the web.xml file whereas serlet config so you mention the data within the serlet whereas serlet context is mentioned out of the serlet tag in the serlet program you can use the API get serlet config and get serlet context and thereafter on the basis of the key you can retrieve the data right so for example shoing card of a user is specific to a particular user so you can use serlet config whereas to get the Mind type of a file or any kind of a global level or a a variable you can use the serlet context now what is a possible life cycle of a serlet now this is uh really important when you talk of servlets guys right so uh servlets they got five stages when you talk of the life cycle right the first of all the Ser will be loaded then it’s going to be in instantiated initialized then a request will be sent to a serlet and then finally the serlet will be destroyed so we got in it service and Destroy as the three life cycle call backs involved when you write the serlet program so you got three of the apis now init service and Destroy what is request dispatcher if you want to share the data from one Ser to the other Ser evenly right so we got this guide known as requ EST dispatcher which can forward the request to the other resource now this other resource can be possibly a serate or an HTML file or a GSP file and we can do so using the two different methods one is the forward method other one is the include method so what happens over here is when you send out the requests from the seret one to seret 2 when you use the forward method response generated from the ser let 2 will be sent back to the client in case of the include method response from the serlet 2 as well as the serlet one will be appended and then sent back as a final response to the client now we got request dispatcher coming up with the forward and include in these two differences so guys one of the important concept associated with the ser session management is cookies right so what exactly a cookie is so cookies are the textual data which gets stored on the client machine and this data is sent from the server so data is stored in the local machine of the client guys let us see this part right so if you can see over here I’ll show you this thing so when you open down the settings of your browsers right and you try to say cookie right so if you can see over here so you get this options of cookie coming up over here content setting you can see cookies so allow the local data to be set which is evenly recommended so guys cookies are the textual data which gets stored on your machine and you from the server can just use the method known as get cookies right to read out all the cookies and you can create a cookie by using the APA cookie itself it’s a hashmap key value pair cookie C1 assign new cookie with the key and the value right and if you want to add the cookie to the client’s machine you just call the method add cookie over the response object so the next part is the Java database connectivity so guys this deals with the database connections now right so Java database connectivity we got the first thing as jdbc driver so whenever you want to create a connection you must must have a driver right so guys driver is the layer which will help us to interract our jdbc apis with the database so there are four major types of drivers we call them type one type two type three and type 4 driver it goes like jdbc odbc Bridge driver native API driver which is a partial Java driver then if you want to come up with a client server model you got Network protocol driver and lastly you got got the pure kind of a driver thin driver the fully Java driver which will’ll be using to interact directly with the database so Java app it’s going to use the jdbc API and the jdbc driver manager will interact with the driver and drivers will further interact with the drivers for the databases libraries and so and hence this whole channel of communication will be established so what are the various steps to connect to the database in Java we use jdbc and there are some sequential steps which you need to perform so that we can perform all the crude operations so what are these now so there are five sequential steps which you need to perform so guys any of the database whichever you are using right so you need to come up with the documentation over their website right uh what is their driver class name what is the URL so on and so forth anyways let us have a look on to the snippet now so the first one is registering the driver which comes through the API known as class. forame so here you manage to write the driver type for driver or any other driver which you are going to use then you need to create the connection which is created with the help of an API known as driver manager so you say driver manager. getet connection we need to pass three things over here the first thing is the URL where your database resides so if it is on the Local Host you mention the host name to be the local host and you manage to write the port number and the database name then the username and the password for your database thereafter you need to say create statement over the connection once you have created the statement thereafter you’ll be able to execute any of your SQL query but in the finally block you must close your connections right so this is important that you manage to close your connections regardless or whether exception is coming or not coming so what are the different jdbc API components so guys we got various interfaces and classes coming into the Java jdbc package so we got java.sql package and many of the libraries if you can see the apis are mentioned over here so in the interface part we got connection statement prepared statement result set result set metadata database metadata and callable statement so all these are the interfaces so connection is used to have a connection statement to execute the SQL statements prepared statement is also used to execute the SQL statements but prepared statement is different from the statement in terms of how you are going to substitute the data into the SQL statement so here we use something known as wild card correctors as question mark right result set is the retrieved data from the database and the data about the retrieve data is known as result set metadata and the data about the database is known as database metadata callable statements are used so that you can execute the stored procedures of your databases and some of the few classes which are mentioned in the right hand side it includes driver manager which is used to get the connection so Bob and clob are the two apis where you can manage the binary large objects and the character large objects so binary large object means the audio files the video files right whereas clob means the textual files then the type will Define what are the various types SQL exception is exception in the jdbc if there is any connectivity issue or any other syntactical issue or any different kind of SQL issues which going to occur at one time so SQL exception is the class to get the error from now what exact a jdbc connection interface B right so guys the connection interface is the one which will maintain a session with the database so here we can uh use the transaction management logic which means Atomic City so Atomic City means that all and everything should happen at once so let us understand so connection is one important interface with the help of which we can manage the transaction for the transactions let us assume I want to transfer the amount from one account to the other account so there needs to be two possible SQL statements which are supposed to be f one will be the updation in my account that will be deduction of the payment in the other account again an updation query which will be the addition of the payment so these two queries should be fired at once and if any one query fails the other query should be rolled back so for the transaction management V are the connection you create the statement and thereafter you can come up with the autoc commit API where you can mark it as true and then you can use the apis like commit and roll back to manage your transactions so close is a method where you are able to close the session with the database right guys so there is one more possible difference between three of the apis that’s like execute execute query and execute update so guys execute query execute update and execute these are the three different apis all the three apis are used to perform the SQL operations over the database but query method is always focused to do a retrieve operation if you can see now select operation right so whereas your execute update method it’s going to perform the DML and the ddl operations insert update delete create an alter of the table right whereas execute method it is able to perform any kind of operation now so this is typically used to retrieve the data here the data can be modified whereas execute method any kind of SQL statement return type of these methods they are different now so result set will be returned from the execute query method here we’ll be getting some integer output and here we’ll be getting some Boolean output this method is used to execute only select queries so non- select queries and here both the select and non- select queries right guys so that’s like the jdbc part right so how we got various apis available in the Java database connectivity but we need to come up and understand there are the five different steps so you start from loading the driver then creating a connection writing the statements executing the statements and finally moving on to the closing of the statements so the next part is the framework of Frameworks that’s like the spring framework so if you know this if you have a hold on your spring framework guys so it’s like you are done with almost everything now right so one of the most important framework in the Enterprise Edition of java let us see what is spring framework so what exactly is spring guys so spring is
an application framework which focuses on a concept known as inversion of control for the Java platform so many of the Great Technologies they are built looking onto the architectural model of the spring framework even the Android how the UI part is linked with the layout part so that concept is again adopted from the spring pattern right so it is one of the pattern which focuses on ioc that’s like inversion of control so the framework core features they can be used by any Java app app for building an Enterprise Edition application one of the major advantage of writing a spring framework app is it’s lightweight it is having an integrated framework architecture where we can use it to develop any kind of an Enterprise app in Java right so it’s less on a memory it’s high on performance and it contains various Frameworks available within it through which you can write a multi-purpose Enterprise application so guys what and all are the modules available in the spring framework now so spring framework has various modules to start with we got the very first layer as the core container if you can see this core layer so whole of your spring framework is dependent on this core layer so this core layer focuses on something known as inversion of control and dependency injection so we got this as spring context dependency injection then aop is aspect oriented programming which focuses on how we can fulfill crosscutting concerns then the database module of the spring framework includes Dow jdbc and orm as in the design patterns so Dow the data access object so here we can write the Dow patterns to access the database we got jdbc support we also got the hibernate or the OM support which is object relational mapping the web module of the spring framework can help us to write the web applications where spring MVC is one of the majorly used Frameworks in the market now so model view controller where model represents the data container view represents the UI or the presentation and controller represents the business logic as in seret now right so so spring MVC is one of the very important concern when it comes to develop the web applications and we got various web services coming out in this module itself let us move on to some annotations which are used in the spring configuration so guys there are various annotations now which are used in the spring framework now at theate required right so it’s like what is the input which is required Auto wiring for your dependency injection what happens pre- destroy what happens post construct right so before the object is finalized just after the object is constructed what is the resource what is the qualifier so these are some of the spring annotations which are used for the configuration purpose so what is Bean in Spring and what can be the different scopes of The Bean in the spring right so guys I’ll take up one very uh a basic example over here to mention this concept right so let us take one example so I got this spring demo available with me with all the jar files available out here we got this employe bean. XML file so just give me a moment right so all right so here you can see now we got this employee beam so this is one XML configuration for the spring framework so we got cod. ed. employee as a class right and here what I able to do is to define the property value tags for my B right in the employee. Java I can say it’s basically a bean or a pojo so what is a bean class Bean class is a class which will have the attributes along with the setter and the Getters right so all the setter get methods are also there in my client class what I’m going to do I’m just going to use this spring container and thereafter I will just extract my employee object right so just let me do this part all right so I got the reference of the employee bean. XML and in my class I got this mban one so I’ll just say m being one and thereafter I’ll do a ceso of M right so let’s try to run the code and you can see that the data over here is coming up as an ID name and salary right I have just over writed this two string method out here so along with this I’m also supposed to do a super do two string right I’ll do a back sln and a super do two string so now it will show me the data within the object as well as the reference variable m is pointing to the address it is showing me the address as well to the object now so the bean is extracted from the spring container right so there are various Scopes available now for example same MB one in my client if I try to get it again right so let us try to say get of bean again right as in M1 and M2 let us say this is M2 and this is M1 right so I will closely observe one difference I mean one similarity that every time when you request this guy get Bean for the mban one you are able to receive the reference to the same object scopes of the beam can be mentioned over here using attribute known as scope and here now I’m going to mention it as prototype you can see we got this guy as a prototype now when I run my code again you’ll find one significant difference that here the reference is coming out to be different it means now by default it was giving me the singl ton as a design pattern but when I change the scope to prototype every time I am requesting the object of M being one from the spring container it is now constructing a new object and returning it back to me so guys this is what we got as in what can be the scope of your being in the spring so inversion of control container can have various Scopes now single ton means only single object which is by default so prototype means you can have every time a new object request means one object per entire request session means one object per entire session and Global session means one object per entire Global session on an application Level so how is a being added to a spring application so guys you use this tag known as be you mention the ID and then you can have the properties as in key value pair right so what is the role of dispatcher serlet and context loader listener so guys dispatcher seret is acting as a front controller in the spring MVC so many times I will call it as a receptionist now so what happens any request when it’s going to land up to your web application so this guy dispatcher serlet will dispatch the request to the corresponding resource available on your web application so it’s it’s going to act as a receptionist in your program now whereas context load a listener it’s a listener which will give you the event call backs when the context will be loaded it’s like startup and shutdown of the web application context in the spring route now what is the difference between Constructor in injection and Setter injection so before you come up with the Constructor injection and the setter injection you must understand what is dependency injection so guys uh let us understand this flow once again I’m having one class as employe right and there is one more class known as address so employee can have the name employee can have some salary there will be definitely an employee ID and employee can also have an address right so I’ll just say an address to be as adrs so what we can do we can create one Constructor of an employee in this way right and here you can say Eid goes like 101 name goes like let’s say John salary goes like 30,000 and address goes like some new address right where address can have some address line then you can have some City you can have a state and lastly we can also have some kind of a zip code just mentioning some parameters over here now what will happen over the client part you will be writing employeee assign new employee so whenever you you are creating the object of employee this becomes the concept that the Constructor of the employe will create the object of the address we can see a significant dependency now when you are creating the object of employee within the Constructor of employee the object of address will be constructed we say this concept as high dependency or you can say we got a higher value of coupling now we need to reduce it right so you need to bring it to the lower level so you need to take it as a low coupling so what I will do I will not use this technique I will say let us create one more Constructor and pass the address as an input right and thereafter you can say address assign a or you can create a Setter you can say set address and you can say address and here you pass this guy so guys in these two approaches rather than having a single employee object you can now create an employee object you can create address objects separately right you need not to be dependent upon the employee object and later you can pass the address object or you can say employee e assign new employee and E dot set the address and you can pass this guy a so we want to reduce the dependency or we want to come down with the coupling parameter we created this logic out here so Setter injection and Constructor injection are the two terminologies linked up in order to justify these two terms now right so let us open up our presentation once again and look on to Constructor injection versus seter injection so there is no partial injection so seter injection can lead to partial injection here we need not to override the setter property but here the Constructor property in case both the things are defined so you can create new instance if any modification occurs so you need not to create any instance if there is a property change so better for too many properties better for few properties so guys depends upon your choice but Constructor and seter injection they are the two key Concepts to bring down your dependency to the lower levels now what is auto wiring in spring so many of times when we are writing this dependency injection programs you can perform these injection programs based on the names right for example you can mention this auto wirring tag and you can say by name so you need not to now write an explicit injection logic it will be mapped automatically for you so there are various modes through which you can have an auto wirring coming into action so no is the default mode it means you don’t specify the autowire it means here uh nothing is enabled so Auto wiring is not enabl so when you mention by name it means you take the seter method and you map the data corresponding to the name by type will use the type of the attribute and Constructor will inject on the basis of the Constructor so how can we handle any exceptions in Spring MBC framework right guys so there can be exceptions now when you are writing the program right so spring MVC framework can help us to achieve robust programming concept through these possible ways Number One controller based so you can define an exception hander method in your controller class itself you can have a global exception hander where exception handling is is a cross cutting concern to aop right and then you can have a Handler exception resolver so any spring Bean which you have declared in the dispatcher serlet application context that can Implement Handler exception resolver which can thereafter be used to intercept and process any exception which occurs in the MVC system and it is not handled by the controller part so you can use the various different concepts out here if you can see add the rate exception hander annotation so that you can specify that this view will be used to display some arror all right so some important annotations again in the spring framework guys we got at theate controller at theate path variable qualifi configuration scope request mapping response body auto wired service and and aspect right so all these annotations they are quite important Concepts and you must have a fair knowledge on all these right for example at theate Auto so either you can configure it in XML file or you can use annotations so XML files they come up with the inversion of control concept whereas annotations you need not to have XML files you can use them directly all right guys so lastly in the spring framework we can also have spring spring framework coming up with the database connectivity either through jdbc or through hibernate or any other framework now right so spring and hibernate they can work together we have some om modules available within the spring framework and we got an API known as hibernate template so if you want to come up with the spring and jdbc you got jdbc template API right so guys spring omm module will help us to integrate hibernate framework into a spring application and spring orm also provides the support so that you can use spring declarative transaction management you can use annotations and you can perform the actions now so now we will be on our last concept that’s like the hibernate which is the backend framework based on object relationship mapping right so guys let us see what and all we got in the hibernate now so the 44th question is what is hibernate hibernate is an OM which is object relationship mapping it’s a framework now where you just mention your Java object and you forget about your database tables so guys what we going to do we’re going to write down some mapping files as an XML configuration files where you will be Mapp that this attribute in my object in my class will be the column name in the respective relational table so hibernate provides a reference implementation of the jpa Java persistence API right and it makes a great choice as an OM tool where we got the benefits of lose coupling now I hope you got the meaning of loose coupling where dependency has been reduced to the maximum level so hibernate configures all the flexible and can be done from the XML configurations as well as through annotations programmatically right so it it provides us both the ways now so what can be the benefits with the hibernate framework so guys hibernate will eliminate all the boilerplate code whereas in the traditional approach you need to mention and write various code Snippets and you need to write the relationship mappings the cache management everything is uh you know eliminated when you use hybrid now so this framework will provides us uh XML support as in through configuration files and annotational support through jpa that’s like Java persistent apis now hibernate provides a very powerful uh language that’s like hql which is very much in line to SQL but you need not to learn it it’s more simpler than the SQL even now SQL itself is very simple language you got more simpler language than the SQL that’s like hql so guys it’s an open-source project from the red hat community and uh it is used worldwide and it’s very famous especially for any large Enterprise application your hibernate framework is one of the ideal choices now now any database vendor specific feature hibernate is suitable because we can also execute native SQL queries so hybern is not just that we can use its native apis and you can’t do anything out of the box you got to execute the SQL queries also with the hibernate one of the most significant features of the hibernate is the cach management so hibernate provides three levels of cash through which your performance of the database operations they’re going to get improved now so what is the architecture of hibernate guys so hibernate of having an architecture in a very uh simpler fashion guys we got a database on top of database we got various you know uh modules coming in for example Java transaction apis we got Java database connectivity and thereafter we got j& di that’s like Java naming and directory interfaces on top of it we got the hibernate apis so configuration API will read the XML configuration file and it will help us to create a session Factory session Factory will be used to create the session and session is one API which maintains and creates a connection with the database using the transaction API you can use the commit and roll back features and query API will help you to create one query and retrieve the data criteria is one API which will help you to mention the criteria for example you got restrictions to you know manage for example greater than less than all equal to so all these are criterias when you are trying to retrieve the data in the Java application you just write a pojo class you just write a bean and you give this object to the hibernate and hibernate API they’re going to manage everything for you all right we got the get method and the load method in order to to perform the retrieve operation so let’s see the differences let’s say we we don’t have a record available in the database so load method will show an exception that’s like object not found exception whereas the get method will return a null as in the object is not found so guys get method will always hit the database whereas load method will not hit the database right in case it’s not there and you’re going to get get a real object not a proxy object whereas load will return you a proxy object so get should be used if you are not sure about the existence of instance now so let’s say that the record is existing or not I don’t know so you use get if you are sure about whatever you are going to extract from the database it is existing you can use the load method so there are now significant differences between hibernate and jdbc guys this is one of um the major query between you know as in the part of interviews so why hibernate and why not jdbc what are the differences what are the advantages that you should be opting for hibernate now if you’re writing a very small app right you need not to go on the hibernate level hibernate level is required when you’re writing an Enterprise app right where you need to save the time and you don’t want to do a rework and there are various other differences so let’s have a look onto that now so guys first of all you need to write lot of code when it comes to jdbc whereas hibernate you have very limited instructions to mention right hnet supports all the association inheritance collection mappings where in case of jdbc APA you need to write all those Logics so one to one one to many many to many all these mappings they are available as a support in the hibernate hibernate will also give you the transaction management implicitly whereas in jdbc again you need to manage that part Now jdbc API they will throw SQL exception right so it’s a checked exception so we need to write lot of TR catch block code when you are using this uh jdbc but hibernate will internally manage this uh TR catch block for you we got hql which is objectoriented programming whereas jdbc you need to write the native SQL queries hibernate will automatically give you the cash management for better performance in three levels of cash whereas jdbc you need to manage it yourself so by default hibernate’s performance is higher as compared to the jdbc part so lastly hibernate will provide an option where we can create the database and the tables too but for the jdbc these EX existence should be there before you dump the data other than that one of the very significant feature why hybernate over jdbc is if you want to switch from one database to the other database it’s going to be very complicated with the jdbc but in case of hibernate we got a configuration file you just need to change the parameters in the configuration file and you will be able to shift from Oracle to my SQL or any other database to any other database of your choice and with this we come to an end to this Java full course if you enjoyed listening to this full course please be kind enough to like it and you can comment on any of your doubts and queries we will reply to them at the earliest and do look up for more videos and playlist And subscribe to the edas YouTube channel to learn more thank you for watching and happy learning

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!








