Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
81 views
Sunbeam Corejava Notes
Uploaded by
PráàshAnt GAud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Sunbeam Corejava Notes For Later
Download
Save
Save Sunbeam Corejava Notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
81 views
Sunbeam Corejava Notes
Uploaded by
PráàshAnt GAud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Sunbeam Corejava Notes For Later
Carousel Previous
Carousel Next
Save
Save Sunbeam Corejava Notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 80
Search
Fullscreen
SUNBEAM Institute of Information Technology cvammaens Placement Initiative Cee Day OI (5 hours) + Java Books: = Core Java Vol | & 2 - Hoarsman ~ SCIP Programmer's guide - Khalid Mughal - Java Programming Language - Jame Gonsiing = Inside JVM - + Java Programming Language: - Invented by "James Gosling" ~ Company "Sun Microsystem” > "Oracle Ine” - Originally Java was invented for embedded systems. In fact first product developed using Java technology was a “Remote Control” named as "*7” = However in spite lot of efforts from Java team, Java was not considered by industry at that time, - In 1990's people started using internet. However internet support was limited to static web pages. - Around 1995 Java use applets as interactive java programs that can be executed on client browsers. In short span of time, applets and hence Java become popular for internet. = There are three main streams were developed using Java language: 1. Java SE = Desktop based java applications (Console & GUI applications), ~ Core language part of Java ie. OOP and other features. Versions pulished: = Java 1.0 = Java 1.1 - J2SE 1.2> Added collection framework -J28E 13 = J2SE 1.4 > another stable and popular Java - JavaSE 5.0 > Added generics, annotations, = JavaSE 6 = JavaSE 7 > Added Parallel programming, -JavaSE 8 2. Java EE: ~ Web based / Enterprise application - Servlets, JSP, EIB, Struts, Spring - Versions published: ~J2BE 13 - 2B 14 —_—_———— ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology Placement Initiative ~ JavaEE 6° ~JavaEE 7 3. Java ME: ~ Java for embedded devices. + C/C++ Compilation & Execution: Lel.epp] > Compiler > [.obj] > Linker > Lexe] Source Code _ Object Code Executable Machine Instru Machine Instr 1 Operating Sys I Processor (HW) + Java Compilation & Execution: Hellojava Glass Helle { public static void main(String[] args) { system. out.printin("Hello, world!"); - COMPILATION COMMAND: javae Hello,java - Name of ava file (with extension) ~ class file is always created as per class-name (not ,java file name). = If single java file contains multiple java classes, then multiple cass files will be created. - EXECUTION COMMAND: java Hello - Name of .class file (without extension) = Its expected that in this class, main() is prsent [Helio,java| > Compiler > |Hello.class] Source code Java Executable Java Code Byte Code ‘SunBeam Institute of Information Technology, Pune, Karad|| & SUNBEAM Institute of Information Technology surseam accra sommes Placement Initiative i YM [Machine Instr] 1 Processox( HW) + JVM, JRE and JDK: = Java Virtual Machine - VM is hypothetical machine assumed by Java compiler an is emulated in software as part of JRE. Machine level instructions of JVM are of one byte each instruction and hence it is called as "byte - java ClassName - Here "java'" is application launcher. = JVM Architecture: class —> Class Loader | | Byte Code Verifier| | > Processor(Hw) Garbage Collector | Java Runtime Environment: - JRE is required for execution of java programs (.class) files, JRE = 1VM + java tools + java libraries (jar) - JRE can be downloaded ftom oracle site for particular OS platform. In other words, JRE is platform depenedent. - Java Development Kit: JDK is required for developing java applications, - JDK = JRE + java dev tools (compiler, debugger...) - JDK can be downloaded from oracle site for particular OS platform. In other words, JDK is platform depenedent. SF | | Sunbeam Institute of information Technology, Pune, Karad geSUNBEAM Institute of Information Technology —— —— Placement Initive Crees + Java Features: - Portable: = Compile Once and Run Anywhere - Java code is compiled into .class files. These .class files can be executed on any OS for which JRE is present. - Even though same .class can run on many platforms (OS), for certain features behaviour will be OS dependent e.g, File IO, Threads, Sockets, AWT, ~ Thus java is not purely "Platform Independent". ~ Architecture Neutral: + JVM GIT) convert byte code into native code as per underlying CPU architecture ~ So same java code can be executed on any CPU arch for which JRE is present. + Reading work: Core Java Vol 1 - Java History Java Buzewords + Java Code compilation and Execution: - PATH is an Ennvironment Variable of the OS. It contains list of directories seperated by semicolon ; (on windows) or colon : (on UNEX/Linux). ~ When any program is executed on command line without giving its full path, OS will search it into all | directories mentioned in PATH variable. | ~ If you want to execute any program without giving its full path, you must add its directory path into PATH variable. - To see current PATH variable: [WIN) set PATH [LINUX] echo SPATH ~To add a dir path in in PATH variable: (WIN] set PATH=new_dir_path;2PATH% {LINUX] export PATH=new_dir_path:SPATH. - To permantly set PATH variable: [WIN] My Computer > Properties > Advanced > Environment Variable -> Select PATH -> click EDIT > add new_dir_path follwed by ; (do not remove/overwrite existing PATH), [LINUX] in bashre fie (in your home dir) add ema: export PATH=new_dir_path: ~ To unset/nullify PATH variable: [WIN] set PATH: ILINUX]__export PATH= ‘SunBeam Institute of Information Technology, Pune, Karad@® SUNBEAM = Institute of Information Technology jean “remuanee =— cvomemne: Placement Initiative Cee - To add path of java compiler (javac) into PATH var: [WIN] set PATH=C:Program Files\Javaljdk xya\bin;%PATH% [LINUX] export PATHE/ustijavaljdk | xyz/bin:SPATH = javac -d dirpath FileName.java - In this example, given Java file will be compiled and .lass file(s) will be ereated in the give dirpath, eg. javac-d. Hellojava > will create Hello.class in current directory. vac -d D:\temp Hi,java > will create Hiclass in D:\temp directory. - java ClassName ‘This will start java application laucher (java.exe), load JVM in it and it will execute given .class file, After loading and verifying class, execution begin from main() method. If proper main() is not found, JVM will throw error: + Hello world example: import java.lang System; class Hello { public static void main(String{] args) { System.out printin("Hello, world!"); } «In java, global data/methods are not allowed. Even main() method must be declared within some class. = When program execution begins, JVM calls/executes main() method. = Here we expect that main() method should be invoked from outside the class (JVM) and hence we declare it as public = JVM invoke main() method directly without creating object ofthe class and hence main() should be declared as static. - main() does not return any value, so its return type is voi. = main() method can take command line arguments and hence it has an aryument : String{] args - System.out.printin("Hello, world! - Here "System" is a pre-defined class = "out" is publie static member of that class. "out" is of type of "PrintStream" class. ‘SunBeam Institute of Information Technology, Pune, Karad2 G@ SUNBEAM ==, Institute of Information Technology ree printin() is a method i by a newline character: ~ System.in encapsulates stdin. ~ System.out encapsulates stdout. ~ System.err encapsulate stderr ~ System.out print) can also be used to print formatted output on the sereen jus ike C language print() function. Supported format specifiers are Yd, %f, 9s, %e: + Java primitive typ - Primitive types are not classes in java to improve the performance. «Integer types: byte (1 byte) - unsigned : 0 to 248-1 short (2 byte) - signed : 2°15 to +2°15-1 sint (A byte) - signed :-2°31 to #2°31-1 slong (8 byte) - signed : -2°63 to +2°63-1 ~ Real (numbers) types: + float bytes) - double (bytes) = character types: char (2 bytes) : unicode characters :"A' * String- set of characters, = "Hello” - string const or string literal ~ boolean type: =boolean (1 bit) : true or false ~ Since java is strictly type-checking only a few conversions are allowed (not all. ~ Conversion from boolean to integer type and vice-versa is not supported directly ~ Conversion from char to integer type and vice-versa is not supported directly. ~ Conversion from narrow data type to wider data type does not need type-casting. However conversion from wider data type to narrow data type needs type-casting. short a= int b: WOKAY int x= 10; shorty=x; // ERROR shortz=(short)x;—_// ALLOWEDSUNBEAM Institute of Information Technology conn ert sae svememencx Placement iniative Creenoe + Java Classes and Objects: ~ Classis user-defined data type. - Class contains fields and methods. - Variables of class type are called as "Objects" = In java, objects can be created only on heap using “new operator". In other words, objects cannot be created on stack. - public static void main(Stringf) args) { Person pl = new Person(); isa reference, keeping address of Person object created on heap. «In java reference can be "null" or can be initialized after declaration. «= If local reference is used before initialization, compiler will raise error Person pl; pl.displayO; 1! error «= Accessing members on null reference will raise "NullPointerException’ (at runtime). Person pI=nulls pl.display(); // exception = Methods: - Constructor: = Same name as that of class, no return type, - Used to initialize fields - If not implemented, each class will have a default paramterless constructor given by the'compiler. - Parameterless constructor - Parameterized constructor Person() { this("™, ", 0); call to param ctor Person(String name, String address, int age) { Was «Tn java, one constructor of class can be accessed from another constructor of that class using "this" keyword - However, such constructor call must be first line of the constructor; otherwise compiler raise error. = In java, if fields are not initialized: Primitive type variables will be initialized to default value e.g, int ‘SunBeam Institute of Information Technology, Pune, KaradG&G SUNBEAM ey Institute of Information Technology sumeamn we sane Cees reference variables will be initialized to null + In java, fields can be initialized at the point of declaration in the class. class Person { String nami int age = 40; + Object initializer syntax/block: class Person { String name; int age; 1 object initializer block this.name = "something"; thisage = 10; ~ When a new object is created. all values initialized at point of declaration of fields will be assigned. = Then object initializer block(s) will be executed in the order of their declaration in the class. - Finally constructor executed as per creation of the object. pl = new Person(); paramless p2= new Person( ",2); / parameterized * Java uses Hungarian notation for class names, while camel notation for field/method names. + getters/inspectors: int getAge() { return this.age; } - setters/mutators: void setAgetint age) { SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology . a a ——— comms Placement Intative 1 Creed this.age } facilitators: displayQ / accept) + User inpu - Using yner" class one can get input from end user. = This class is defined in “java.util” package (not in default "java.tang” package). - Hence before using this class, importing package is mandetory (as shown in example). + import java.util Scanner; class Main ( public static void main(String[] args) { Scanner se = new Scanner (System. in) ; system.out.printf ("Enter full name : "); String name = sc.nextLine() ; system.out.printf("Enter name : "); String name = sc.next(); system.out.printf ("Enter roll : ") int roll = sc.nextint () ; system.out.printf("Entex marks ="); double marks = sc-nextDouble(); sc.nexthine(); // flush \n char System. out.print£("Enter School name String school = sc.nexthine(); “ se.close(); Day 02 (5 hours) + Access Modifiers: ~ Class members ca .ve one of the following access modifier: 1. public protected private {te of Information Technology, Pune, Karad ‘age 8G&G SunBeEAam =, ___Institute of Information Technology mn Placement Initiative Cees 4. default (package) - Usually fields are declared as private and methods are declared public. = class Person { 7 private String name; private int age; public Person() { ee ) public void display() ( uy + Compilation and Execution Standard Pract {project} I [sre} 1b java I [elasses} | class 0. Create directory structure as above & save java files into "src" directory. 1. Open command prompt and go to "sre" directory. 2.CMD> ——_javac-d ..\classes Main java 3. CMD> cd ..\classes, 4. CMD> java Main + static keyword in java: ~ Static members do not belong to the object, they belong to the class. ~ Static members can be accessed directly by using class name and dot () operator ~ Hence to access static members there is no need to create object of the class. ~ However, Like C++, java allows access to the static members using dot operator on objec + statie fields + Static fields do not contribute to size of object. ~ The data that is commion for all objects of the class should be declared as static. + static methods - Static methods do not receive implicit "this" pointer and hence they cannot access non-static members of the class directly. ‘SunBeam Institute of Infor rion Technology, Pune, KaradSUNBEAM Institute of Information Technology cccoeseum Placement Initiative ~ Static methods can access static members ofthe class: - Static methods are written to manipulate static fields in the class. - Static methods are sometimes implemented as entry-point to the class. In other words, they are used to create objects of class. ~ e.g. Calendar cal = Calendar. getinstance(); - Creating object using such static method in the class is called as "static factory pattern’ ¥ static block - class Sample { aw static { (7 000 “ , = When class is loaded first time into JVM, class-loader invokes static block(s) declared in the class. - There can be one or more number of static blocks declared in the class. = When class is accessed first time, all these static blocks will be invoked in the order of their declaration in the class, - Static blocks are used to perform one-time initialization for the "cla - Initialization of static members when class is accessed first time. - JDBC driver registration must be done once before establishing database connection, eg. Singleton class: class Singleton ( static Singleton obj = null; public static Singleton getInstance() { if (obj==null) obj = new Singleton () ; return obj; , // fields private Singleton() { ) // methods class Singleton { ————$—————————— ‘SunBeam Institute of Information Technology, Pune, Karad| | SUNBEAM Institute of Information Technology Cee static Singleton obj = null; static { obj = new Singleton() ; , public static Singleton getInstance() { return obj; ) // fields private Singleton() { ) // methods , class Main { : public static void main(String[] args) { Singleton s1 = Singleton. getinstance() ; Singleton s2 = Singleton.getInstance() ; MD ve ) + static member class - Will be discussed with "inner classes”. + Composition - Represents “has-a" relationship between the objects - class Date { private int day, month, year; We sas ) = class Book { private String name, author; private double price; private int pages; private Date publish; public Book() { this.name = ""; this.author = this.publish = new Date(); ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology a ne ma seaman Placement initiative a Cerro public Book (String name, String author, double price, int pages, int day, int month, int year) { this.name = name; this.author = author; this price = price; this pages = pages; this.publish = new Date (day,month, year) ; ) public Book (String name, String author, double price, int pages, Date publish) { this.name = name; thie. author = author; this.price = price; this.pages = pages; this.publish = publish; > public void display() { system. out. printf ("#s\n$a\: system. out. printf ("#£\néd\n", price, pages); publish. display (); ", mame, author); ) class Main { public static void main(String[] args) ( Book bl = new Book(); bl.display(); Book b2 = new Book("booki", "aul", 100.00, 30, 1, 1, 2014); b2. display (); Date d = new Date(2,2,2014) ; Book b3 = new Book("bk2", "au2", 200,00, 40, d); b3.display(); Book b4 = new Book("bk4", "aud", 20.0, 10, new Date(3,32014)); b4.display(); ES Fy | Sentear stitute oftnformation Technology, Pune, Karad ageSUNBEAM Institute of Information Technology acacia ee Placement hitiative Ceo + Arrays: - In java, arrays are objects. So they must be created on heap using "new" operator - Syntax - antl] arr; Just declares a reference to array of ints, ~ ant{] arr = new int(5]; = By default array elements are initialized to zero. - int{] arr = new int{5] { 11, 22, 33, 44, 55}; = Initializing array elements at point of declaration. Internally array is object of "java.lang.Array” class and it holds array elements and also a “length” field to represent number of elements in the array. ~ To access array elements: > for(is0; i < are length; i+) system.out.printé("Sd\n", arr[i]) ; for(int n : arr) system.out.printé ("d\n") n)s ~ If you try to access array element at invalid index (index <0 or index >= length), then exception will be thrown. = When we create array of objects, internally array of references is created. By default each reference is "null" = Programmer must initialized each reference to a valid object to avoid "NullPointerException” ~ Date[] arr = new Date[5]; arr[0] = new Pate (1,1,2000) ; arr[1] = new Date(1,1,2001) ; arr[2] = new Date(1,1,2002); arr[3] = new Date(1,1,2003) ; arr[4] = new Date(1,1,2004) ; for(int i=0; isarr.length; i++) arr[il display (); - Each java program receives a set of command line arguments given by user while executing program on ‘command line, in form of an array argument to mainQ function, = Unlike C/C+, Oth element of the array is not name of executable / class fil. - Main java > class Main > public static void main(String{} args) { for(int i=0; i
Satara 3 > Sangli + Ragged Arrays: “In java, we can create array of aray ODIECTS size of each array object may of may not be Same © se lint ind; care tength? int) for(int ; jcarx(i} lengths 344) ( system. out printé ("td "+ are(il(3))7 ) system.out.printin () i Le 4+ Java Method Arguments: ~ in java primitive types are always passed by value public static void swap(int 4 iat b) ¢ int t= a aab A bet system.out.printé("a:8d, P aa\n", a, b)7//20 10 ) public static void main(String{} axgs) { int x=10, y=207 system. out.printé("x:8d) ¥ aa\n", x, ¥)7//10 20 wap (x, ¥) system.out.peinte("eitd, yia\n"s * y) i//10 20 ) Tip java objects are always passed by reference in public stati void change (Date at d.setDay (24) } public static void main (String{] args) ( pate di = new Date (12,6, 1980) mation Technology, Pune, Kat ‘SunBeam Institute of Infor rad —_— rage 14SUNBEAM Institute of Information Technology S Ree "@l.display();-//-12/¢/1seem change (di) ; dl.display(); — // 24/6/1980 d ~ Variable Arity Method: public static int add(int... azz) int sumo; for(int # i
public void display() ( class Employee -> public void display() (... Person pl = new Employee () ; pl.display(); _// Employee's display() is called = While overriding a method, its access specifier can be widen in sub-class. Reverse is not allowed (compile time error). - In other words, if method is "public" in super-class it must be overridden in sub-class as "public". Attempt to make it protected or private in sub-class raise compile time erro. - While overriding method in sub-class, return-type of method can remain same or can be of sub-class type (of return type). + Package: - Package is collection of sub-packages, classes and other types. - Package is a physical container (Le, directory) containing sub-packages, classes and other types. - A type/class can be added into the package by giving package declaration on the first line of ava file package pha; - Packages are used to avoid name-clashing (just like namespaces in C+). = Class access modifiers: 1. default; - Classes are accessible into the same package. 2. public: Classes can be accessed in the same package as well as outside the package. «To access a class outside the package, use import statment into that java file. —_—_——— SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology ~ import java.util Seanner: ~The one or more "import" statements can be written after "package" statement in te java file (if present) - One ,ava file can contain one or more java classes; however only one class can be "public" (in a Jjava file). class must match with java file name. Otherwise compiler will raise error. + Example of packages: = Person,java package pl public class Person { We oot - Mainjava import pl Person; diimport p1.*; public class Main { public static void main(String{] args) { Person p! = new Person(); + javac -d . Person.java ~ create "p|" package (dit) and Person.class file in that dir. + javac-d.. Mainjava (pkgname ~ create Main.class in cur directory. + java Main (UNIX). - will execute program. ~import pL.*s (class) am = This will allow to access all public classes in "p1" package into the java file (in which above line is written). ~ This will not allow classes under sub-packages of "pI" = However it is recommended practice to import each class individually as required, = A class without any package cannot be accessed in class with some package. Si : ‘SunBeam Institute of Information Technology, Pune, Karad e2¢ unBeam |6& SUNBEAM Institute of Information Technology sumeeam a me Placement Initiative = Nested packages: = It is possible to have package within another package. In fac, itis recommended practice to have hierarchial package names. - Example: Person java package com. sunbeam, wimc.pkgl: public class Person { Ww package com. sunbeam. wime.pkg2; import com. sunbeam. wimc.pkgl.Person; public class Main { aw (CMD> javac -d. Person.java CMD> javac-d . Main java CMD> java com sunbeam. wime.pkg2.Main * Note last command, where "Main" class is kept in some package. While executing giving full name of class (pkgname + classname) is expected. + CLASSPATH: - CLASSPATH is an environment variable containing list of directories separated by ; (win) or (UNIX). - Java tools (like java compiler, java app launcher, java debugger. ete) and JVM search java classes (class) and packages into all directories mentioned in the CLASSPATH variable. = To see current CLASSPATH variable: [WIN] set CLASSPATH [LINUX] echo SCLASSPATH. - To add a dir path in in CLASSPATH variable: —_——_ Institute of Information Technology, Pune, KaradSUNBEAM G Institute of Information Technology SUFEEAM
"obj", return +1, else return «1 ~ class Student implements Comparable { public int compare To(Object obj) { = (Student) obj; iN{this roll == other.roll) return 0; if(this.roll > other.roll) return +1; | else return -1; } = The sort() method can be called as follows: Student(] arr = new Student (517 arr[0] = new Student(...); | “ws arr[4] = new Student(...); Arrays sort (arr); - Arrays sort() method sorts the array of objects. Whenever comparision of two objects is required during sorting process, it internally calls compareTo() method on the object. = If class is not inherited from Comparable interface, Arrays sort() throws ClassCastException. + user-defined sorting method! = SPaeEall ‘SunBeam Institute of Information Technology, Pune, Karad Page 31 age| 1 { ‘ | | i SUNBEAM — Institute of Information Technology SUTBEAM se sexs” stm a Placement initiative a. i Ma ered public static void sort (Object{] arr) ( for(int i=0; i
0) { Object temp = arrfil; arr[i] = arr[3]; I arr{3] = temp; + Marker interfac In java, interfaces may not have any method declarations (i.e. empty interfaces). Such interfaces are called as "marker interfaces", - They are used to indicate that the class is associated with certain functionality ~ e.g, Serializable is a marker interface. If class is inherited from "java.io.Seriablizable” interface, then JVM cf convert object details into sequence of bytes (using ObjectOutputStream class's write object method). Ifclass is not inhorited from Scrializable, JVM will throw exception. ~ e.g, Cloneable is a marker interface. If class is inherited from "Cloneable’, then Object class's clone method can create copy of the object of that class. Otherwise it throws CloneNotSupportedException, - example: class Date, class Person, + Exception Handling: ~ Runtime problems are known as exceptions. Exception handling is flexible way of handling runtime problems in the execution of the program. - When a function cannot handle a problem detected at runtime, it will "throw" it in form of object of class. ~ The calling function should use "try-catch" block for handling such runtime problems. If no runtime problem occur. all statements in try block will be executed. ~ Ifruntime problem occurs, all statements thereafter in try block are skipped and catch block is executed. ~ In java, runtime problems can be thrown in form of objects ofthe classes inherited from *java.lang, Throwable” cass. -Ifex = There two main types of Throwables: exception is ne ~ Error ~Ifime ~ Represents non-recoverable JVM-internal problems (usually). terminated. ‘SunBeam Institute of Information Technology, Pune, Karad Page FunBeamns aSUNBEAM Institute of Information Technology cnaamumne Placement Initiative ative Cero = Exception Represents runtime problems that can be handled There ar = unchecked exceptions ‘wo types of exceptions: - Mosily occur due to programmer/end user's mistakes. ~ All such exception classes are inherited from java. ang. RuntimeException. = Compiler do not force to handle these exception. -€.g, NullPointerEception, ArrayindexOurOfBounst'xception, etc. ~ checked exceptions - Represents runtime problems raise within JVM or outside the VM. = Compiler force to handle these exceptions in one of the following ways: - Calling function should have try-catch block. Calling function has throws clause specifying exception class. ealled as) - All class inherited from java.lang Exception (except RuntimeException and its sub-classes) represents checked exceptions. JVM oa - e.g, lOException, SQLException, CloneNotSupportedException, ete isnot | - Java Exception Hierarchy: Throwable e method | Brror | OutOMemoryException fete . |- Exception | IOException oe | SQLException |- CloneNotSupportedException of class fon |- RuntimeException |- NullPointerException cuted. | ArrayindexOutOfBoundsException [+ ClassCastException ete, not handled by the calling function, then it will propogated to its calling function, However if n() function. = If main() function doesn’t handle the exception, it will be caught by the JVM; however progr terminated, = If exception i ‘exception is not handled in the entre chain of functions, finally itis given to' | | 6 sunBeam = Institute of Information Technology 0 Coe ~ One try-block can have multiple catch blocks. However exception sut and then exception super-class catch block. Otherwise compiler will raise error. Ps -class catch block should appear first Placement Initiative try ( Haw } eateh(ArrayIndexOutOfBoundsException e) { Wow } catch(RuntimeException ) { Wow }eateh(Exception €) { Ww } catch(Throwable e) { I generic eateh . Maw try { Hon ) eateh(Exception 6) { Wow } finally { Mn i ~ The finally block will always execute irrespective of exception occur of not. statements), finally block is still executed. = In java, finally block can be written after catch block(s) It is optional block. - Even if control is returning/jumping from try or catch block (as a result of return, break or continue like I I ~The only case in which finally block will not be executed in execution System.exit() within try or catch block = example: class Main { public static int divide(int num, int den) ( if (den==0) eturn num / den; y public static void main(String[] args) { int num, den, res; ‘SunBeam Institute of Information Technology, Pune, Karad throw new RuntimeException("Den cant be 0."); | | | Page 34 StPrasanng Wadekny 6 sunBesam Institute of Information Technology sunBeAn amare ecmmenane Placement initiative wa Core Java Notes Scanner sc = new Scanner (System. in); try ( pum = se.nextint (); den = se.nextint () ; res = divide(num, den) ; System.out.print£ ("Result : #d\n", res); ) catch (Runtimezxception e) ( System. out.printin ("Error occured!") ; } finally { system.out.printin ("Always executed!") ; , ~ java.tang, Throwable: - public Throwable(String message); - Throwable class object encapsulates a string message. which can be initialized via parameterized constructor, Such constructor is present for all its derived exception types. ~ public String getMessageQ; - Returns a message encapsulated by exception object. public void printStackTrace(); - Displays info about exception - mainly exception class type and location in the code from ‘where it is generated (along with stack trace). = public String toString); - returns exception details in form of string which contains exception type. message. ~ User-defined exception class: - example; class MyException extends RuntimeException { private String field; private int value; public MyException(String msg, String field, int value) { super(msg); this.field = field; this.value = value; } 1 getters class Date { | sunBeam Institute of Information Technology, Pune, Karad Page 34|SUNBEAM Institute of Information Technology S SUNBEAM a: accomememn — Placement Initiative Cee Ws public void setYear(int year) { iflyear <0) throw MyExeeption( “invalid year”, "year", yea"): this.year = year; + ~ throws clause : Exception specification list ~ example: class Temp { public void fin throws IOException, ServietException { ” . } } - If'a method is not handling generated checked excepion (using try-catch block), then it must write throws clause in method prototype to indicate exception types it may throw. - ifclass B extends A: A> void fun() throws El, E2, E3; then B > void fun) throws El, E2, £3; // OK OR B > void fun() throws El, E25 NOK BUT B > void fun() throws El, E4; A Error super-class method; but it cannot throw any additional exception, if class D extends C: C> void fun() throws IOException; then D> void fun() throws IOException; 1 OK oR D = void fun() throws EOFException;// OK BUT D> void fun() throws Exception; // or In other words, an overridden method can throw exception of the same type or exception sub-class typ corresponding to super-class method; however it cannot throw super-class of exception type aT rrcT ‘SunBeam Institute of Information Technology, Pune, Karad Page 36 tn other words, an overridden sub-class method can throw same or fewer exceptions than correspondingsponding lass typel Page 36 SUNBEAM Institute of Information Technology siamo i cocrsmmmex Placement Initative Coron - multi-cateh block: (j2¢e 7) ~ example try { “ fun() ; Vio } catch (BOFException e) { // igonore : do nothing ) cateh(TOException | SQLException e) ( system. out.printIn ("Error Occured!") ; system.Exit(1); } catch (Exception e) { e.printstack?race(); ) = When we want to implement same logic to handle more than one exception, we can use multi-catch block as shown in above example. ++ Wrapper classes: - In java, primitive types are not classes i.e. primitive type variables are not objects. = However sometimes. there is need to treat prmitive type values as java objects. E.g, java collections can work only with objects (not with primitive types) : ~ Example: tll j2se 1.4 ArrayList obj = new ArrayList(); / Ithas add method to add object of any type 1 void add(Object ob); objadd(11); error: cannot add primitive type obj-add(new Integer(11));// no error: Integer obj - Thus "Integer" is wrapper class provided by java to treat “int” values as “objects” - Java provides wrapper classes for all primitive types as follows: - byte > Byte = short > Short + int > Integer = ong > Long « float -> Float - double > Double —— ‘SunBeam Institute of Information Technology, Pune, Karad6 sunBesam = _institute of Information Technology _ = ~ char -> Character - boolean -> Boolean. + Autoboxing: ~ example; int mum = 100: Integer num2 = num; «This is valid syntax from J2SE 5.0 and onwards. - Here primitive type value is automatically converted to corresponding wrapper class object type. This feature is known as “autoboxing”. ~ example: {nt num3 = num2; - As shown in above example, even wrapper class object can be converted! back to the corresponding primitive type value directly. - However conversion from primitive type to wrapper object is not efficient (as internally memory is allocated, as well as it takes tinue). Fui better performace autoboxing should avoided whereever possible, ~ example: ~ example: ‘ArrayList obj = new ArrayList(); ‘obj.add(11); _ // valid from j2se5.0 - but slow + String class: «String encapsulate set of characters and length. It provides numerous method for manipulating String data - String is immutable object. Any meihod modifying string contents will not change the object's contents; rather it creates a new String object with modified contents. ~ example: public static void main(String[] args) { String s1 System.out.printf("s1 : %s\n", 51); 52 sl.concat("Infotectr System.out printf('sI : %s\n", s1); System.out.printf("s2 : %sin", 82); ‘SunBeam", s2; 1g Compa ‘SunBeam Institute of Information Technology, Pune, Karad6& SunBeam Institute of Information Technology sunbeam ae noe seemmumes Placement Iitiative Crees ~ Two object's equality can be checked using equals() method. - They can also be compared using Comparable interface compareTo() method. - Object references are compared using == operator. If this operator results true, both reference are pointing to same object. - String class overrides equals() method and implements Comparable interface. String s1 = "sunbeam’, s2="infotech"; = Internally two String objects are created with different values. “s > false .equals(s2) false - Siring si = "sunbeam", s2=new String("sunbeam"); - Use of new operator force to create a new object with simitar contents si false = sl.equals(s2) = ~ String s1 = "sunbeam", s2="sun = To minimize memory requirement, java compiler adda single entry into "string table” maintained in .class file. Obviously at runtime single string object is created and both references point to the same. -si==s2 ~ sl equals(s2) ~ String s1 = "sunbeam", s beam"; - Java compiler itself ad "sun" and "beam to create a new string "sunbeam" and found that the entry is already present in string table, So again single object is created and both references point to it. ~si==s2 true ~ sl.equals(s2) true - Java does not support operator overloading; however +, += operators are built-in overloaded for String class. - String methods: - Stving(String 5); - String(char (Jar; = int length; ~ char charA(int index); = boolean equals(Object str); ~ boolean equalstgnoreCase( String str: = int compareTo(String st); ~ static String format(String fmt, .); int indexOf(char ch); = int indexOf(String subste); ee ‘SunBeam Institute of Information Technology, Pune, KaradGwe Institute of Information Technology er ad ~ String substring(int start, int end); = String{] split(String regex); - String concat(String s): - String replace(String find, String replace); - String toUpperCase(): ~ String toLowerCase(): + StringBuffer Class: = Represents mutable string object i.e. any method modifing contents of object will modify contents ofthe same object. ~ example: public static void main(String] args) { * StringBuffer s1 = new StringBuffer("sunbeam"); System.out.printf('s|: %sin’, .toString()s sl.append("infotech"); System.out prnt{('s| : %sin", s1.toStringO); } characters in the StringBuffer class encapsulates a string buffer which can dynamically grow as number 0 object are increased (appended). “The number of characters present can he found using length() method, while maximum number of characters that can be stored in internal buffer can be found using capacity(), - Stringbuffer Methods: - StringBuffer(String s) int length + int capacity; = char charAtfint index); - StringBuffer append String 3); - StringBuffer reverse(); et. «All methods in StringBuffer class are synchronized, hence it can be safely manipulated in multi-threaded program. However due to synchronization. efficiency reduces (slower). + Stringbuilder Class: - Functionalitywise same as StringBuffer. ~ Added into J2SE 5.0. = Its methods are not synchronized. So used in single threaded program to improve the performance. + Stringtokenizer Class: ‘SunBeam Institute of Information Technology, Pune, Karad® SUNBEAM Institute of Information Technology —e Placement initiative Ceres it string data into multiple pars. Nowdays splitQ/method is preferred over StringTokenizer. + java.util. Calendar class: - Represents a calendar date and time. object = Calendar cal = Calendar getlnstance(); - By default object will contain current date and time values, - Calendar is abstract class. On desktop (I2SE), it internally creates object of java.util. GregorianCalendar class. = To set calendar fields: -cal.set(year, month, day); cal.set(year, month, day, hour, min, see); - Imp note: months are counted from 0 to 11 = To get value of individual field: + int dd = cal.get(Calendar DAY_OF MONTH): ~ int mm = cal.get(Calendar, MONTH) + 1; ~ int yy = cal.get(Calendar-YEAR); + Java.UtiLDate Class: = Was used to represent a calendar day & time. Nowdays most of the functions from this class is deprecated. = Currently this class is used to represent time duration in milliseconds from epoch time i.e. 1-JAN-1900 00:00:00. - example: Date d2 = new Date); System.out printIn(d2.toString(); + Nested Classes: 1, static member class: - A class can be declared within another class with “static” keyword. In this case, the inner class is treated as.a static member of the outer class. = Inner class object is not dependent on outer class object. «Inner class can access static members of outer class directly; however it cannot access non-static members directly, - If name of static member is same in inner and outer class. inner class using syntax "Outer.member". - static member class can have public, private, protected or default access modifier «If static member is visible outside the Outer class (due to its access modifier), then it can be accessed ‘Outer.inner” outside the class, using synta eS ‘SunBeam Institute of Information Technology, Pune, Karad Page 41SUNBEAM Institute of Information Technology Kao S suneeam Ces ‘Outer.Inner ~ example: class Outer { static class Inner { 2, non-static member class: « Non-statc inner class object can be created, ifand only i tis associated with some outer class object. « Non-static member class can access static as well as non-state members ofthe quer class dreety ~ Non static member class have a hidden reference to the associated outer class objet ie, "Outer this". « FFname of non-static member in outer class is same as that of inner cass, then i ean accessed in the inner class using syntax "Outer.this.member" “Object oFinner class can be created outside the Outer class using one ofthe following way = Outer obj = new Outer; Cuter. Inner refl = obj.new Inner); ~—Outerinner ref2~ new Outer().snew Inner; “Inner class abject can be created inthe outer class non-static method directly ~ class Outer's non-state method: void nsMethodd { Inner obj new Inner); his new Inner()s Mnner obj = example: class Outer { class Inner { a ist implements Iterable ( private static class Node ( Object data; Node next; public Node() { ‘SunBeam Institute of Information Technology, Pune, Karad6 sunBeam Institute of Information Technology , this.next = null; private Node head; public List() { this.head = null; » public void add(object val) { Node newnode = new Node (val) ; if (head==null) head = newnode; else { Node trav = head; while (trav.next!=nul1) trav = trav-next; trav.next = newnode; private class Iter implements Iterator ( private Node nodeOb3; public Iter() ( this.nodeobj = head; , public boolean hasNext() { return nodeObj!=null ? true : false; , public Object next() ( Object val = nodeob3.data; node0b} = nodeob3.next; return val ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology mene om oesomaseac Placetnent Inittive public void remove y public Iterator iterator() { return this.new Iter (); ) public class Main ( public static void main(String{] args) { List obj = new List (); ob3.add ("A") ; ‘ Te List.Iter itr = obj.iterator(); while(itr.hasNext()) ( String val=(String) itr next () ; system, out.printia (val) ; } fox (Object val : obj) system.out.printin (val) ; 3. local class: ~ in java, clases can be defined within the method. Such classes are treated like local variables and ate called as "local classes". Their scope is limited to the method in which they are implemented. In other words, the class cannot bbe accessed outside the enclosing method. “Af class is implemented within static method, it behaves as static member class (i.e. ean access static members of outer class directly) «If cassis implemented within non-static method, it behaves as non-static member class (je. can access static and non-static members of outer class directly) - In both cases, local classes can access final local variables of the enclosing method. ~ example: class Main { ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology Placement Intative Cees public static void main(String[] args) Student[] arr = new Student[5] arr[0] = new Student(...); uw class StudNameComparator implements Comparator { public int compare (Object ol, Object 02) { Student si=(Student) ol; Student s2=(Student) 02; int diff = s1.getName() .compare(s2.getName()) ; return diff; ) StudNameComparator cmp = new StudNameComparator () ; Arrays.sort(arr, cmp) ; for(Student s:arz) system. out.printin(s) ; ? ~ We can create any number of objects of local class within enclosing method. 4, Anonymous Inner Class: = example’ ClassName obj = new ClassName() { b = When you want to create single object ofa class inherited from some other classinterface and need to invoke its overridden methods, anonymous class would be the best choice. «= In above syntax example, internally a new class is created inherited from "ClassName" and then its object is created, which is accessed by "obj" reference. - Obviously with “obj” reference we can access only overridden methods of that inherited anonymous class = Usually such classes are written in some method and hence their behaviour is same as "local classes". ~ example: Rerays sort (are, new Comparator () ( public int compare (Object 01, Object 02) { Student s1 = (Student) ol; Student s2 = (Student) 02; EES ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM w@® Institute of Information Technology SURDEAM sp access samc ee erica int diff = sl.getName() .compareTo(s2.getName()) 7 return diff; Placement initiative ne + Generis in Java: _ When same logic need to be implemented for different datatypes, generic (template) programming can Pe used in java. _ Example: All data structures (e.g, Stack, Queve, List, Tree, et) logie remains same irespective of which type of objects are used in that data structure. - Limitations of generics in Java: 1. Cannot be used with primitive types. . Cannot create array of generic type (T). 3. Type of generic type cannot be properly detected at runtime using reflection. Also cannot work ‘well with “instanceof” operator. ~ Efficiency of generic types is same as efficiency of corresponding "Object" based types in Java. = Advantages: 1. The same generic class can be reused for different class types. 2. Generic classes are type-safe. If different type of elements is added in the generic collection, compile time error is raised. - Generics were added in Java 5.0 version. Till Java 1.4 all collection classes were used as "Object" collections. However 5.0 onwards, all collection classes refined to take generic parameters. x14; ArrayList list = new ArrayList(); ExS,0: ArrayListePersort list = new ArrayList
Q; Ex7 : ArrayList
list ~ new ArrayList>0; example class Stack
{ private T[] arr; private int top; ‘ (vt) array newinstance(type, size); public Stack (Class type, int siz top = <1: » public void push(T ele) ( arr[++top] = ele, y public void pop() { SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology Caron ‘top-=; public T peek() { return arr[top] ; ) public boolean empty() { return top==-1; > public boolean full() { xeturn top==arr.length-1; ) public class Main { public static void main(stringl] args) { Stack
s1 = new Stack<>(); s1.push (11); s1.push (22) ; int ele; ele = s1.peek(); s1.pop() ; System. out.print£ ("popped : > - Generic Interface - predefined java.util. Comparable
interface: public interface Comparable
{ int compareTo(T 0); - implementing Comparable
in Student class: aa\s class Student implements Comparable
{ uv public int compareTo(Student other) { iffthis.rol return 0; ther. roll) return this.roll > other.roll +1 } _ ‘SunBeam Institute of Information Technology, Pune, Karad Placement InitiativeG sunBesam es Institute of Information Technology SUTBEAM ss suncnammsatss oes Seem Placement initiative 3 - Generic Metho By default all methods in generic class are generic methods However it is possible to implement generic method in non-generic class. example class Util { public static void swap
(? ol, T 02) ( Te = ol; , o2 = 02; o2 = t: System. out.print£("o1:8s, o2:%s\n", ol, 02); ) class Main { public static void main(String{] args) { String sl="sunbean", s: Util. swap (s1,s2) ; Ws "infotech"; + Java Collection Framework: ~ Collection Framework = Interfaces + Implementations + Algorithms + Java Collection Hierarchy: ~All collection interfaces and classes are kept under java.util package. + Collection
|: SetsE> |- HashSet
| LinkedHashSet
| TreeSet
| List
|; ArrayList
| LinkedList
|r Vectorse>* I+ Stack
SunBeam Institute of Information Technology, Pune, Karad@ 2UNBEAM — Institute of Information Technology suTmeAm ee oe scuriemmanee Placement Initiative Cerne ‘QueuesE> | PriorityQueue
KV> HashMap
LinkedHashMap
TreeMap
- Hashtable
* Before J2SE 1.2 only Vector and Hashtable were supported. When collection framework is introduces with SAVA2, these classes are modified to be compatible with collection framework interfaces. + Java Collection Interfaces: 1, Collection
= Root of collection hierarchy. - Most of the classes inherited from Collection interiace. 2. Set
- [sa collection which allows duplicate values, bidirectional traversing and random access. 4, QueuesE> - Isa collection which provide data structure queue functionality. 5. MapeK,V> - Not inherited from Collection interface = Stores data in key, value pair so that fora given key, value can be searched in fastest possible tine. + interface Collection
: extends Iterable - Iterator
iterator(); - All classes inherited from Collection interface, i implement Iterator. They all can be traversed using for-each loop. = boolean add(E ele); = boolean contains(E ele); ~ boolean remove(E ele); = boclean isEmpty = int size(); - boolean addAll(Collection
0); __———— ‘SunBeam Institute of Information Technology, Pune, Karad( G@ SUNBEAM Institute of Information Technology GURBEAM somammmmene ecm cnr em Placement lniatve ~ boolean containsAlli Collection
¢); - boolean removeAli(Collection
©); - boolean retainAll(Collection
©); = void clear(); + interface Set
~ HashSet
- Elemenis are stored in any order (based on hashcode). - Faster/E(Micient search. - Equality is based on hashCode() and equals() method. ~ LinkedHashSet Elements are stored inthe order of insertion, ~ Equality is based on hashCode() and equals() method. ~ TreeSet
Elements are stored in the sorted order. - Equality and comparision is based on compareTo() method of Comparable interface. =In other words, objects to be added into TreeSet® should implement Comparable interface; otherwise ClassCastException will be thrown. = Note that TreeSet> does not depend on equals() and hashCode() method of the containing objects ~ As a standard practice, if equalsQ and compareTo() both are implemented, then both should perform comparision on the same fields. + interface List
+ Since itis inherited from Collection
interface, it has all methods discussed in Collection
. + List provides additional searching mechanisms: = int indexOMObject 0); ~ Compare given object with all objects in the list using equals() method and if found, return “index” of that element, Ifnot found return - ~ As list can have duplicate elements, this method returns first occurance of the element ~ example: roll senextintO); = new Student); ssetRoll(roll); ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM @® Institute of Information Technology Placement initiative Cer index = list.indexOfs); iffindex!=-1) ‘System. out-printin("Found’): else System.out.printin(*Not Foun!) int lastindexOMObject 0); 1 with all objects in the list in the reverse order using equals() method. ~ Compare given obj If found return index of object, else return -1 As list can have duplicate elements, this method retums last occurance of the element. + Random access: Element at any index can be accessed/teplaced directly. E get(int index); = Returns object at given index. Throws exception for invalid index. ~ example: index = se.nextInt(); 5 list.get(index); System.out.printin(s); E set(int index, E newEle) - Set a new object at given index (replacing old object). ~ example: index = se.nextInt(); new StudentQs saccept() list.set(index, s); - E remove(int index); = deletes element at given index and all elements after that index will be shifted to index-1 + Bi-directional Traversing: implements iterator for traversing. This iterator is inherited from ListIterator= interface « Listlterator< interface is inherited from Iterator<>. It has additional methods: - boolean hasPrevious(); -E previous(); - void set(E ele); Object of Listlterator<> can be received using listIterator() method of List interface. = ListIterator> listlterator(); - Listlterator> listlterator(int index); ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM | Institute of Information Technology am Placement initiative Cereb | Forward traversing: Listterator t= tists : while(ite-hasNext(Q) { Student s = itr.next( System.out printin(s); } - Reverse traversin Listlterator itr = list. listlterator list size()); while(it:hasPrevious() { Student s= itr previous(); System.out.printin(s); By default, iterator points fo stat ofthe lis, so revere traversal isnot posible = Solin case of reverse traversing lis erator should begin fom end of ist (as shown n above example) | + Algorithms which can work on List iterface: | ~ Alll methods given here are static methods of java.util.Collections class. - Sorting List: = void sort(List'
list); ~ The type T must be inherited from Comparable<>. = void sort(List
list, Comparator
c); ~ Reversing List: = void reverse(List
list) - Randomizing List: = Void shutffle(List
list); ~ Binary Seareh: + List should be initially sorted. - The type T must be inherited from Comparable>. - Void binarySearch(List
list, T obj); + List Implementations: ~ ArrayList> class: ~ Internally implemented as doubly linked list of arrays. Each node contains multiple elements. = It gives more efficient random access. ~ Insertion and deletion (at middle of list) is slower operation). ~ LinkedList> class: ~ Internally implemented as doubly linked list with head and tal pointer. ’ ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM G Institute of Information Technology Ceres jon at ends of list are very fast. Also insertion and deletion at mi woman: Placement Initiative j ~ Insertion and delet of list ifefficient, However random access is slower. = Vector> class: = Vector-> is implemented as dynamic array (contiguous memory). The array grows or shrink runtime as per requirement. - However Vector<> is synchronized class (all methods are synchronized), = It is mainly preferred in multi-threaded program. However syne reduce the performance in single threaded program. - Stack> class: Inherited from Vector. - Provides last-in-first-out behaviour using methods: push). popQ, peekO, + Queue interface: ~ Implementation class: PriorityQueue> + Map
interface: = Map does not allow duplicate keys, If try to add duplicate key. new value will replace old value. = methods: V puttk key, V val; = V get{K key): = int sizes + void elearQs - void removetK key): - boolean containsKey(K key): - boolean containsValue(V vale) = SetcK> keySet(; - Collection
values(); Set
entrySet(); - Implementation classes: - HashMap
: ~ Elements are stored in any order of the keys. - Faster searching LinkedPashMap
- = Elements are stored inthe order of insertion of keys = TreeMap
- Elements are stored in the sorted order of keys. ~ The Key class must implement java.util Comparable
, ‘SunBeam Institute of Information Technology, Pune, Karad6 SunBeam Institute of Information Technology SUNBEAM. socssnmammens: cmennanan a scement Initiative performance in single threaded program. * Note: MapéInteger,Student> map = ...3 KEY : Integer VALUE : Student - KEY class ie. Integer class must implement Comparable interface for TreeMap<> and must implement cequals() & hashCode() for HashMap<>, LinkedHashMap© and HashTable>. * Note: Map
niap =. KEY : Student VALUE : ProgressCard In this case Student class must implement Comparable interface for TreeMap© and must implement equals() & hashCode() for HashMap<>. LinkedHashMap© and HashTable>. + Time Complexity: It is approximate measure of time required to complete any algorithm. - Many times time complexity is calculated from number of iterations done into the program. - For example: nia1t293%..¢n - The program will be having loop repeated n times. So time required is proportional to “n", Thus time complexity is of order of "n" and denoted as O(n). - Here "O(n)" is known as Big O notation, - Few Imp Time complexities:- - Time required to add or delete element from stack or queue, is constant (independent of number of elements). So time complexity is O(|). + Time required to add element at the end of linked list having only head pointer, depends on number of elements (loop is repeated to traverse to last element). So time complexity is O(n). - Time complexity of binary search: ai {where, iis num of iterations and n is number of elements in the sorted array] Time complexity O(log r). Time complexity of selection sort: ‘SunBeam Institute of Information Technology, Pune, KaradG SUNBEAM = Institute of Information Technology sunBeam caemane Placement inititive ree ed ‘of comparisions = (n-1) + (n-2) +... #1 =n(wl)/2 So time complexity is O(n"2) + Hashing: ~ Hashing is used for fast searching, ~ The data is stored in form of key-value pair, so that for a given key value can be searched in fastest possible time. ~ Ideal time complexity of searching in hash table is O(1). ~ Hash table is internally an array, holding data and data is accessed by proper index. ~ The values are stored into the array, ata particular index. This indey is calculated from the given key using ‘some mathematical function, called as “hash function”. - Simplest example: -Si ~ Here array of “n" student objects can be created and information of student with roll number ":" can student info so that it can searched for given roll number. be stored! at index This "r-1" is example of simple hash function ~hikey)=key-1 => results in index of hashtable. ~ Here student with roll "r* can be immediately found at index." ‘Time complexity of searching O(1). - However inthe complex examples, multiple keys can result to same inde slot into the hashtable/aray. This is called as “collision” ~ The collision can handled in one of the following ways: 1. Open Addressing: If slot calculated using hash function is already occupied by some object, then another ‘mathematical function is used to find alternative slot for the object. This is called as "re-hashing" ~ Simplest re-hashing function would be "index+" ie. next slot of table (if empty). This simplest mechanism of open addressing is known as "linear probing” Load factor = num of elements / num of slots. ~ This mechanism can be used only if Load factor < 2. Chaining: ~ Each slot of hash-table holds a list of objects competing for the same slot. This list known "bucket" | ~ As numi from O(1), F collisions are increased, the time complexity of searching will be deviated (increased) +hashCode() method: ‘SunBeam Institute of Information Technology, Pune, Karad Page 5,G& sunBeam a Institute of Information Technology SURBEAM (seaman senses nse Placement Initiative Core Java Notes - java.util. Object class has hashCode() method, which can be overridden into the derived to return hash code/value of the object. - This hash code determines the slot of the hashtable, in which object isto be stored. - Ifnot overridden, Object class hashCode( is called, wiiich return hash value based on memory address of the object ~ Rules of hashCode() method: 1. If two objects are equal (by equals() method), then their hash code must be same. 2. IPtwo objects are not equal (by equals() method), then their hash code may be same. ~ Hence hash code must be calculated on the same fields, on which equality is compared. - Statistically itis proven that hash code calculated using prime numbers is uniformly distributed (more unique) ‘and hence most of the hash code calculations are done using prime numbers. + Reflection: - Reflection technique is used to get information about the data type at runtime. - Three applications/uses of reflection: 1. To get complete info about the type at runtime. It is used to develop intellisence feature, tools like Javap.exe. 2. Use the retrieved information about the type to create object of class at runtinne and invoke its methods. This is used in most of frameworks like struts, servlets, applets, etc internally. 3. Generate the java classes (byte code) at runtime and execute them. This can be done by using ClassLoader.defineClass() method. - Information about a type can be received in java.lang.Class object using one of the following way: 1. Class ¢ = obj-getCiass(); - Get the info of the class whose object is referred by “obj”. 2. Class ¢ = ClassName.class; - Get the info of the class with name "ClassName". 3. Class ¢ = Class.forName(“pkg.ClassName"); - Get the info about the class whose name will be taken at runtime (in form of String) ~ This method loads the class in the JVM and return its information. - java.lang.Class methods: - String getName(); boolean isAbstract(); - boolean isinterface(); - boolean isEnum(); - Field{] getFieldsQ; - Method{] getMethods() - Constructor{} getConstructors(); - Annotation{] getAnnotations(); —————————— ‘SunBeam Institute of Information Technology, Pune, Karad ‘& SuNBeam FR Institute of Information Technology Placement Iniative suneeam Cree + GUI programming in JAVA: - JAVA provides different classes for creating desktop GUL There are two main ways to create GUI on JAVA: 1, AWT-- Abstract Window Toolkit: - Java Ul classes intemally depends on the Peer classes, which in turn use OS functions to create Ul. ~ e.g, java.awt, Button class intemally use "ButtonPeer", which in turn calls OS function ("CreateWindow on Windows OS) to create button UL - Due to this AWT Ul will be have different look & fe! on different platforms (0S). ~ Also intemal use of peer classes make them heavy components, 2. SWIN - Java has another set of classes to create platform independent Ul, These classes are called as "SWING". - The look & feel of UI remains same on all platforms. wing components internally use MVC architecture i.e. each swing component (ui contol class) internally use three objects to spit the functionality: = Model : keep the data of the component e.g, Strings in the JComboBox. - View : keep appearance related info of the component e.g. height, width, back color, fore color, et. ~ Controller : responsible for calling event handler when event occurs €. user click, selection changes in combo box, ete. It also communicate between view and model + SWING: + Swing component heirarchy: = Component : represents a UI control on the sereen. . = Container : is collection of one or more components. = Window. - Container that can hold multiple components. ~ It has its own window ie. title bar and border. Panel ~ Container that ean hold multiple components. + It does not have its own window. I is always present in some other window to group components. - JFrame: - Frame has its own window. So it is stand-alone desktop based application, - Frame application has main() function, = JApplet ~ Applet does not have its own window. - So it always execute within browser window. ‘SunBeam Institute of Information Technology, Pune, Karad Page 57| ! | | | SUNBEAM Institute of Information Technology — cence veemmemmene+ Placement ntiatve Coens ~ Applet does not have main() function. Its execution begin with init() method. ~ Swing components = SLabel, JTextField, sTextArea, JButton, JComboBox, JListBox, 1CheckBox, et. + Event handling: - User action is called as an event. e.g. key press, mouse click, et. - We can handle these events to add functionality into the GUL ~ The standard way to handle events isto implement appropriate "Listener" interface. - Example: Button élick handler: * stepl: Implement ActionListener interface into some class (in one of the following ways) ~ Write a new class inherited from ActionListener interface. - Implement ActionListener into the user-defined frame class itself ~ Anonymous inner class to implement ActionListener interface * step2: Pass the object of class inherited from ActionListener to the addActionListener() method of button object, when that button is created. * step3: Into this event handling class write appropriate logic within actionPerfromed() method. = When a button click event occurs, a first it is detected by OS and inform to the JVM. Then JVM pass the event to the button object. Finally button object invokes actionPerformed() method of the listener inherited class object(s) registered with it. - Event objects: ~ Bach listener method receive an Event object inherited from "java.awt.Event" clas. ~ e.g, ActionEvent, WindowEvent, etc. - This event object contains complete info about the event, which includes source of event (component for which event occured) and additional info. + Adapter classes: ~ Certain listener interfaces have more than one methods. e.g. WindowListener has 7 methods, ‘MouseListener has 6 methods. = Most of the cases programmer is interested in handling one or two methods from such interface. However being an interface, it is compulsory for the user to implement all the methods. ~ To simplify this operation, java provides adapter classes for such interfaces. They are abstract classes having empty/default implementations of all methods in such interface. e.g. WindowAdapter and MouseA dapter. = So programmer can write his own class inherited from adapter class and override only those methods in which he is interested. — ‘SunBeam Institute of Information Technology, Pune, Karad Page 58Institute of Information Technology @ SUNBEAM UeeAM Placement Iniiatve ered ~ Typically preferred approach is to create anonymous class inherited from adapter and add its object with target compon: -eg In constructor of the user-defined frame class this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose() + Layout Managers: Java has few builtin managers which are used to place components in the container in proper way. = The layout manager can be set using Container’ setLayout() method. If layout manager is not given (ie, set to null), then programmer must give appropriate x,y coordinates and width,height using setBounds() method of the component. this.setLayout(null); There are few imp layout managers as follows: 1. FlowLayout: = Add components in horizontal direction one after another, just like web page. = this setLayout(new FlowLayout(); ~ button = new Button("Caption"); this.add(button); ~ This is default layout of Panel and Applet class. 2. GridLayout: - Add components in the grid defined by the programmer. Components will be places in appropriate cell (row & col) one after another. « this setLayout(new GridLayout(2,3)); = button = new Button("Caption"); this-add(button); 3. BorderLayout: - Add components in certain direction or center of the container as shown in diag, = this setLayout(new BorderLayout(); button = new Button("Caption"); this.add(button, BorderLayout. CENTER): = This is default layout of Window and Frame class, 4. GridBagLayout: Complicated layout manager which provides flexible way of adding components in the container. ‘SunBeam Institute of Information Technology, Pune, Karad Page 596& SuUNBeAam Institute of Information Technology SUPBEAM (sesnsanmanmerns wer eee Placement Iitiatve Ceres + Applets: + Applet steps (on command line) 1. Write a java class inherited from java.awt. Applet class and override init() method. Write appropriate code in it. 2. To test applet with appletviewer tool, write comment before class (after import statements), *
*/3. Compile applet class. Javac -d . ClassName,java 4, Run applet into applet viewer: appletviewer ClassName,java 5. To test applet in html file, write HTML file as follows:
APPLET DEMO
“IBODY? 6. Open HTML file in the browser. + Applet: - Applet isa java class which is loaded into the client browser and executed within client side JRE plugin of the browser. Applets are embedded into htm! web pages using
tag having following attributes: ~ code="pky.ClassName.class” ie, name of the applet class with package. = codebase*"dir path" i.e. path of directory in which applet package is kept. Required if applet package isin diffrent directory than the html page. = width="300" ie. width of applet ~height="300" ie. height of applet + Applet Life Cyel —— — eesoeorsereolrrlrvml'l SunBeam Institute of Information Technology, Pune, Karad— Institute of Information Technology suGeam muna asm acesssscamns Placement Initiative Cen ~ Applet class has five life cycle methods, which are-overridden by the programmer as per requirement and called by the IRE/JVM within the client side browser. 1. public void init; - When client requests a web page having embedded applet ini, the class file is also loaded at client side, Client broser JVM get the info about applet class from
tag (code attribute). It will load applet class into JVM, create its object, default constructor is executed and then init() method is invoked at runtime. - This method is called only once in the life cycle of applet class object. - Programmer should override this method to perform one time initialization like creating components on applet, etc 2. public void destroy(); - When applet object is no longer required, browser JVM will garbage collect it - However before doing this, it will call destroy() method of the browser. - Programmer should override this method, if applet is holding some resource like file or network connection and need to be released before object is destroyed. - This method is called only once in the life cycle of applet object. 3. public void start; - Whenever applet is made visible to end user, this method is invoked. - Programmer should override this method to perform any operation that to be done when applet is shown to user e.g, initiating animation, if any. ~ This method can be get called multiple times in the life-cycle of applet object. 4. public void stop(); When user navigates from the applet web page, (the applet is no more shown to user) stop() method is called. - Programmer should override this method to stop operations initiated into star() method, if any. i.e. stop animations. 5. public void paint; - When whole applet or part of applet window need to be repainted, JVM invokes paint() method, - Programmer should override this method to draw customized painting logic, if required. + Java IO: + File System Operations: File or directory path is represented by java.io.File object. - This "File” class has several methods to deal with file system. - boolean canRead(): = boolean canWrite(); SunBeam Institute of Information Technology, Pune, Karad{ | : Institute of Information Technology ~ boolean setReadable(boolean perm); ~ boolean setWritable(boolean perm); @ SUNBEAM - boolean setExecutable(boolean perm); ~ boolean isHidden(); - boolean exists(); - boolean isFileQ); - boolean isDirectory() - boolean createNewFile() = boolean mkdir(); - boolean deleted; Stringf] list(); long length; + Input and Output: ~ Stream is java object in which data can be written or read from. = There are two main types of streams: ~ Byte streams : Data is read/written byte by byte. ~ Character streains : Data is read/written char by char (unicode). + Byte Streams - There are two types of Byte Streams: 1. OutputStream: - The data can be written into the output stream, - It is represented by abstract class: "java.io OutputStream’, ~ This elass has following important methods: - abstract void write(int b); - Write single byte of data to the destination - int writeCbytef] arr; int fet, int length); - Write part of byte array to the dest. = int write(byte(] arr); = Write whole array data to the dest. = void flushO; - Write all data to the dest (if kept in mem). a ‘SunBeam Institute of Information Technology, Pune, Karad | |@ SunBeam Institute of Information Technology sumsenn sucmeee Placement rilatve Cares = void close() + Close the stream and release resources. | 2. InputStream: ~The data can be read from input stream, = Itis represented by abstract class: "java.io.InputStream”. ~ This class fas following important methods: = abstract int read(); - Read single byte of data from destination + int read(bytef] arr, int offset, int length): - Read part of byte array from the dest. ~ int read(byte() ar); - Read whole array data from the dest. - int available() - Returns num of bytes to be read = void close(); ~ Close the stream and release resources. | | | + OutputStream heirarchy: 1. FileOutputStream: ~ Write the data to the file on the storage device (with help of OS). 2. ObjectOutputStream: = Converts java object and its info into the sequence of bytes (serialization). 3. Filter OutputStream: - Process data before writing it on underlying stream. 4, DataOutputStream: = Converts java primitive types into the object. 5. BufferedOutputStream: - Stores data in buffer (temp memory) before writing (o underlying stream. Reduces number of \write operations and thus improves performance. 6. PrintStream: ~ Convert java object data into proper (aligned) format, Neatly readable character data is produced 7. ByteArrayOutputStream: - Store data in form java byte array. + Demo of DataOutputStream / DatalnputStream Day 1 ‘SunBeam Institute of Information Technology, Pune, Karad+ Serialization ~ Converting java object into sequence of bytes is called as "serialization". These sequence of bytes contains data (contents) as well as metadata (info) ofthe object. = Converting seqence of bytes back to the java object is called as "deserialization’.It use metadata to recreate the object and restore its contents (using reflection). - For serialization, the class must be inherited from marker interface "Serializable"; otherwise "NotSerializableException” will be thrown, ~ Also class must have a public parameterless constructor. - If you do not wish to serialize certain data member of the java object, it must be marked as "transient" (java keyword) | * class Employee implements Serializable { t private int empid: private String name; private double basieSalary; private transient double totalSalary; public Employee() { Wan - Serialization & Deserilization example: public static void writeStudent(Student s) throws Exception { | FileOu(putStream fout= new FileOutputStream("filepath"); | ObjectOutputStream out = new ObjectOutputStream(fout); out writeObject(}: outflush0; out.close() fout.close(); 3 public static void readStudent() throws Exception { FilelnputStream fin = new FiletnputStreamilepath’); ObjectinputStream in = new ObjectinputStreamttin); Student s = (Student)in readObject0; System. out printin(s toString(); SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute ¢ of Information Technology Pracementinitative Cee in.closeQ; fin.closeQ); + Character Streams: Java stores characters as unicode (two bytes each). = However char data can saved on disk using diffent encoding schemes e.g. ANSI, UTF-8, Unicode, Big Unicode, ete. = The character streams are used for interconversion between java characters and encoding schemes. + There are twvo main abstract classes: - javaio.Reader class = java.io. Writer class example’ FileReader reader = new FileReader(path); System.out.printin("ENCODING : " + reader.getEncoding()) BufferedReader bufReader = new BufferedReader(reader): while (true) { String line = bufReader.readLine(); if (line = null) break; System.out print(line); 3 buiReader.closeQ; reader.close() + Threading: - Thread Creation in Java: 1. extends Thread: - Programmer should write a class inherited from Thread class and override its "run()" method, = Object of that class should be created and its start() method is invoked. example: class MyThread extends Thread { W public void run) { a ‘unBeam Institute of Information Technology, Pune, Karad| SUNBEAM Institute of Information Technology SUTBEAM sscacnosmaan creme — Placement Initiative etched class Main { public static void main(String{] args) { MyThread t1 = new MyThread0; t1stand; } 2. implements Runnable: ~ Programmer should write a class inherited from "Runnable" interface and implement its "run()" method. - Object of "Thread" class should be created and object of above created class should be passed to its cénstructor. Then call "start()" method of thread object. = example: Glass MyRunnable implements Runnable { “uw public void run() ( (i ) class Main { public static void main(String{] args) { MyRunnable rl = new MyRunnable(); Thread ti = new Thread(r1); t1.start(); - Thread Life Cycle: 1. New: - A new thread object is created. ~ Thread t1 = new Thread(..); 2. Ready to Run: ~ When start() method is invoked on thread object, the thread is associated with the scheduler, ~ Scheduler can select thread for the execution at any time based on scheduling algorithm. 3. Running: = When thread is selected forthe execution by the scheduler, JVM invokes appropriate run() method and its execution begins. 4, Non-Runnable: ——————— ‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology exeoneesoc — <-cemmaen Placement Initiative Creo Running thread may do 1O request, sleepQ or wait(). Because of that thread will go to non- runnable state, It is also called as "waiting" or "blocked" state. - After 1O completion, sleep() time completion or notity() done, thread may return back to idy state” so that scheduler can schedule it again for further execution, However thread doing sleep() or wait() can be forcefully unblocked by calling interrupt() on the thread object (from another thread). This will raise InterruptedException into the sleeping/waiting thread. 5. Finally if run() method of a thread is completed, thread will be “dead” or “terminated” + Thread Join: = When a thread calls join method on some other thread object. it (calling thread) is paused until the given thread is terminated. + If main thread calls t1 join, then main thread will be paused until tis terminated. + Some important methods of thread class: - void startQ; - void setDaemon(boolean daemon); - void joing: void interrupt; - static void sleep(long milli); - void setName(String name): + String getNameQ; - void setPriority(int pri) + int getPriority(); - State getState(); + static Thread currentThread() - Get the “Thread” object in its run() method, = static void yield; + Thread calling "Thread yield()" method will goto ready state (from running) and thus JVM/scheduler gives CPU time for another thread. + Daemon threads: ~ JAVA has mainly two types of threads: = non-daemon thread - daemon thread - By default all threads are non-daemon threads. ~ To make a thread as daemon, call setDaemon(true) on the thread object before starting that thread, SunBeam Institute of Information Technology, Pune, Karad Page 67SUNBEAM Institute of Information Technology cern ee Placement Initiative Cee = When all non-daemon threads are terminated, process (in which JVM is running) is terminated. This will cause all daemon threads to terminate automatically. - Thus daemon threads keep executing if at least one non-daemon thread is running. - Daemon threads are also known as service threads, which provides service to non-daemon threads ~ The main thread is a non-daemon thread. + Thread synehronizatio - When multiple threads try to access same object at the same time, itis called as "race condition”. ~ This may result in corrupting object state and hence will get unexpected results, - To avoid this Java provides syne primitive known as "monitor". ~ Each java object is associated with a monitor object. The monitor can be locked or unlocked by the thread. - If monitor is already locked, another thread trying lock it wll be blocked until monitor is unlocked. - The thread who had locked monitor, is said to be owner of monitor and only that thread can unlock the monitor. - Java provides "synchronized" keyword to deal with monitors / synchronization. ~ synchronized block: ~ example: void fun() { Ban synchronized(obj) { Wo } = When certain part ofthe method should be executed by single thread at atime, we can use “synchronized” block, = When a thread begin execution of the sync block, it will lock the monitor associated with given object (obj) and continue execute within that block. - Meanwhile if another thread try to execute same syne block, it will try to lock the object monitor again. - Since object is already locked, the second thread will be blocked, until first thread release the lock (at the end of syne block. - When first thread release the lock, the waiting second thread will acquire it and continue to execute the block - synchronized method: = When non-statie sychronized method is invoked by the thread, it will lock the monitor associate with current object ("this"), When method completes, thread will release the lock. - When static synchronized method is invoked by the thread, it will lock the monitor object associated with lassName.class” object SunBeam Institute of Information Technology, Pune, Karad k f6 sunBeam = Institute of Information Technology surseam roe seem Placement initiative ~ This ensure that two threads cannot execute same synchronized method on the same object. - example: class Account { private double balance u" public synchronized void withdraw (double amt) ( // get cur balance from db // balance = balance - amt; // wpdate new balance into db , public synchronized void deposit (double amt) { // get cur balance from db // balance = balance + amt; // wpdate new balance into db ; : public double getBalance() { // get cur balance from db // return balance; y ~al.withdraw(.) and al.withdraw(...) executed by two different threads atthe same time will not execute parallely. (AS "al" object is locked by thread! and thread2 must wait fori) | withdraw(..) and al.deposit(. executed by two different threads at the same time will not execute parallely. (As 1" object is locked by thread! and thread? must wait for it). al withdraw(...) and a2,withdraw(...) executed by two different threads at the same time can execute parallely. As lock is acquired by two threads on two different objects. -al.withdraw(... and a2,getBalance(...) executed by two different threads at the same time can execute parallely. Because getBalance() method is not synchronized and hence the thread is neither trying lock the object nor will get blocked, = If all methods in a class are synchronized, only one thread can perform any operation on object of that class. Such class. E.g, StringBuffer, Vector. Hashtable, etc class is called as "synchronized" ——————_— ‘SunBeam Institute of Information Technology, Pune, Karad: SUNBEAM Institute of Information Technology ce a Placement Initiative - Socket is an IPC mechanism used to communicate between two processes on the same machine or different ‘machines (connected over network) - Socket is defined as communication endpoint. - Socket = IP address + port number + IP address : unique identifier for machine over network + port number: 16-bit logical identifier for the socket on a machine. ~ Range for port number : 0 t0 65535 = Ports 0 to 1023 are reserved for system use. Programmer should choose any other unused port. ~ There are two main protocols: 1. TeP: - Tranmission Control protocol ~ Connection Oriented ~ Acknowledgement is sent to transm - Reliable - Stream based 2. UDP: - User datagram protocol ~ Connection less = No acknowledgement - Less Reliable ~ Packet based = In java, UDP protocol communication is done using classes : DatagramSocket and DatagramPacket. In java, TCP protocol communication is done using classes : ServerSocket and Socket. + Remote Mettiod Invocation: - "Remote Procedure Call - RPC" is IPC mech: - RMI demo : four coding steps: - step]: Mylntfjava public interface Myintf extends Remote { int summ(int a, int b) throws RemoteException; Student search(int roll) throws RemoteException; 3 + Write a java interface containing methods to be called from client side, SunBeam Institute of Information Technology, Pune, KaradG@ SUNBEAM Institute of Information Technology sunsean ere cecum: Placement Initiative Cree It must be inherited from marker interface "Remote - Each method in interface must throw "RemoteException - step2: Mylmpljava public class Mylmpl extends UnicastRemoteObject implements Mylntf { public Mylmpl() throws RemoteException { } public int sum(int a, int b) throws RemoteE ception { return a+b; } public Student search(int roll) throws RemoteException { return null; ) Write java class to implement above remote interface and provide proper logic. ‘This class must be inherited from UnieastRemoteObject. ~ Class must have a paramless constructor throwing RemoteException. ServerMain,java public class ServerMain { public static void main(Stringf] args) throws Exception { Mylmpl obj = new MytmplQ; Naming.bind( “abe”, obj); = Create object of impl class and associate it with some name (friendly name). - step: ClientMain java public class ClientMain { public static void main(String} args) throws Exception { MyIntf obj = (Mylntf)Naming,lookup( abe"); int res = obj sum(12, 5 System.out.printin("Sum :" + res): 3 ~ Find the object with name given at server side, type cast to interface ref and then call methods on it. —_— SunBeam Institute of Information Technology, Pune, KaradG SUNBEAM Institute of Information Technology FEEAM = amma CO 85 a Placement intative ‘Note: Crees Usually remote interface and other classes which are required for both client and server, are kept in the seperate package. The implementation class and server side main is kept in a package and finally client main class is kept into one more package. * Note: In order to execute server and client code from two different machines on the network, Client side Naming.lookup() method should contain complete URL of the server e.g. rmi:#server-ip:1099/objname ‘Also in this case, server and common package should be deployed on the server machine; while client ‘and common package should be deployed on client machine. - Compilation and Execution of RMI code: - step5: Compile all above files: command: javac -d.* java + step6: Run "miregistry" from the dir in which server package is kept (in command prompt 1). command: rmiregistry + step7: Run ServerMain from the dir in which server package is kept (in command prompt 2) command: java pkg.ServerMain ~ step8: Run ClientMain from the dir in which client package is kept (in command prompt 3). command: java pkg.ClientMain - RMI: Calling java method from another JVM (process) on same or different machine (over network) is called as "RMI”. = Internally Stub and Skeleton objecis are used to execute the method and receive result atthe client side as shown in diag. ~ Remote interface must be inherited from marker interface “java.rmi.Remote”. It allows JVM to create stub for the given remote interface. ~ Each method in remote interface and consructor in the implementation class must throw RemoteException. Since RMI internally performs networking, network connection may fail at runtime. So java forces each method to throw RemoteException, so that programmer can implement some logic to handle such exception mentation class must be inherited from "java.rmi.server. UnicastRemoteObject". The functionality of this class is internally used by the skeleton at the server-side. - RMIREGISTRY: ~ The info about impl class object (remote interface methods) is kept into rmiregistry associated with some "name". This is done by the Naming.bind() method at server side. = When client program calls Naming.lookupQ, it internally communicates with rmiregistry running on server and receive info about remote object. This info is used to create stub at runtim SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Institute of Information Technology 6S cconmmcnam Placement initiative = Naming,lookup() rerums pointer to stub object, on which client program can execute methods. These stub methods intemally communicate with server skeleton to receive result Inthe older RMI compiler) com: fa versions, stubs were not created at runtime. They should be created manually using "rmic” = RMI architecture: = Marshalling & Unmarshalling - Sending object contents over the network after serialization, is called as "marshalling". ~ Receiving object contents from network (in form of byte sequence) and deserializing it, is called as “unmarshalling” + Java DataBase Connectivity - DBC: = JDBC Driver is a special program used to convert java requests to database understandable form and database response to java understandable form. = There are four types of JDBC driver: 1. Type I driver: - Also called as "JDBC ODBC Bridge Driver" - ODBC drivers are implemented in C and can connect to older databases like Foxpro, Access. etc. - Java has builtin JDBC driver to communicate with ODBC driver which in tur work with database = Name of driver class is sun,jdbe.odbe JdbeOdbeDriver = Due to multiple layers, it is slower = Also ODBC support is not fully present on all platforms. 2. Type Il driver: = Partially implemented in C and partially in Java. = Use JNI to communicate betn Java and C layer. - Better performance than Type | - Different driver for each database, = Not truely portable (as partially in C). = Outdated. | ~e.g. Oracle OCI driver 3, Type III driver: \ - JDBC driver communicate with 2 middleware, which in turn communicate with actual database. i e.g. Weblogic RMI driver 4, Type IV driver: = Completely implemented in Java and hence truely portable. - Different for each database. SunBeam Institute of Information Technology, Pune, KaradSUNBEAM Ge Institute of Information Technology SURGEAM cnet smo =n Placement initlve ees Internally use sockets to communiate with database ~ e.g. Oracle Thin Driver +JIDBC is a specification: Speci tion is given in form of interfaces by "Sun Microsystem”, Important Interfaces: ~ Driver : Used to create and manage database connections. ~ Connection : Eitcapsulate socket connection which communicate with database ~ Statement : Encapsulate SQL query to be executed on db, ~ ResultSet: Represents database response tothe query (rows and cols), used to fetch result row by row. ~ PreparedStateiment : Used to execute parameterized query on the database, + CallableStatement : Used to execute stored procedure on the database. ‘The specification given by Sun is implementeb by each JDBC driver. So internally each JDBC driver is set of classes inherited from above given interfaces. This ensures that same methods are present in all driver implementations. ~ Thus JDBC program remains same irespective of which IDBC driver or database you are using + JDBC Example: M0. adding JDBC driver into CLASSPATH + ON COMMAND LINE: > Set CLASSPATH=/path/ofifile/driver jar;%CLASSPATH% ~ javac -d . ClassName,java ~ java pkg.ClassName + ON ECLIPSE: ~ Right click on project, Add New Folder. Give name “lib’, ~ Copy driver jar file into "lib". ~ Right click on project, go to properties. Click "fava Build Path”. Click "Libraries", then "Add Jars". Now select driver jar from ib" directory within current project. public class Demo46 Maint { Moracle,jdbe.OracleDriver Public static final String DB_DRIVER = "com.mysqljdbe. Driver"; 1 jdbc:oracle:thin:@ade:1521 :oracle public static final String DB_URL = "jdbe:mysqli/localhost:3306/test"; Public static final String DB_USER = "root"; public statie final String DB_PASS = "nilesh; public static void main(String{] args) throws Exception { IN. load and register jdbe driver SunBeam Institute of Information Technology, Pune, Karad Page 74® SUNBEAM — Institute of Information Technology suneean an ccomanss Placement Initiative Caren Class.forName(DB_DRIVER); 1/2, create connection object Connection con = DriverManager.getConnection(DB_URL. DB_USER, DB_PASS); 115. create statement object Statement stmt = con.createStatement(); 1/4, execute query and get result String sql = "SELECT DEPTNO, DNAME, LOC FROM DEPT"; ResultSet rs = stmtexecuteQuery(sql}: 11S. process the result white(rs.next() { int deptno = rs.getini("DEPTNO"); String name = fs.getString("DNAME"); String loc = rs.getString("LOC"); System.out.printi("%éu, %s, %s\n", deptno, name, loc): 3 116. close connection, statement, rs.close() stmt.close(); con.close(); + JDBC Insert Example: public class Demo46_Main3 { public static final String DB_DRIVER = "com. mysql.jdbe.Driver Public static final String DB_URL = "jdbe:mysql:/locathost:3306/test" public static final String DB_USER public static final String DB_PASS Public static void main(String{} args) throws Exception { 1/1, load and register jdbe driver Class.forName(DB_DRIVER); 12, create connection object Connection con = DriverManager.getConnection(DB_URL. DB_USER, DB_PASS); 113, create statement object Statement stmt = con.createStatement(); 14, execute query and get result Scanner se = new Seanner(System.in); titute of Information Technology, Pune, Karad@ SUNBEAM Institute of Information Technology SS, Nsttute of Information Technology _ System.out.printin("enter deptno, name, loc : "); int deptno = sc.nextint(): String loc = se.next() | String sql = String. formatc"INSERT INTO DEPT VALUES(%d,%s'%s')", deptno, name, loc); | int count = stmt. executeUpdate(sql); System.out printi("Records Inserted : Yod\n", count); | 11S. process the result 16, close connection, statement, | stmt.close); con.closeQ); + Using Statement: Class.forName("..."); / ‘con = DriverManager.getConnection(". Statement stmt = con.createStatement(); int dno = se.nextint(); 18 = stmt.executeQuery("SELECT * FROM DEPT WHERE DEPTNO="+dno); while(rs.nextQ) { + Using PreparedStatement: Class.forName("..."); con = DriverManager.getConnection(".."," : PreparedStatement stint = con.prepareStatement("SELECT * FROM DEPT WHERE DEPTNO=?"), {nt dno = so.nextint(); stmt.setint(1, dno); 15 stmt.executeQuery(); while(es.next() { Wan d con.close(; | SunBeam Institute of Information Technology, Pune, Karad |Prasanna Wadlekar IGI7024%4 OF @ SsunBesam Institute of Information Technology vrosane, Placement Initiative Creed + Using CallableStatement : executing stored procedure Class forName(".."); riverManager.getConnection( {CALL sp_adddept(?,?,2)}"): Callable dno = se.nextintQ; stmt setint(1, dno); iatement stmt = con.prepareCall name = se.next(); stmr.setString(2, name); Toe = se.next() stmt setString(3, loc); stmtexecute(): + DriverManager: - Manual driver regi Class ¢ = Class.forName("*pkg.DriverClassName"): Driver drv (Driver)e.newinstance(); DriverManager.registerDriver(drv); = Connection Creation: con = DriverManager.getConnection(DB_URL, ..) DriverManager internally search for appropriate driver object (already registered) and then call its connect() method to create actual jdbe Connection and retumn it. + Serollable ResultSet: ~ While creating the statement, type and concurrency of result set can be specified. - ResultSet types: ~ ResultSet. TYPE_FORWARD_ONLY ~ Only forward access, no reverse and random access. + This is default type ~ ResultSet.TYPE_SCROLL_INSENSITIVE + Can perform forward, reverse and random access. ~ Any changes done in the database while resultsetis in use, will not reflect into resultset. ~ ResultSet.TYPE_SCROLL_SENSITIVE ~ Can perform forward, reverse and random access. SunBeam Institute of Information Technology, Pune, Karad| & SunBeam =>" Institute of Information Jechnology SURBEAM or scmmmemosr ve mentee Pracement intative eed ~ Any changes done in the database while resultset is in use, will reflect into resultset. ~ ResultSet functions: - To fetch records: = boolean last(); i - boolean next; | ‘ ~ boolean previous(); ~ boolean absolute(int row); ~ boolean relative(int relRow); = To check result set position: boolean isBeforeFirst(); - boolean isAfterFirst(); 1 + boolean isFirst(), boolean isLast(); + Updateable ResultSet: - While creating the statement, type and concurrency of result set can be specified. ~ concurrency types: ~ ResultSet. CONCUR_READ_ONLY: + default type using result set records can be only fetched from database. - ResultSet. CONCUR_UPDATEABLE: ~ using resultset records can fetched and also manipulated (insert, update, delete ‘operations can be performer! on the current record), - update related functions = deleteRow(; ~ delete current row from resultset and database - updateRow(): : ~ update changes made in current row into the database. - insertRow0; add newly created row into the database + CachedRowSet: + Inherited from ResultSet interface. ~Fetch all rows into the client memory, so that for accessing each row no need to connect to the database. In this case connection can be closed while data is accessed at the client side (after receiving CachedRowSet). Due to this more number of clients can connect to database. ——————— ‘SunBeam Institute of Information Technology, Pune, Karad_ Page 78SUNBEAM Institute of Information Technology veces Placement initalve ens if large of number of records are fetched into client memory, performance will be reduced (due to shortage of memor ++ Images in database: ‘CREATE TABLE STUDENTS (ROLL INT PRIMARY KEY, NAME VARCHAR(20), MARKS DOUBLE, PHOTO BLOB); = load and register driver = get connection ~ PreparedStatement stmt = con.prepareStatement("INSERT INTO STUDENTS(ROLL,PHOTO) VALUES ey" stmtsetint(1, roll); Blob bl = new BlobClassName(); OutputStream blobOut = bl setBinaryStream(0); FilelnputStream fin = new FilelnputStream("D:\pic.jpg"): int ‘while((b=fin.ead0)!=-1) blodOut write); blobOut. flush); fin.close( biobOut close); stmt setBI0b(2, BD; int ent = stmt executeUpdate() + Transactions: - Transaction is set of SQL statements to be executed as a single unit. [fall statements are executed successfully, then all of them should be commited to database. f any of the statement fails, then already executed statements should be rollbacked ~ example’ try { con.setAutoCommit(false); stmtl = con.prepareStatement("UPDATE stmt2 = con.prepareStatement("UPDATE Ww stmt! executeUpdate() stmmt2.executeUpdate(); con.commit(); } catch(Exception e) { con.rollback(); W lly { I closing SunBeam Institute of Information Technology,
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6134)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brene Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (935)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8215)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2923)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4973)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2061)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1988)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2544)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)