[Go to site: main page, start]

0% found this document useful (0 votes)
5 views96 pages

Java Notes

The document provides an overview of key concepts in Java programming, including the differences between classes and objects, method overriding and overloading, polymorphism, exception handling, and inheritance types. It explains various programming principles such as abstraction, user-defined exceptions, and the distinction between checked and unchecked exceptions. Additionally, it covers the Java Virtual Machine's (JVM) exception handling process and includes code examples to illustrate these concepts.

Uploaded by

Tanureet Kaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
5 views96 pages

Java Notes

The document provides an overview of key concepts in Java programming, including the differences between classes and objects, method overriding and overloading, polymorphism, exception handling, and inheritance types. It explains various programming principles such as abstraction, user-defined exceptions, and the distinction between checked and unchecked exceptions. Additionally, it covers the Java Virtual Machine's (JVM) exception handling process and includes code examples to illustrate these concepts.

Uploaded by

Tanureet Kaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
UNIT:1 NOTES 1. Difference between class and object with code. Class Object Ablueprint or template Areal instance of the class Defines properties and methods Uses properties and methods: No memory is allocated unt an objects created Occupies memory Logical entity Physical entity Class: class Car { String color; int model; void start() { [Link]("Car is starting..."); Object: Car myCar = new Car(); [Link] = “Red”; [Link] = 2023; [Link](); 2. Difference between method overriding and overloading Definition ‘Same method name, diferent Same method signature redefined in ld cass parameters lasses Same cass Parent and child classes Polymorphism Compie-time Runtime * Method Overloading: class Deno { void show(int a) ( [Link](“int*); } void show(String a) { [Link] .printin(*string class Test { public static void main(String) args) ( Demo d = new Demo(); .show( 1 [Link]("Helle"); // String * Method overriding: clase aniesl ( void sound() { [Link]("Asinal makes sound"); > » clase Dog extends Animal ¢ Poverride void € Syaten-out-printin(e © 8)5 pumite or ¢ Public static void main(Stringt} eres) ¢ marnowseds . Runtime polymorphism: wa Animal ( void sound) { [Link]-printIn(“Animal sound"); d ? class Dog extends Animal ( override void sound() { [Link] -println("Oog berks” y public cle 2 { public static void main(stringl] args) ( Animel @ = new 00g(); // Runtime polymorphism @-sound( Output: Oog barks , + 4. Difference between throw and throws. Feature veo Use To throw an exception manually Place Inside a method Number of exceptions Can throw only one exception Type Used to create exceptions - Throw: To declare possible exceptions tn method declaration (Can declare multiple exceptions Used to propagate exceptions class Test ¢ wold checkAge(int age) { if (oe < 18) ( throw now Aritheetictxception(“Mot eligible for vote"); ? [Link]("Eligible for vote"); , public static void wsin(String[} eres) ( news Tost().checksge(35)5 class Test { void readFile() throws IOException { throw new IOException("File not found”); public static void main(String[] args) throws IOException { new Test()-readFile(); 5. What is the inheritance and types. Type Description Single (One child inherits from one parent Multiple One child inherits from multiple parents (via interface) Multilevel Chain of inheritance Hierarchical ‘One parent multiple children Hybrid Combination of above types (Cnt extends Parent class € implements A, 8 Grandparent + Parent = Chile Cntdt, nila extends Parent ‘Class + mstiple interfaces 1. Multiple Inheritance ‘+ Multiple inheritance means a class inherits from more than one parent class. ‘+ Not allowed in Java with classes, Reason + Toavoid the “Diamond Problem” (ambiguity problem). aed interface: neem emeice s and hybrid inheritance. “2 1) Single ‘© Single inheritance: class Parent { void show() { [Link](“Parent class”); } class Child extends Parent { void display() { [Link]("Child class"); } public class Test { public static void main(String[] args) { Child ¢ = new Child(); [Link]()s // Parent method ¢.display(); y . Multiple inheritance: interface 4 { woid showh(); d interface 8 { void show8()5 , class C implements A, B { public void showl() { [Link]("Interface A"); } public void show8() { [Link]("Interface 8"); } , public class Test { public static void main(Stringl] args) ( C obj = new CC); obj. shows(); obj. show8(); class GrandParent { void show() { [Link]("GrandParent"); } class Parent extends GrandParent { } class Child extends Parent { } public class Test { public static void main(String{] args) { Child ¢ = new ChildQ)s .show(); // Inherited from GrandParent « hirerarical inheritance: class Parent { void show() { [Link]("Parent”); } class Childi extends Parent { } class Child2 extends Parent { } public class Test { public static void main(String{] args) { Child c1 = new Childi(); Child2 c2 = new Child2(); 1. show(); 2. show() 5 - Hybrid inhertance: interface A { void a(); } interface B { void b(); } class Parent { void show() { [Link](“Parent”); } } class Child extends Parent implements A, B { public void a() { [Link]("Interface A"); } public void b() { [Link](“Interface 6"); } public class Test { public static void main(String{] args) { Child c = new Child(); ¢.show(); <.aQ)i €-b0; 6. What is abstraction and types: Abstraction in Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. Abstraction lets you focus on what the object docs instead of how it does it, Ways to achieve Abstraction ‘There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%) ‘Abstract Class Imertace 6 Feature Keyword Methods Can have absract + corcrete Abstract by default ova 8+ can have defn static Muttigle ‘Variables tohertance XK Not alowed ¥ Alowed ve multiple interfaces: Can have instance war acles Only public static final constants before Java a abstract class Vehicle { abstract void start(); // abstroct method void stop() { // concrete method [Link]("Vehicle stopped"); lass Car extends Vehicle { void start() { [Link]("Car started"); public class Test { public static void main(String{] orgs) { Vehicle v = new Car(); vestart(); v.-stop(); interface Aninal { veld sound()s // abstrect method ) class 00g implements Animal { public void sound() { [Link]("oog bark ) public class Test ¢ public static void mein(Stringl] ones) { Animal 2 = new Dogs [Link] (@ Rules of Abstract Class in Java 1. Declared with abstract keyword + Tomoke 9 cass abstract use the abstract keyword before lass i 0 Conycose ntact clans Vehicle 2. Cannot be instantiated directly * You cannot create an object of an abstract class. pe 0 copyeose Vt Trem Vote(s // IE Compile tine 3. Con have abstract and non-abstract methods + Abstract methods: no body. only signature + Non-abstract methods: with body 7. What is the exception in java and types. (© What is an Exception in Java? An exception s an unexpected event or error thet occurs during the execution of 9 program which disrupts the normal New ifthe pron 2 tn tava oocytes ate aber devil om thee ca Set ag Pe op 2 etl oeicptionn propel eases program dee net raat Oumae Checked Kaception Uncheched tcepton o Laceptiors thet Ove Comper forces you to handle either Ceceptore (al the compiler dows not (by Uny-cateh oF by deciaring them with thew. force you to handle: they can cerur at tention: When Occurs During compile-time ‘Dus rurine. amples asia. Sam ainiaertaantin, serio. Handling Requirement — Must be handled or declared. Optional to handle - Checked Exception: no Gowan Inert [Link].*s Public class Checkedtuarple { public static void saie(String{} args) { wrt Filenaader file = raw Filetoater(*tact txt"); } catch (FiletotFoundtxception #) ( [Link](*File nat found!"); , ? Gi Explanation: FiletiotFoudéxceotion 's 2 checked exception, so the compiler forces us to handle it with ttry-cotch- . Unchecked exception: public clas Unchachedtuaaple { sublic static veld nakn(stringl] anes) ( ot LY enmars = (5 25 ynten. cut. printle(mabersti1); // Amey nies ovt of bount ? © Explanation. areayincexouoftountstaception i an unchecked exception so the compiler doesn't force handling i wal throw an error at runtime ‘Aspect tror Definition Serious problems that applications usually cannot handle Cause Usually caused by JVM issues ke memory overflow. stack overflow. Handling Cannot be handled effectively by the pegem. Examples OutofMesoryError . Stackverflovérror ‘Exception: Exception Example (Handled) joa public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / } catch (ArithmeticException e) { Problems that applications can handle using Usually caused by program logic or runtime ‘conditions like fite not found, division by Can be handled using try-eatch or // Causes ArithmeticException [Link](“Exception caught: “ + e); public class ErrorExample { public static void main(String[] args) { // Causes StackOverflowError recursiveMethod(); static void recursiveMethod() { recursiveMethod(); // infinite recursion ~ } 8. Difference between try and catch. Here's a simple explanation of the difference between try and catch in Java: wy catch Contains the coke tha might throw an andies the exception theowm by the try ‘exception. tock Must wrap code that can fail. Mast fotow a try block to catch a specific exception Executed first fan exception occurs, Executed only if an exception occurs in the ‘control passes 10 catch try Block, Ppa wy Cs comes) public class Finalexample { public id main(stringt} pal tot number = [Link]-println("Final number: "+ number); ery { Ant result = number / @; es Arithmeticéxc } catch (arithmeticexception e) ( [Link]("Exception caught: "+ #)s ) natty ¢ [Link](“Finally block always executes"); > Demo obj = new Demo{): obj = eul System. 205 9, What is the user defined exception and types. In Java, a user-defined exception is an exception that is created by the programmer to represent specific error conditions that are not covered by Java's builtin exceptions It helps make your code more readable and maintainable. 1. Checked User-Defined Exception ‘Definition: Must be declared or handled by the programmer. ‘© Inheritance: Extends the Exception class (but not Runtimetxception ) © beample: i copy cote Claas menechestxception extends Exception ( ychechedtaception(String message) ( per(message); ) ) Usage: 2. Unchecked User-Defined Exception ‘© Definition: Optional to handle; occurs at runtime. © Inheritance: Extends the RuntineException class. + Bample: pe Copy code class nyuncheckedtxception extends Runtinetxception { myuncheckedexception(String message) ( super(message); ) Checked User-Defined Exception Example ive Create user-defined exception class MyException extends Exception { MyException(string message) { super(message); public class Test { static void checkige(int age) throws MyException { Af (age < 18) { throw new MyException(“Age must be 18 or above"); } else { [Link]( “welcome public static void main(String() args) { try { checkage(25) ; [Link]("Caught exception: ” + [Link]()); [Link] is the custom exception. Acustom exception in Java is another term for a user-defined exception—it's an exception that you create to represent specific errors in your application that aren't covered by Java's built-in exceptions. User define code example. [Link] is the exception handling. Exception handling in Java is mechanism to handle runtime errors s0 that the normal flow ofthe program is not disrupted It alows a program to catch exceptions, take appropriate action and continue execution, Inttead of caching Exception Handling Keywords in Java Keyword Purpose ty Contains code that might throw an exception eaten Handles the exception thrown by try fnanay Code that always executes after try-catch (optional) tro Used to explicitly throw an exception trons Declares exceptions that a method can throw [Link] JVM handles an exception. Exception Handling Process in JVM When an exception occurs, the Java Virtual Machine (JVM) follows these steps: 41. Exception Occurs © JVN detects an abnormal event (ike Aritheet icException, WallPointerException ) during program execution. 2, Search for a Handler * JVM looks fora matching catch block in the current method. + tt searches from the innermost try-catch block outward. 3. If Handler Found © The JVM transfers control to the catch block. # The catch block executes, and program continues after the try-catch-finally 4, No Handler Found in Method ‘+ JVM propagates the exception to the caller method (the method that called the current method). Flow Example in Code (String[} args) { Features roi Java Portable Coe is platform-Gependent. Java is platform-independent. | coos may end tan prop. ] ‘oes mit wa freon propane veda window, web-based, erternrise and mobile applications. ‘C++ was designed for systems and Java was designed and created as an interpreter for printing systems but -toplcations programming, was an later extended as a sueport network computing. It was designed with 2 (etenson of C programming language, ‘eal of being easy to use and accesible to a broader audience. Co supports the pot statement. Jaa doesn't support the goto statement. C++ supports mito inbertance. {Jina doesn't support mafic inheritance through das. It canbe achieved ‘by interfaces in java. Coe supports eperator ovetoaing. Jina doesn't surport operator ovetouding. 1. Identifier '* Definition: An identifier isthe name given to variables, classes, methods, or objects in Java. 1+ Rules for Wdentifir: 11. Must begin with a letter, $..0r _ (cannot start with a digit 2. Can contain letters. digits, $, and 3. Cannot be a keyword. 4 Case-sensive (m/Var and pyar are diferent). Example va © comrade Sat age = 25; // ‘age’ 4s on Maentifier ‘ering name « "Dobe"; // “name(s on ‘dent fler 2. Keyword 1 Definition: & heyword it reserved word in inca with a special meaning. cannot be used at an enter (+ example Keywords: tnt. clast. 21, sis, try. eaten. for, watts, return 3. Token + Definition: The smallest element in a Java program that has meaning is called a token. ‘Types of Tokens in Java: 1. Keywords - reserved words (nt. class. if, etc) 2. Identifiers ~ names of variables, methods, classes 3. Literals ~ constant values (10, “Hello” ) 4. Operators — symbols for operations (+, =. *. /, =, ==) ‘5. Separators (or Punctuation) ~ symbols to separate statements (3. (), O. +) Example of Tokens in Java jue Orem public class Test (| // ‘public’, ‘class’ = keywords: ‘Test’ = identifier public static void main(string{] args) { // tokens: identifiers, keywords, separators int 0+ 10; // “int* = keyword, ‘a’ = identifier, “10° = Literal, ‘=" = operc [Link]("Wello"); // tohens: identifiers, Literals, separators ? Feature Primitive Data Types Non-Primitive Data Types o Definition But.n base data types prowded by lava, Datatypes crested by the programmer or rovided by Iva APL Examples Ant. feet. devote. char. ostean String. Array. Chass, Interface size Fured sie (depends on ype e9. int'=4 rable sie: depends on the object tes) Default Valve Each type has a deat value (eg. Sint <0, Default is at Dostean alse) 11. What is the access modifiers in java. In Jovan acess modifi keyword that defines the ws (access level of clases methods and ‘arabes controls which other classes can acess them ‘Types of Access Modifiers in Java AeconMotar Ca Pacts Sudan ayn) Onion pate ’ x % x Acceso in tue as. ast iomosten ’ = x eesti wt ee paar cy rotted . ’ x cesta tae page dinates iwva public class Example { private int a = 10; // accessible only in this class int b = 20; // default access, accessible in same packag protected int ¢ = 38; // accessible in package & subclasses public int d = 40; // accessible from anywhere public void display() { [Link](a + ob yo et oe d)y Can a class be static in Javi ‘The answer is Yes, some classes can be made static in Java. Java supports Static Instance Variables Static Methods, Static Block Static Classes 1. private ‘© Definition: An access modifier that restricts visibility to within the same class only ‘Usage: Used for fields, methods, constructors. + Bample: a © copy cose class example { peivate int data = 19; // accessible on 1 Exanpte > 2. static + Definition: & keyword used to define class-level members (variables, methods, nested classes), + Key Points: Belongs to the class, not the object. + Can be accessed without creating an object. + example: = 0 capycate class example ( stale Ant count = #2 we by ott ot state wots sou) ( [Link]("Cout: ~ + count): ? > 3. Accessing Outer Class from Inner Class © Aninner class can access alll members (even private) of its outer class. “+ Use uterctassnane this if there is ambiguity Example, ~ © Copy cote lass outer { private int mum = 30; class Inner ( wold eisplay() { [Link]( "Outer ram: [Link]. peintln( “outer via this: oo) ess private mente © 6 Outer [Link]) 5 ) public class Test ( public static void main(Stringl} ones) { [Link] Sener = new Outer().new Inner¢); inner .aisplay()s , [Link] is the encapsulation. Encapsulation in Java is the process of wrapping data (variables) and methods that operate on that data into a single unit (class) and restricting direct access to some of the object's components. It's a key principle of COP that helps protect data and achieve data hiding. Key Points: (© Use private variables to hide data. © Provide public getter and setter methods to access or modify the data. class Person { private String name; public void setName(String n) { name =n; } public String gethame() { return name; } public class Test { public static vold main(stringl] args) { Person p = new Person(); p-setName("John"); [Link]([Link]()); Data Privacy ‘ields in a class are made private to prevent it to bea ‘lass. *rivate fields can be accessed only by using the publi t leads to Data Hiding or Privacy incapsulated data is accessed using the “*Accessor (g« “Mutator (setter)” methods. \ccessors — Methods to retrieve the hidden data. Mlutators — Methods to change hidden data. Hello Avcl"— ————— SAHUDO’ Poofoca) driver Ward Chterd Hairs _s = Serwen ve) Pe fo. . dof VOId 710. Sa y Q Ee iS i e r EY 6 OOF NOs blizavon of Chu: € fangs progam Ci if = - 1 Aufoboxes Object *369- é | fay i | wha is multi Hit ead 19 ALLE Yyrich zation: Le Mult threac g:-' | WceALs My Sach fant0 FSunpyog xan Gatlod throad. Hhteaal O/'ah4 S fs Ls Weight od] : - mproved phonhe O 2 2) Rorpamnnrive O [Main eee i fee, [| \. FP ia oe "Witaate Rinna Hyee Glas enctemds Thrag Vord maim CL. wl), = Win: HEN LY OX ke1co pare PAGE No a Byte SIO am: - | hamdic binaxy data - — = Keao ot g LS f Blaucs ) Gla +)'O fowge~ , gubheral + nut FxO Bis Mp rcol ou est nae acest Ate Clauss Objes_inhus Saw A obfes Oupuk straw pond 2ation J No rer bt 1. Whatis the serviets and lifecycle. ‘What is a Serviet? ‘A Servlet is a Java program that runs on a server and handles requests and responses in a web application. {tis part of Java EE (Jakarta EE) and is mainly used to extend the capabilities of servers, especially for web- ‘based applications, ‘+ Servlets are managed by a Servlet Container (like Apache Tomcat). They can process HTTP requests (like GET, POST) and generate dynamic content (like HTML, JSON, XxMy), ‘Types of Serviets “Servens can be classed two man es aed on functionality 73 based on the APY they ampiement 1 Based on APVimpiementation 1. Generic Serviet © Partof the [Link] package. © brtends Jovan. tarvlat Canartctaretet cans. ‘© Canhandle any protocol (not limited to HTTP, © Abatact cans, you need to override the service() method. © Example: O cooyose pablic class Myserviet extends Genericserelet ( ublie vols servise(Servlettinguest request, ServletRespamse response) thraus Servlet response. getietter() printin( Mello from GenericServlet"}s ? 2. HTTP Servlet 1+ Part of the Javan-terviet htt package © Extends. [Link] clas ‘+ Specifically designed for HTTP requests, + Commonty used metho: © GeSekC), — handles GET requests + debout()) — handles POST requests enue). saoanetes)) — handle other HTTP methods © Geampte: com vote public class myimapserviee extends Metpservie® ( protected wois doure (wttpservietamquest request, wttesersletiasponse response) throat respense-grturiter().grimeinC melo from MIP Serwiet")s > Servlet Architecture jae import [Link]." import [Link]. Import [Link].*; public class Hel Let extends { protected void (uttpServietRequest request, WetpServietResponse response) thro ServletException, 10€xception { response. setContentType(“text/ht PrintWriter out = [Link](); [Link]("chi >Hello World from Serviet” Lifecycle of a Servie [Link] serviet class [Link] serviet instance [Link] the init{-) method [Link] the service(-,-) method [Link] the destroy{) method 1itecture Overview -serviet and ™ | face Server Side Web Component + Awob component is @ software entity that runs on a web server Provides it with the capabilites needed for dynamically handling client requests and ‘generating web presentation content + The J2EE specification defines two types of web components ~ Serviets — Java Server Pages(JSPs) oer atte —— 0 Ae 8 fa antes ServietRequest Interface in Java The Serviettequest interface is part of the [Link] package. It provides a way for a servlet to read client request data sod eteract with the chent n 9 protocol independent way, In simpler words: it represents the client's request to the server. Key Points ‘+ iisimplemented by the serviet container (ike Tomcat) + Used to get ‘© Cent information Request parameters = Atwibutes + lnput stream of request data ‘+ Protocot-independent (not tied to HTP: for HTT, MetpservletRequest extends ‘Common Methods of ServietRequest Method ercPorameter(string same) errs the value ofa request parameter as a String ertrarenetervnies (string sane) Retrrs multe vahes ofa parameter asa String) lertaterinceastring same) Seruran bye stored at an tr bute nthe request import [Link]"; Import [Link].*; Amport [Link]. public class RequestExanpleserviet extends HttpServiet { protected void doGet (HttpServietRequest request, HttpServietResponse response) throws ServietException, 10Exception { response. setContentType("text/html”); Printwriter out = [Link](); // Getting request parameter ‘String name = request .getParaneter(“name"); Sf (name == ull) { name = “Guest™; // Getting client info String clientIP = [Link](); ‘[Link]("

Hello, ” + name + “!

"); ‘[Link](""); ServietResponse Interface in Java The Serviettesponse interface is part of the [Link]. package. t provides a way fora serviet to send data back to the cient. {In simple terms: it represents the response from the serviet to the client. 2 It kcimnlamanted bu the servet enntaines Nike Tameat import [Link].*; import [Link].*; Amport [Link].*; public class ResponsetxampleServiet extends HttpServiet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response. setContentType("text/html”); // write response Printhiriter out = [Link](); [Link]("Hello from ServletResponse!"); [Link](“

This is a simple response example.

"); import [Link].*; import [Link].*; import [Link].*; public class ResponseExampleServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) ‘throws ServletException, IOException { // Set response content type response. setContentType(“text/html”); // trite response Printhriter out = [Link](); out .println("Hello from ServletResponse! "); [Link]("

This is a simple response example.

"); } [Link](“

User List

"); [Link](™" + [Link]("id") + “"); out .printin(""); out .printin(""); [Link]("™); > out .printin("
" + [Link](“name™) + “" + [Link](“email") + “
"); zetch (Exception e) { [Link]("

Error: " + [Link]() + “

")5 finally { // 6. Close resources try { if (rs t= null) [Link](); } catch (Exception e) {} try { if (stmt t= null) [Link](); } catch (Exception e) {} try { if (conn t= null) [Link](); } catch (Exception e) {} Steps to Use JDBC in a Serviet 1. Load JDBC Driver 2. Establish Database Connection 3. Create Statement / PreparedStatement 4. Execute Query / Update 5. Process ResultSet (for queries) 6. Close Connection and Resources Example: Simple Serviet Connecting to MySQL = CO Com coe import [Link]. public class 306CDemoServiet extends HttpServiet { Protected void doGet(HttpServletRequest request, HtteServietResponse response) ‘throws ServietException, IOException ( 1 Set response type [Link]("text/ntmi"); Printwriter out = [Link](); // Database varioples String uel = “Jodc:mysal://localhost :3306/testdd"; // 0B URL String user = "root"; // 08 username String password = “password”; // 08 possword 8:34 @ a: RF all F 34% ChatGPT : ee [Link] < Qo: @ ChatGPT ~ @ 1. errorPage Attribute (Page Directive) Yeh batata hai ki agar current JSP page mein error ho jaye, to kaunsa JSP page error ko handle karega. Example: isp © Copy code Easy Samajh: « Agar iss page mein exception aaye — user automatically [Link] par chala jayega. 2. isErrorPage Attribute (Page Directive) Yeh batata hai ki yeh JSP page ek error-handling page hai. Vv Agar aap error handle karna chahte ho to aapko + Add) Ask anything ChatGPT can make mistakes. Check important info. See Cookie Preferences. 835 BGM: ChatGPT : ee [Link] < Qo: G@_ ChatGPT ~ @ isp © Copy code <%@ page isErrorPage="true" %> Easy Samajh: « Isse JSP ko pata chalta hai ki yeh page errors ko show karega. « Aise page ke andar aap exception object ko directly use kar sakte ho. Example: isp © Copy code Exception occurred: <%= [Link] ye Simple Flow Samajh Lo: Normal page: jsp Vv © Copy code + Add) Ask anything © ChatGPT can make mistakes. Check important info. See Cookie Preferences. ChatGPT . xv [Link] < Q : @ ChatGPT @ Define the servlet context and page context in java a Yeh dono concepts ko simple, easy language mein samajhte hain: 1. ServletContext ServletContext ek global information store jaisa hota hai jo poori web application ke liye common hota @. Easy Definition: ServietContext ek aisa object hota hai jisme aap application-level information rakh sakte ho ya use kar sakte ho. Iska use poori web application ke saare servlets/JSPs kar sakte hain. Important Points: + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefers 836 Bee: ChatGPT : xv [Link] < Qo: G ChatGPT ~ qd © xml © Copy code dbName studentDB Servlet java © Copy code ServletContext ctx = getServletContext(); String db = [Link]("dbName" 2. PageContext (JSP) PageContext ek JSP-specific object hota hai, jo sirf usi JSP page ke andar valid hota hai. Easy Definition: PageContext ek aisa obi~ + hai jo current JSP page ke information ko huid karta hai, jaise: + Add Ask anything 6 ChatGPT can make mistakes. Check important info. See Cookie Preferences. ChatGPT [Link] x v G@ ChatGPT ~ ° config * etc. Yeh sab objects ko ek hi jagah se access karne ka shortcut deta hai. Important Points: ¢ Scope limited to current JSP page « JSP ke saare implicit objects provide karta hai « Page-level information store karne ke liye use hota hai Simple Example (JSP): Isp © Copy code <% [Link]("name", "Rah String n = (String) [Link] [Link](n); v + Niffaranra (Nna | ina) + Add Ask anything Ciei0T can eran foletalen. Checks lieealtant Wile Gen Conkle 836 BESO: Rez all 834% ChatGPT : ee [Link] < Qo: @ ChatGPt v @ String n = (String) pagec © Cory code ¢ [Link](n); % yr Difference (One Line) ServletContext PageContext Puri application ke liye Sirf current JSP page ke common liye Servlets + JSP dono use Sirf JSP mein use hota kar sakte Application-level data Page-level data store store Agar chaho to main iska diagram ya real-life example bhi explain kar Te hoon! oO + Add) Ask anything © ChatGPT can make mistakes. Check important info. See Cookie Preferences. a45 . RMF ul 832% ChatGPT : v 3 7 [Link] < A: @ ChatGPT v qd @ directive elements, along with comprehensive examples and analysis of how they work behind the scenes and influence the architecture of Java web applications. yy 1. What is JSP (Java Server Page)? JSP is a server-side technology where HTML and Java code coexist in a single file. It is essentially a template engine. When a JSP file is requested: v JSP | Servlet Response The server translates JSP into a Java Servlet class, compiles it, executes it, and sends the output to the browser. Understanding JSP = Understanding how it becomes a Servlet. Vv + Add Ask anything a ChatGPT can make mistakes. Check important info. See Cookie Prefers ChatGPT . mee logic Expression v 2.1 Scriptlet — - > Allows embedding raw Java code in JSP. + Add) Ask anything a ChatGPT can make mistakes. Check important info. See Cookie Preferences. 845 BEB: ChatGPT : mn or < A} @ ChatGPT v @ v 2.1 Scriptlet— <% ... %> Allows embedding raw Java code in JSP. isp G) Copy code <% String user = [Link]("u if(user == null) user = "Guest"; %>

Welcome <%= user %>

©, Behind the scenes Scriptlets are inserted inside the JSP-generated servlet’s service() method: © Copy code Java out .write("

Welcome " + user + "

" ! Critical Analysis « Encourages mixing business logic + + Add Ask anything a ChatGPT can make mistakes. Check important info. See Cookie Preferences. 345 BESS: RRA xv ChatGPT < Qa : [Link] @ ChatGPT v qd @ * Modern Java trameworks avoid it (Spring MVC, JSF, Thymeleaf) v 2.2 Expression Element — <%= ... %> Prints a value directly to output. isp © Copy code

Server time: <%= new [Link]() Q, How it's compiled The expression becomes: java O Copy code [Link](new [Link]()); v Benefit: ¢ Clean way to output variables Vv ! Drawback: + Add Ask anything a ChatGPT can make mistakes. Check important info. See Cookie Prefer 845 BEES: ChatGPT [Link] x Vv G@ ChatGPT ~ V 2.3 Declaration Element — <%! %> Declares methods or fields that become part of the Servlet class, outside the service method. isp © Copy code <%! int counter = 0; int increment() { return ++counter; ‘%>

Visitor count: <%= increment() %>

Q, Behind the scenes This becomes a class-level field: java v © Copy code + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefer ChatGPT : mee Hello <%= name %>

Last visit: <%= [Link]("

Application started: <%= application.g Q. Critical Analysis ¢ Implicit objects simplify interaction with servlet API ¢ They encourage logic in the view, which modern architectures avoid ¢ session and application can cause memory issues if misused * out can cause bu,“ overflow if used incorrectly + Add Ask anything 8 ChatGPT can make mistakes. Check important info. See Cookie Preferences 846 BEES: ChatGPT : a oa G@ ChatGPT ~ qd © Servlet. There are 3 directive types: Directive Usage Purpose page <%#@ page ... Defines page-level e settings include + Add Ask anything 36 ChatGPT can make mistakes. Check important info. See Cookie Preferences. 846 BEES: ChatGPT [Link] x Vv G@ ChatGPT ~ v 4.1 page directive Used for configuration. isp © Copy code <%@ page import="[Link]" %> <%@ page contentType="text/html; charset=U <%@ page errorPage="[Link]" %> Q Critical Analysis © Powerful but can make JSP heavy « Excessive imports slow down translation ¢ Often replaced by tag libraries (JSTL) v 4.2 include directive — Static include isp © Copy code <#@ include file="[Link]" %> This is inserted before « J) pilation — fast but not dynamic. + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefer WRF ll 832% xv ChatGPT < Qa : [Link] @ ChatGPT v qd @ v 4.3 taglib directive Used to load JSTL or custom tag libraries. jsp © Copy code <%@ taglib uri="[Link] Welcome ${user} Q Critical Analysis ¢ Best approach: encourages separation of concerns ¢ Uses EL (Expression Language), replacing scriptlets ¢ Safe, readable, MVC-friendly ¢ Modern JSP relies heavily on taglibs v . yy 5. Integratea Comprehensive FE : + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefers 846 BEES: xv ChatGPT < Qa : [Link] @ ChatGPT v qd @ JSP Example: [Link] isp © Copy code <%@ page import="[Link]" %> <%@ include file="[Link]" %> <%@ taglib uri="[Link]

User Dashboard

<% String user = (String) [Link] if (user == null) { response. sendRedirect("login. jsp" return; >

Welcome: <%= user %>

Server Time: ae Date() %>

trang 1airsuvame Due : Ce di [Link] = firs © Cory code [Link] = lastName; [Link] = email; ye How Hibernate Maps This Entity Internally Hibernate generates SQL like: sql © Copy code Get smarter responses, upload files and images, and more. Sign up for free ++ Add < anything ChatGPT can make mistakes. Check important info. See Cookie Preferences. 855 & ChatGPT . a [Link] < Q ia @ ChatGPT v q@ @ sql © Copy code create table students ( id bigint not null, first_name varchar(60) not null, last_name varchar(60) not null, email varchar(255), primary key (id) oF create sequence hibernate_sequence start Hibernate converts objects —. SQL via metadata from these annotations. a~* cA 8 Get smarter responses, upload files and images, and more. Sign up for free Vv + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Preferences. xv ChatGPT < Qa : [Link] @ ChatGPT v qd @ * database-specific optimizations « bulk operations ©, 6. Features Comparison Table Feature HQL. sQL o Uses entities v Yes x No Uses x No v Yes tables/columns Database- v Yes x No independent Object-oriented v Yes x No Supports Hibernate ——- Yes Limited caching Supports native DB Limited v Full functions Complex queries Meum Strong + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefer 859 BEES: xv ChatGPT < Qa : [Link] @ ChatGPT v qd @ Q. 1. Definition HQL (Hibernate Query Language) ¢ An object-oriented query language. * Queries operate on entities, their fields, and relationships, not directly on tables. ¢ Database-independent (portable across DB vendors). SQL (Structured Query Language) « Arelational query language. * Queries operate on tables, columns, rows, and joins. ¢ Database-specific (different SQL dialects per DB). ©, 2. Syntax Differences HQL Example Java © Copy code + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefers 8:59 xv ChatGPT <<: [Link] @ ChatGPt v qd é Q. 2. Syntax Differences HQL Example java © Copy code String hql = "FROM Employee e WHERE [Link] List list = [Link] .setParamete ceeeet ye « Uses class names ( Employee ) « Uses property names ( department .name ) ¢ No need to write joins manually—Hibernate resolves them using mappings. SQL Example Java © Copy code String sql = "SELECT * FROM employee e " "JOIN department d ON [Link] "WHERE [Link] = 2"; List row [Link] .setParamete Victey- + Add ) Ask anything @ ChatGPT can make mistakes. Check important info. See Cookie Preferences, 8:59 @- xv ChatGPT [Link] G@ ChatGPT ~ ©. 3. Return Types Hau Returns mapped Java entities: java © Copy code List employees = [Link](); SQL Returns: * raw Object[] rows * or scalar values * or entities with extra configuration java © Copy code List data = [Link](); Vv OA Daetahilinn + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefer 8:59 ° Wk F all 8 30% ChatGPT : arene [Link] < A: G@ ChatGPT ~ © ¢ Database-agnostic ¢ Hibernate translates HQL — SQL for the specific DB dialect ¢ Easier for multi-DB applications SQL * Database-dependent ¢ Must adjust queries if switching from MySQL ~ Oracle -. PostgreSQL Q. 5. Performance HQL « Uses Hibernate caching ¢ Supports lazy loading * Typically better for object-centric operations SQL * Can be faster for: * complex joins J * database-specific optimizations + Add Ask anything ChatGPT can make mistakes. Check important info. See Cookie Prefers 9:03 BSE: 29% 4 Google 6 Q > whatis the spring framew.. GY @ Ml Videos Images Shopping Short videos +> AlOverview eet fé 6 4) Listen The Spring Framework is an open-source, somprehensive framework for building anterprise-level Java applications. It aims to simplify the development process by providing a nodular and flexible architecture that addresses sommon challenges in enterprise Java Show more V Spring Framework Software 1, Introduction to Spring cP Framework Images may be subject to copyright. Learn More « Share DQ Save j Spring — 1. Introduction to Spring ... So 8 BMC Software The Spring Framework B... Bi Overview of Spring Framework ZA comprehensive framework or enterise Jove applications Provides support for developing Java-based applications with features like Dependency Injection, Aspect-Oriented Programming (AOP), et. ¥ Keymodules: Spring Core, Spring MVC, Spring Boot, Spring Cato spring Bi Benefits of Spring Framework ieee (2) eer Advantages of Spring Framework Lies etter) A Disadvantages of Spring Framework ra) ea) o eee Ceri Writing a Basic Spring App Let's create a simple Spring application + Create a configuration file applicationContextxmi) + Define a simple java bean, + Load the Bean using spring container + Runthe application Sample Spring Application Code Java Bean (HelloWorld java) SpringConfiguration([Link]) Running Spring Application Code Create a Main java file Run Main java and see the output. Output: * Hello Spring” ey loC(Inversion of Control) ‘What is loC? 7 IoCis a design principle that transfers the control of object creation to the framework. 7 Instead of manually creating objects, Spring injects dependencies automatically. a loC Container features Spring 1OC Container A Types of loC Container ‘mor enterprise spec incon 5 Dependency Injection 7 ttis a design pattem which removes the dependency from the programming code, that makes the application easy to manage and tos. Dependency Injection makes our penn coe cnc ch nena caren rleeraton =) dosen't affect the use. a Types of Dependency Injection 1. Constructor injection [Link] Dependencies are injected through Dependencies ae injected using setter constructor parameters methods. 1 Eneures immutebilty & final flelds ‘1 lows optional dependencies. a Spring Bean Lifecycle and Scope 1 Understanding Spring Bean ifeeyele ean initialization Steps Bean Instantiation ~ Objoctis created Bean Initialization = @PostConstruct or Intmethed executes. Bean Ready to Use Object is used Bean Destruction @PreDestroy or destroy method executes. | Spring Bean Lifecycle and Scope 2. Spring Bean Scopes Singleton (Defaut) ~ One instance per Spring container Prototype ~ New instance forever request Request Oneinstance per HTTP request (fr web apps) Session ~ One instance per session. Global Session ~- One instance per gba ASN88 Spring Configuration ‘7 What is Spring Configuration? 7. Spring needs to be configured soit knows how to manage objects and dependencies. spring Types of Configuration Y XML-based Configuration { erseetencamet ey | + Prefered in legacy projects 7 Java-based Configuration Uses @Configuration and @Bean, ‘Type safe and modem approach, 7 Annotation based Configuration BComponent, @Service, and @Repository. °s @ComponentScan inthe configuration Spring Annotations Commonly Used Spring Annotations Spring simplifies configurations using annotations instead of XML. Core Annotations in Spring: Annotation Purpose @Component Generic Spring managed bean oe Indicates a service layer component @Repository ‘Specialized DAO (Data Access Object) component @Autowived ‘Automatically injects dependencies, Spring Annotations Spring Annotations Example: Dependency Injection using @Autowired. @Configuration ~ Defines a Spring configuration class. @Componentscan ~ Specifies packages to scan for components Best Practice: Use @ComponentScan(basePackages = “com example") to scan custom pa Creating a Spring Application Building a Simple Spring Application Steps to Create a Spring Application: Set up a Maven project in Eclipse/Intelid Add dependencies in pom xl ee eee ey paler emer eet eran reer eet Ret Creating a Spring Applicatio: Implement Dependency Injection in a Real-World Example (Order Processing). Cas erie Cat eae accom a ase aay Ot SOL toed Key Takeaways: + Use @Autowired for dependency injection + Maintaina clean separation of concerns, Spring Transaction Management What isa Transaction? ‘Atransaction ensures data consistency in the database by folowing the ACID properties: + _Atomicity ~ All operations complete successfully or none at al Consistency ~ Data remains valid before and after the transaction + Isolation ~ Concurrent transactions don’ interfere Durability - Changes are permanent after the transaction commits. + Why Use Transaction Management? Ensures data integrity Prevents partial updates. + Manages rollback in case of failue. : Spring Transaction Management Using @Transactional for Transaction Management + Without Transactions (Risky Behavior) If anerror occursin credit) the money is stil debited! Cort a erent Cet ee ee ene eee a A Spring Transaction Management Using @Transactional for Transaction Management With @Transactional (Safe Approach) Han error occurs, changes rollback automatically. eee

You might also like