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)
80 views
Java
Uploaded by
a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Java For Later
Download
Save
Save Java For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
80 views
Java
Uploaded by
a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Java For Later
Carousel Previous
Carousel Next
Save
Save Java For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 160
Search
Fullscreen
+ Java language is both a technology and a platfor: + Language: - Programming language is a notation to write program, eg. C, CH, CHetc. - Every programming language has following elements * Syntax Semantics Type System [ Data types ] * Operator Set * Built in features * Standard library and runtime system. - Java has all above elements hence Java is considered as programming language. + Technology : - Using language and technology we can develop the application. - Let's consider example of asp.net. Asp.net helps us to create Web application and web services so itis classified as technology but it is not a language. To implement it we should use G# as a programming language. = Using java, itis possible co create different types of application hence itis considered as technology. + Platform : ~ A platform is the hardware or software environment in which a program runs. - Platforms can be described as a combination of the operating system and underlying, hardware( e.g MS Windows, Linux, Solaris OS, Mac OS etc ) or software only platform( e.g. MS.NET, Java ), - The Java platform has two components: ~ Java virtual machine{ JVM } Java application programming interfacel Java API J. + History of Java : ~ Java goes back to 1991, when a group of Sun engineers, led by Patrick Naughton and James Gosling, wanted to design a small computer language that could be used for consumer devices like cable TV switchboxes. Since these devices do not have a lat of power or memory, the language had to be small and generate very tight code. Also, as different manufacturers may choose different CPU's, it was important that the language not be tied to any single architecture. The project was code-named “Green” ~The requirements for small, tight, and pla¢form-neutral code led the team to design a portable language that generated intermediate cade for a virtual machine. The Sun people came from a UNIX background, so they based their language on C++. ~ Gosling decided to call his language The people at Sun later realized that Oak was the name of an existing computer language, so they changed the name to Java.SUNBEAM Institute of Information Technology = In 1992, the Green project delivered its first product, called “*7."It was an extremely intelligent remote control. Unfortunately, no one was interested in producing this at Sun, and the Green people had to find other ways to market their technology. However, none of the standard consumer electronics companies ‘were interested either. The group then bid on a project to design a cable TV box that could deal wit emerging cable services such as video-on-demand. They did not get the contract. ‘Green project spent all of 1993 and half of 1994 looking for people to buy its technology. No cone was found - First Person was dissolved in 1994, While all of this was going on at Sun, the World Wide Web patt of the Internet was growing bigget and bigger. The key to the World Wide Web was the browser translating hypertext pages to the screen, In 1994, most people were using Mosaic, a noncommercial web browser that came out of the supercomputing center at the University of Illinois in 1993. = In the SunWorld interview, Gosling says that in mid-1994, the language developers realized that ‘we could build a real cool browser, It was one of the few things in the client/server mainstream that needed some of the weird things we'd done: architecture-neutral, real-time, reliable, secure-issues that weren't terribly important in the workstation world, So we built a browser - The actual browser was built by Patrick Naughton & Jonathan Payne and evolved into the Hotava browser, which was designed to show off the power of Java. The builders made the browser capable of executing Java code inside web pages. This “proof of technolowy was sliowii at SunWorld on May 23, 1995, and inspired the Java craze that continues today. + Java Platforms: - Java is not specific to any pracessor or operating system as Java platforms have bees: implemented for a wide variety of hardware and operating systems with a view to enable Java programs to run identically on all of them. Different platforms target different classes of device and application domains - Java Card: A technology that allows small Java-based applications to be run securely on smart cards and similar small-memory devices. - Java ME (Micro Edition) : Specifies several different sets of libraries (known as profiles) for devices with limited storage, display, and power capacities. It is often used to develop applications for mobile devices, PDAs, TV set-top boxes, and printers. - Java SE (Standard Edition) : Java Platform, Standard Edition or Java SE is a widely used platform for development and deployment of portable code for desktop environments - Java FE (Entesprise Edition) : Java Platform, Enterprise Edition or Java EE is a widely used enterprise computing platform developed under the Java Community Process. The platform provides an APT and runtime environment for developing and running enterprise software, including network and web services, and other large-scale, multi-tiered, scalable, reliable, and secure netwark applications. ‘SunBeam Institute of Information Technology, Pune Karad Pagewit} va ——————— ‘SunBeam Institute of Information Technology, Pune & Karad Page & Institute of Information Technology S SUNBEAM. a Java = Notes - Chapter 1 = The Java Programming En JDK and JRE + = SDK is software development kit which is required to develop application ~ SDK = software development tools + documentation + (libraries + runtime environment] ~ JDK is java platforms SDK. It is a software development environment used for developing Java applications and applets. = JDK - java tools + java docs + JRE. = JRE - Java API (java class libsaries ) + Java virtual machine( jvm ). - All core java fundamental classes are part of ar file. JVM and "rtjar" is integrated part of JRE. = To develop application it is necessary to have both i.e. IDK and JRE on developet’s machine. - To deploy java application on client’s machine, it is necessary to install only JRE on client's machine. + Java SE Naming and Versions: - The Java Platform name has changed a few times over the years. ~ Java was first released in January 1996 and was named Java Development Kit, abbreviated IDK. ~ Version 1.2 was a large change in the platform and was therefore rebranded as Java 2. Full name: Java 2 Software Development Kit, abbreviated to Java 2 SDK or J2SDK. = Version 1.5 was released in 2004 as J2SDK 5.0 2€“dropping the “I."from the official name ‘and was further rentamed in 2006, Sun simplified the platform name to better reflect the level of maturity, stability, scalability, and security built into the Java platform. Sun dropped the "2" from the name. ‘The development kit reverted back to the name "JDK" from "Java 2 SDK". The runtime environment has reverted back to "JRE" from "J2RE." ~ JDK 6 and above no longer use the “dot number”at the end of the platform version. + Directory structure of JDK : ~ "fust/lib/jvnvjava-8-openjdk" js a installation directary of JDK in Ubuntu, Following is the directory structure of IDK. Directory structure Description openjdk [The name may be different]. I | bin ‘The compiler and other java tools. docs Library docuimenation in HTML format. [-include Files for compiling native methods. fe jre Java runtime environment files. juib Library files. [este The Iibrary source code{ Extract stc.zip J. J-man6& sunBeam = institute of information Technology sunGeam Een + Simple Hello World Applicatio ~ Let us write simple "Hello World” application using editor{ e.g vim/gediv/Leafpad]. Leaming Initiative The Java Programming Environment ~ class MyProgram ‘ public static void main String]) args ) ‘ ‘System.out printIn("Hello World."); , } ~ Steps to Compile and execute java application. export PATH=/ust/bin/ 1170 locate java tools javac-d. MyProgram java Hroutput : MyProgcam.class export CLASSPATH=.; ITTo locate .class file java MyProgram Ifo execute java app - In the Java programming language, all source code is first written in plain text files ending with the java extension. Those source files are then compiled into .class files by the javac compiler, A .class file dows not contain code that is native to your processor; it instead contains byte codes - the machine language of the Java Virtual Machine (Java VM). The java launcher too! then runs your application with an instance of the Java Virtual Machine. + Bytecode : - java compiler is responsible for generating bytecode, - Itis architecure neutral code. Bytecode is also called as a virtual or managed code. - Using “javap -c"command we can view bytecode. - Bytecode is an object oriented assembly language code which can be understand by the java virtual machine [JVM ]. + Path and Classpath : ~ PATH is an operating systems environment variable which is used to locate “javac" file. - CLASSPATH is a java platforms environment varibale which is used to locate ".class" file. + Let us seperate java file from .class file. Consider the following directory structure. - Complex{ dir }* J |; secl dir} _——— SunBeam Institute of Information Technology, Pune & Karad Page 4Learning Initiative @ SUN BEAM => Institute of Information Technology suman va'~ Notes - Chapter 1 -.The Java Programming Environme: | MyProgram.java k- binf dir) - Now, let us compile and execute MyProgram,java file from Complex directory. export PATH=Hust/bin/; javac -d J/bin/ ./src/MyProgram.java export CLASSPATH=./bin/; java MyProgram ~ After compilation MyProgram.class file will be stored in bin folder. See the following directory structure Complex dir ]* I ir srct dir} i ! | MyProgram,java }- bin dir} | | | [+ MyProgram.class | + Java 8 New Features: - The newest version of the Java platform, Java 8, was released more than a year ago. There are very few good reasons to do this, because Java 8 has brought some important improvements to the language. - There are many new features in Java 8. 1. Lambda expressions. 2. Seam API for working with Collections. 3. Asynchronous task chaining with CompletableFuture, 4, Java Date and Time API. ‘SunBeam Institute of Information Technology, Pune & Karad Page:qe SUNBEAM = Institute of Information Technology Te ‘Java Notes ~ Chapter 2 - The Java Buzzwords Authors of java have written an influential "White Paper" that explains their design goals and accomplishments. + Simple: ~ Since syntax of java is simpler than syntax of C/C++, Java programming language is considered as simple. ~ Consider the following points: * In Java, there is no need for header files. * It does not support pointer and pointer arithmetic. * It does not structure and union. * It does not support friend concept, operator overloading and virtual base class. * It does not support multiple [implementation] inheritance. * [tsupports new operator but not delete operator. * There is no concept of declaration and definition separately. - Another aspect of being simple is being small. One of the goals of java is to enable the construction of software that can run stand-alone in small machines. Ihe size of the basic {cerpreter and class support is about 404; the asic standard libraries and thread support add another 175K. + Object Oriented: ~ Since java sapyutts all major and minor pillars of oops, it is considered as abject oriented programming language. - Java programming language was influenced from its previous successors programming language like (C++, Java developers did not just took everything and implemented in Java but they. analyzed the current challenges in the existing language and then included what is necessary. - The object oriented model in Java is simple and easy to extend and also the primitive types such as integers, ar? retained for high-performance. + Robust : - Following features of Java make it Robust, * Platform Independent: Java program are written once and executed on any platform this ‘makes the job of developer easier to develop programs and not code machine dependent Coding. * Object Oriented Programming Language: helps to break the complex code into easy to understand objects and manage high complexity programs in distributed team environment. * Memory Management: In traditional programming language like C, C++ user has to manage memory by allocating and deatfocating memory which feads to metnory leaks in the program. In Java, memory management is taken care by the Java Virtual Machine and safe from memory crashes. All the allocation and clean of the memory is done automatically. +Ar ins, All the +E ing cor the peand ike ry SUNBEAM =, Institute of Information Technology teaming initiative Java Notes = Chapter 2 - The Java Buzzwords ™ Exception Handling: in Java, developers are forced to handle the exception during the development time. All the possible exception are errored out during the compilation of the program. This way when the exception happens during runtime there is proper exception handling mechanism already coded in the program. + Architecture-Neutral : ~The major challenge when Java was developing is to have programming language with which a program can be developed and executed anytime in future. With changing environments of hardware, processor, Operating system there was need to have program still adopt to this architecture changes = Java code does not depend on the underlying architecture and only depends on it JVM thus accomplish the architecture neutral programming language. -MS.NET is single platform for multiple technology and Java is single technology for multiple platforms. + Portable : - Java programs are not dependant on underlying hardware or operating system. The ability of java program to run on any platform makes java portable. - Number of datatypes and their size is constant / same on all the platforms which makes java portable. - Since java is portable java do not support sizeof operator. + Secure : ~ When Java programs are executed they dona€™t instruct commands to the machine directly. Instead Java Virtual machine reads the program (ByteCode) and convert it into the machine instructions. This way any program tries to get illegal access to the system will not be allowed by the JVM. Allowing Java programs to be executed by the JVM makes Java program fully secured under the control of the JVM. + High Performance: ~ Performance of java is slower than performance of C and C++. - When java programs are executed, JVM does not interpret entire code into machine instructions, If JVM attempts to do this then there will huge performance impact for the high complexity programs. SVM was intelligently developed to interpret only the plece of the code that is required to execute and untouched the rest of the code. - Just In Time compiler (JIT ) has taken place of interpreter which helps to increase performance of the application. reed SunBeam Institute of Information Technology, Pune & Karad Page 2 ree eR area ec eee eee nec ee@. SUNBEAM am Institute of Information Technology Bee : suneeAm earning Initiative + Multithreaded : - If we want to utilize hardware resources( e.g CPU efficiently then we should use threrad - Since java supports multithreading, itis easy to write program that responds to the user actions and helps developers to just implement the logic based on the user action instead to ‘manage the complete multitasking solution. + Dynamic: ~ Methods of the class are by default considered as a virtual. - Java is designed to adapt to an evolving environment hence it is truly dynamic programming language. - Java programs access various runtime libraries and information inside the compiled code (Bytecode). This Uyuamic feature allows to update the pieces of libraries without affecting the code using it. + Distributed : ~ Due tot RMI( Remote Method Invocation }, java is considered as a distributed. - using RMI, program can invoke method of another program across a network and get the output. —— ‘SanBeam Institute of Information Technology, Pune & KaradG SUNBEAM institute of Information Technology oo ER Cee ena causa Geant Rect ca i + Coding Conventions: - Camel case naming convertion: In this case of naming convention, first character of each word except first word should be capital. e.g parselnt. - Use "camel case" naming convention for following elements * fields * method ** method parameter * local variable ~ Pascal case naming convention : In this case of naming convention, first character of each word including first word should be capital. eg StringBuilder. - Use "pascal case" naming convention for following elements. * Type name{ Interface/class/enum ] * File name. ~ package name must be in lower case. ~ Constant must be in uppet case only. + Simple Java Program : - Java is pure object oriented programming language so you can not write anything global. In C/C++ we write main function globly but in Java it must be member of class. For method rnames java follows camel case naming convention so name of entry point method is in lowercase. ~ Consider the following code: import java.lang.*; //Optional to import class Program { public static void main( String[] args ) { System.out.println("Hello SunBeam"); + Characteristics of entry point method : - main is considered as entry poit method in java. ~ syntax : 4€cepublic static void main( String(] args C+. ~ JVM invokes main method. i | iLeaming Initiative ing Structure TErEituear rican we can overload main method in java. ~ per class we can write entry point method. + java.lang System class = package java.lang; import java.io*; public final class System extends Object { iields public static final InputStream i public static final PrintStream out; public static final PrintStream err; Methods public static Console console(); public static-void exit(int status); public static void ge(); public static void foadLibrary(String libname); lend of System class. + System.out.printin : - System : It is a final class declared in java.lang package and java.lang package is declared in rt jar file - Out : Itis an object of PrintStream class and, Out is declared as public static final field in System class. - Printin ; It is non static overloaded method of PrintStream class, +Java.io.PrintStream class : package system.io; public class PrintStream extends .. { 1/Constructors public void flush); public void print(String s); 11Other overloaded print methods public vote printin(String x); SS SunBeam Institute of Information Technology, Pune & Karad Page 2 +Com | +Dat Sun saa ROR CSRS= 5 ® SUNBEAM ==" Institute of Information Technology sunbeam FEUER eA cur racic et 1/Other overloaded printin methods public PrintStream format( String format, Object... args ); public void close(); Viend of class ae + Comments : ~ If we want to maintain documentation of source code then we should use comments. - Java supports three types comments * Single line comment. * /* Multi line comments */ * /** Documentation comments */ ~ If we want to generate java code documentation using java source code then we should use ~ javadoc tool. It comes with jdk. using javadoc we can generate documentation in HTML, format. + Data ‘Types : ~ Data type describes three things: 1. How much memory is required to store the data 2. Which kind of data memory can hold 3, which operation we can perform on the data. - Java is strictly as well as strongly type checked language. In java, data types are classified as: 1. primitive / value types 2. hon primitive / reference types - Value Types : Type Default value boolean undefined false byte byte 0 char 2bytes ‘\wo000" . short 2 bytes 0 int bytes 0 long 8 bytes OL float Abytes 0.0 double Bbytes 0.04 SunBeam Institute of Information Technology, Pune & Karad 3 Learning Initiative Page 3 " | | !6 sunBeam Institute of Information Technology - Wrapper Class: - Java has designed classes corresponding to every primiitive type. It is called as wrapper class. - All wrapper classes are final classes i.e we can extend it. ~ All wrapper classes are declared in java.tang package. - Consider the hierarchy: * java.lang.Object |-Boolean — < final > |-Character «final > |-Number —
| Byte < final > |-Short —< final > J-Integer < final > |-Long «final > |- Float < final > |-Double «final > = Widening: We can convert state of object of narrower type into wider type. it is called as widening int numl = 10; double num: yum; Jhwidening - Narrowing : We can convert state of object of wider type into narrower type. It is called narrowing, double num! = 10.5; int num2=(int) num; //narrowing - Reference Type: ~ Onlly 4 types are reference types in java - following are the reference types in java 1. interface 2. class 3. enum 4, array ‘SunBeam Institute of Information Technology, Pune & Karad Page 4 + Con +Cor—-e jative ng, all ® SUNBEAM - => Institute of Information Technology NCR COeR Se eis Gein aks ue at eck ec Learning Initiative + Command Line Arguments: public class Program { public static void main(String{] args) { int num| = Integer.parseint( args{ 0] ); float num2 = Float.parseFloat( args{ 1} ); double num3 = Double.parseDouble( argst 2]; String operator = args{ 3 J; switch( operator ) double result = num1 + num? + num3; System.outprintin("Result: "“+result); } } } ‘Mnput from termial : java Program 10 20.1f 30.24 + + Console Input Output : ~ In java there is no standard way to take input from console. = we can use any one of the following way to take input : 1. Console is 2 class declared in java.io package Console console = System.console(); String text = console.readLine(); 2. JOptionPane is a class declared in javax.swing package String text = JOptionPane.showInputDialog("Enter text"); JOptionPane.showMessageDialog(null, text); 3. BufferedReader is class declared in java.io package BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader(System.in)); String text = readerreadLine(); 4, Scanner is a class declared in java.util package. ae! ‘SunBeam Institute of Information Technology, Pune & Karad Pages@. SUNBEAM instituté’of Information Technology Learning Initiative FEE ee ee cee ui mie Scanner sc = new Scanner(System.in); String text = sc.nextLine(); + Boxing : = Itis the process of converting state of object of value type into reference type. - Consider the example: int number = 10; String strNumber tring. valueOf( number ); ~ If boxing is done implictly then itis called autoboxing, - Consider the example: Object obj = 10; /AutoBoxing itis internally works like Object obj = new Integen( 10 ); + UnBoxing : - It is the process of converting state of object of reference type into value type. ~ Considert the example: String stiNumber = "125"; int number = Integer.parselnt( stNumber ); - If unboxing is done impliitly then it is called as autounboxing - Considert the example: Integer obj = new Integer(10); int number = obj; //AutoUnboxing SS SunBeam institute of Information Technology, Pune & Karad Page 6 sac fl q 4 + Classpat -It “2 + Package if use packag oP if 6 ott -d -N put a da== Institute of Information Technology sureean @ sunNBeam ré Pracement iniative EE hapter 4 - Package + Path: = Its operating system platform’s environment vatiable which is used to locate java tools. ~ export PATH=/ust/bin/ + Classpath - It is Java platforms environment variable which is used to locate .class file. - export CLASSPATHE./bin + Packag: ~ If we want to group functionally equivalent or functionally related classes together then we should use package. ~ Package can contain following elements: * Sub package * Interface * Class *Enum * Error * Exception * Annotation - Advantages of package * To avoid name clashing/ collision ambiguity * To group functionally related classes together. ~ Kf we want add class in package then we should use package keyword eg package pl; class Complex { } ~ package statement must be the first statement in java file. import java.util. Scanner; package pl; //Error class Complex { } we can not declare multiple packages in single java file. package p1; package p2; //Error class Complex { } ~ package name is physically mapped with folder. ~ Default access modifier of the class is package( default), package pl; 22? class Complex —_// 22? > package level private { } ~ If we want to access any Type outside the package then we should declare that type public. ~ ass can have either package or public access m Package pl; public class Complex a) ~Name of public class and java file must be same hence in single Java file we cannot write multiple public classes. - 8 file can contain muiple non-public classes but can contain a the most only one public class, ae& SunBeam Institute of Information Technology Teomme lative ea TE we want to use packaged class outside the package then we should use either fully qualified class name or import statement, ~ Consider the example: class Program { public static void mai { t String{] args ) pL.Complex cl = new p{.Complex(); Ok J or import p1.Complex; //Look Here class Program ( public static void main( String{] args ) { Complex cl = new Complex); /0k } } = We can access packaged class in unpackaged class. - If we declare class without package then it fs considered as a ueuber of default package. We cannot import default package hence it is not possible to access unpackaged class in packaged class. "Complex. java" public class Complex. { iz #0DO “Program,java" package p2; public class Program { public static void main( String[] args ) { } Complex cl = new Complex; //Error ) ~ We can add multiple classes in Single package. In this case we can access class directly within same package. "Complex.java” package pl; public class Complex ( JODO a ‘SunBeam Institute of Information Technoiogy, Pune & Karad Page 2 ‘Surative stass ~~ SUNBEAM TE Institute of Information Technology . mn initiative Boe ek keer - 8 5 a ure. “Program,java" package p1; public class Program { public static void main( Stringf) args ) { } Complex cl = new Complex; Ok } ~ we can declare package inside package. Its called sub package. package pl.p2; __//Here p2 is sub package public class Complex { wODO J ~ IE we want to access types outside package then we should use import statement and if we ‘want to access static members of packaged class outside package directly then we should Use static import, import static java.lang Math.PI;, import static java.lang. Math. pow; import static java.lang System.out; public class Program { public static void main(String} args} { Aouble radi double area = PI * pow( radius, 2); ourprintin("Atea =: "4atea); 7 } = Most commonly used packages in java: * javalang * java.util *javaio *javanet * javarmi * java.lang.reflect » javasql * javarmi SunBeam Institute of Information Technology, Pune & Karad Page 3©, SUNBEAM.. = Institute of information Technology Learning Initiative Java Notes = Chapfer.4-=Package. Since javalang package is by default imported in every java file, itis optional to import java.lang package. + Jar: - using jar ton! we can group packages together. Jar tool creates jar file. - If we want to create reusable component in java then we should take help of jar file. = Steps to create jar file from eclipse: * create java project and add ciasses init. * Right click on project-> Expott-->Java-->Jar File-Next->Brozse... ->.jar -> Finish. - Steps to add jar file in runtime classpath or buildpath: * create java project. * Right click on project-->#uild Path—->Configure Build Path->Java Build Path-> Libraties-> Add External Jars--> Select jar file and then click on ok. * import package and use types. — SunBraza Zastitute of Information Technology, Pune & Karad Page 4 de 6 g a + Class: =Itis -Cla -Inj - Ob, + Instance -0 a] Cc + Constr Javadang, |all | 6 SUNBeaAm Institute of Information Technology i sunbeam Placement Initiative FEY ei) en ea ae + Class: ~ Iti a collection of fields and methods * Field - data member is called field in java * Method - member function is called method in java ~ Class is reference type ie instance of class get space on heap section, - We can achieve encapsulation using class. ~ In java every class is by default extended from java.lang. Object class. +Javalang.Object: - Object is non final concrete class declared in java.lang package. - In java every class extends Object class directly or indirectly. ~ Methods declared in Object class: * protected Object clone() throws CloneNotSupportedE.xception * public boolean equals(Object obj) ~ public int hashCode() * public String toStringQ) * protected void finalize() throws Throwable * public final Class getClass() * public final void wait()throws InterruptedException * public final void wait(long timeout)throws InterruptedException * public final void wait(long timeout,int nanos) throws InterruptedException * public final void notify() * public final void notifyANQ) | | + Instance: ~ Object is called instance in java, ~ To create instance itis necessary to use new operator. - Consider the following code snippet: * Complex cl; reference *new Complex; “instance * Complex cl = new Complex(); Complex c2=cl; //Shallow Copy of references. + Constructor: = Itis method of class which is used to initialize the object or instance. ~ Java do not support default argument. Hence it is possible to call one constructor from another constructor. It is called constructor chaining, ~ If we want to reuse implementation of existing constructor then we should use constructor chaining. using this statement we can achieve constructor chaining. - this statement must be the first statement in constructor. lass Complex { private int real; private int imag; i public Complex()this(0,0); ctor chaining } public Complex(int real, int imag) { this.real = real; this imag = imag; } — } 7 J + Final variable: - After storing value inside varible, if we dont want to modify value of that variable then we should declare such variable as final. - final is keyword in java. = we can declare reference as a final but we can not declare object as a final. + Static in java: = In java we cannot declare local variable as a static, ~ If we want to share value of field in all che instances of same class then we should declare field as a static. - Static field do not get space inside object hence we should access it using class name. To initialize the static field we should use static block. we can write multiple static blocks inside a class. - JVM executes static block at the time uf class loading. = Ta acvess state of non-static member we should define non static method inside class and to access slate of static member we should define static method inside a class. ~ In non-static method we can access static as well as non-static members. = Static method do not get this reference hence in static method we cannot access non-static members. = Using object/instance we can access non static members inside static method. + Singleton Class: ~ a class from which we can create only one instance is called singleton class. ~ Consider the following code.. class Singlton { private Singleton() a) private static Singleton singleton; public static Singleton getInstance() { if( singleton == null ) singleton = new Singleton(); return singleton; } ) 7 SunBeam Institute of Information Technology, Pune & Karad Page2 + Single D [ .nitiative _| ould dea abers, SUNBEAM Institute of Information Technology re Placement Initiative pes eed = Itis collection of same type of elements where each element get space continuously. = It is collection of fixed elements i.e it cannot grow/shrink at runtime. ~ Arrays are reference types in java ie to create array instance we should use new operator = There are three types of array in java: * Single dimensional + Multi-dimensional Ragged Array + Single Dimensional Array: ~ int aril, TArvay reference : Ok ~ imt{] arr; Array reference : Recommended + int{] arr = new int{ 3]; Array instance yew int{ }{ 10, 20, 30 };, MInitialization 40, 20,30 }; ‘Maitialization : valid ~ Accessing elements using for loop for( int index = 0; index < arrlength; ++ index ) System.out.printin( arf index ] ); ~ Accessing elements using for each loop for{ int ekement : art) System. out. printin( element ); +Multi-Dimensional Array: - Array of array which contains same number of elements is called Multi-dimensional Array. ——— ~ int arfIQ]; Array reference : Ok “| ~int{] arr]; NiArray reference + int{}{] ar; i#Asvay reference : Recommended = int{]{) arr = new int(2][3]; J/Aaray instance ~ int{I[] arr = new int{2}[3]{ {10, 20, 30}, (40, 50, 60} }; Initialization ~ int{}{] arr = { {10, 20, 30}, (40, 50, 60} }; initialization ~ Accessing elements using for loop fort int row = 0; row < arzlength; ++ row) { for( int col = 0; col < arrf row ].length; ++ col ) { ‘System. out printhn(arr{row feot]); } } ~ Accessing elements using for each loop for(int] artRef : arr ) { fort int element : artRef ) { System.out-printin(element); a6 SsunBeam Institute of Information Technology 3 Tn eke oo ea ae + Ragged Array: ~ Array of array which contains diff. number of elements is called ragged Array. int anf]0; Asray reference : Ok = imi{]0) arr, Array reference : Recommended + int{]{] arr = new int(3]0]; WAxray of references anf 0 ] = new int{ 2}; ar{ 1] = new int{ 3 J; arr{ 2] = new int{ 4]; ~ Accessing elements using for loop I for( int row = 0; row
Composition #is-a/kind-of --> Inheritance #use-a —> Dependancy #creates-a > Instantiation + Minor Pillars / Parts / Elements of QOPS: ~ Typing / Polymorphisin * Ability of an object to take multiple forms is called polymorphism. * Using polymorphism we can reduce maintenance of the system, * We can achieve it using # Method Overloading # Method overriding ~ Concurrency * Process of executing multiple task simultaneously is called concurrency. * We can achieve it using threading. ** Process of maintaing state of the object in file or database is called persistence, Pycementing Learning Initiative Java Notes - Chapter7 - OOPS + Composition: - Composition is also caiied as containment, - If has-a relationship exist between two types then we shoud use composition. eg Carhas-a engine - If object/component is part of another object then itis called as composition. ~In java composition do not implies physical containment. Composition is achieved using reference variable only. = In other words object outside the object is called composition. - Consider the example: lass Person { private String name = new String(); Private Date birthDate = new Date(); private Address curraddress = new Address(); wropo ) + Inheritance: + Inheritance is also called as generalization. - If s-a relationship exist between two types then we should use inheritance. - Without modifing existing class if we want to extend meaning of the class then we should use inheritance. - In java, parent class is called super class and child clas is called sub class. ~ to create sub class we should use "extends" keyword ~ consider following example: class Shape = (3 class Circle extends Shape to ~ Sub class can extend at the most only one super class. i.e, multiple implementation Inheritance is not allowed: class Af } dassB{ } class C extends A, B_ //Not Allowed in java £ 3 ~ Java supports only public mode of inheritance. ee SunBeam Institute of Information Technology, Pune & Karad Page 2& sunBeam Institute of information Technology {In same package | Indiff package Same class Sub class Non sub class | Sub class Non Sub class FE private A NA NA | NA, NA spiteren | package =A A A NA NA { I protected = A A A | OA NA L public A A A A A - If we Create instance of sub class then first super class constructor gets called and then sub class constructor gets called. = In Java class do not contain destructor. ~ using super statement, we can call any super class constructor from sub class constructor. = If we want to access members of super class in method of sub class then we should use super keyword, + Upcasting and Downcasting: - we can convert reference of sub class into reference of super class. Its called upcasting. eg. Employee emp ~ new Emioyee("Sandeep",33,45000); Person p=emp; —_/Upesting. r - We can convert reference of super class into reference of sub class. Itis called downcasting, | eg Person p= new Emloyee("Sandeep",33,45000); Employee emp = (Employee ) p; _/MDowncasting If downcasting fails then JVM throws ClassCastException. ~ In java all the methods are by default virtual hence using super class reference variable we can cal) ‘method of sub class. It is called dynamic method dispatch. — + Rules of method overriding: 1. Signature of super class and sub class method should be same. 2. Access modifier of super class and sub class method should be same or it should be wider than super class method. Se erearr Terenas A jai Initiative perf i } _ So -SUNBEAM = Institute of Information Technology sueeam teaming Initiative FENEWD Cosa eek eae '3, Retum type of super class and sub class method should be same or it should be sub type ‘of retum type specified in super class method. 4, Method name, number of parameter and type of parameter pass to the method must be same. 5. Checked exception list specified in sub class method should be same ot it should be subset of exception list specified in super class method. + Difference between == and equals method: if we want to compare state of object of value type then we should us operator. [— int num: 10; int num2 = 10; if(num1 == num2 ) System. out.printin("Equal”); | else | System. out.printin("Not Equal"); Output : Equal ~ if we want to compare state of variable of reference type then also we should use [ ‘Complex cl = new Complex(10,20); Complex ¢2 = new Complex(10,20); | if(cl == 2) | System.out.printin("Equal"); Ll else System.out printin("Not Equal"); Outpot : Not Equal = if we want to compare state of object of reference type then we should use equals method. | Complex c1 = new Complex(10,20); | Complex c2 = new Complex(10,20); if( cLequals( 2 )) System.out printin("Equal"); else System.out printin("Not Equal"); Li /Ourput: Equal * if class do not contain equals method then super class equals method gets called. Asl if any super class do not contain equals method then Object class equals method gets called. Object.equals always compares object reference. * To compare state of the object we should override equals method in class. * For example: —_———————— ‘SunBeam Institute of Information Technology, Pune & Karad Page 4 aSUNBEAM... — Institute of Information Technology ee ain é Java’ Notes ~ Chapter 7. OOPS ‘Part Ul — class Complex 7 t private int real; private int imag; @Override public boolean equals(Object obj) ( | | iff obj != null) | | | le { Complex other = (Complex)obj; if( shis.real == otherreal 8:& this.imag return true; otherimag ) } return false; + Final method: - If implementation of super class method is logically complete then we should declare super class method as final = We van not override finial method in sub class. But final method inherit into sub class. - Some of the final methods are: * public final Class getClass() public final void wait() throws InterruptedException * public final void notify() * public final void notifyAll) + Abstract: -Ifi decl -At olf a + Fragt + Final class: If implementation of all the methods is logically complete then instead of declaring ries method as final we should declare class as final, ~ we catt not extend final class ie we car create sub class af fina class, } ~ Some of the final classes are: Psa All Wrapper classes. : * javalang.Systern i * javalang String i * javalang StringBuffer 4 | aispar * java.lang.StcingBuikder group * java.lang.Math | Gener: ‘SunBeam Institute of tnformation Technology, Pune & Karad Pages {_ | SunBe L =aitiative G sunBeam “Institute of Inforfiiation Technology eee Java: Notes ~ Chapter 7 + Abstract method: ~ {€ implementation of super class method is logically 100% incomplete then we should declare super class method as abstract. ~ Abstract method do not contain body. - If method is abstract then itis compulsory to declare class as abstract. ~ if super class contains abstract method then sub class should override that method in sub class or sub class should be declared as abstract. = we cannot overtide private, final and static method in sub class hence such keywords cannot be used with abstract method. - Some of the abstract methods declared in Number class ace: * public abstract int intValue() public abstract float float Value() ™ public abstract double doubleValueQ) * public abstract Jong longValue() + Abstract class: ~ {€ implementation of any class is logically incomplete then we should declare class as abstract. - If class contains abstract method then we should declare class as abstract. = Without declaring method as abstract we can declare class as abstract. ~ We cannot create instance of abstract class but we can create reference of abstract class, ~ Abstract class can contain constructor, ~ Some of the abstract classes are: * java lang Enum, * java.lang. Number + Fragile base class problem: = Hf we make changes in super class method then it is necessary to recompile all the sub classes is called fragile base class problem. ~To avoid fragile base class problem we should declare super type as a interface. + Interface: ~ Set of rules is called standard and standard is also called as specification. ~ If we want to define specification for the sub classes then we should use interface. - There are a number of situations in software engineeting when itis important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. ‘Generally speaking, interfaces are such contracts. Interface is keyword in javé er SunBeam Institute of Information Technology, Pune & Karad Page 6& SUNBesm.-. ee Institute of information Technology suena Java Notes -.Chapter 7 - GOPS - Part'll ~ Interface is reference type. F Learning Initiative - Interface an contain only constants, method signatures, default methods, static methods, E and nested types. = Interfaces cannot be instantiated , they can only be implemented by classes or extended by e other interfaces. = Observe the following statements: interface : 11, 12, 13 Class :C1, C2, C3 F * 12 implements 12 iMncorrect t * [2 extends [1 correct : Interface inheritance * 13 extends 11, 1? Meowvect ; Multiple interface inheritance * C2 implements C1 silncortect * C2 extends C2 correct : Implementation Inheritance * C3 extends C1,C2 ‘incorrect : Multiple Implementation fulweritance *Textends C1 sMncorrect * 11 implements C1 incorrect * cl implements iL Meorrect : Interface implementation inheritance * cl implements 11,12 //correct : Multiple Interface implementation inheritance * c2 implements 11,12 extends C1__/lucomect | * c2 extends C1 implements [1,12 _ //correct = If we want to impiement interface then we should use implements keyword. interface A { void £10: } class B implements A { @Override public void £10 {J L iH = If class implement multiple interfaces which contain methods with same signature then sub class can override it only once. interface A { void F103 } interface B ST ‘SunBeam Institute of Information Technology, Pune & Karad Page 20| SUNBEAM... ey ~ Institute of Information Technology mae ENERO ee) een ee void £10; } class C implements A, B u @Override public void £10 { 3 } = If class implement multiple interfaces which contain methods with same name and different return type then sub class can not override it interface A { int £105 } interface B { double f10; } class C implements A, B { /ferror: Can not override method in sub class a) + Default Methods: ~ Designing interfaces have always been a tough job because if we want to add additional methods in the interfaces, it will require change in all the implementing classes. As interface grows old, the number of classes implementing it might grow to an extent that it is not possible to extend interfaces. That is why when designing an application, most of the frameworks provide a base implementation class and then we extend it and override methods that are applicable for our application, ~ To overcome such problem, in java 8 , we can add default methods in interface. - For creating a default method in java interface, we need to use “ default” keyword with the method signature, interface A { void £1(String str); default void log(Swing str) { —CO SunBeam Institute of Inforination Technology, Pune & Karad Page 9 G& SUNBEAM. Institute of information Technology = Notice that log(String str) is the default method in the Interface A. Now when a class will implement |* interface A, it is not mandatory to provide implementation for default methods of interface. This feature will help us in extending interfaces with additional methods, all we need is to provide a default implementation. = We know that Java doesn’t allow us to extend multiple classes because it will result in the “Diamond Problem” where compiler cannot decide which superclass method to use. With the default methods, the diamond problem would arise for interfaces too. ~ Some key points about default method: » Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes. * Java interface default methods has bridge down the differences between interfaces and abstract classes, * Java 8 interface default methods will help us in avoiding utility classes, such | asall the Collections class method can be provided in the interfaces itself * Java interface default methods will help us in removing base implementation classes, we can provide default implementation and the implementation classes can chose which one to override. * One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions. A default method cannot override a method from java.lang.Object. * Java interface default methods are also referred to as Defender Methods or Virtual extension methods. + Interface Static Method: - Java interface static method is similar to default method except that we cana€™t override them in the implementation classes. Important points about java interface static method: * Java interface static method is part of interface, we can’t use it for implementation class | objects,SUNBEAM... => Institute of Information Technology Learning initiative eA eee a * Java interface static methods are good for providing utility methods, for example null check, collection sorting etc. Xen coers ~ Java interface static method helps us in providing security by not allowing implementation classes to override them. = We can’t define interface static method for Object class methods. * We can use java interface static methods to remove utility classes such as, Collections and move all of it’s static methods to the corresponding interface, that would be easy to find and use. + Functional Interface: = An interface with exactly one abstract method is known as Functional Interface. = Anew annotation @Functionalinterface has been introduced to mark an interface as Functional Interface. - @Fanctionallnterface annotation is a facility to avoid accidental addition of abstract ‘methods in the functional interfaces. It’s optional but good practice to use it. - Functional interfaces enables us to use lambda expressions to instantiate them. - java.util.function package contains functional interface that are targeted to lambda expression. te of Information Technology, Pune & Karad Page 106& SunBeam = Institute of Information Technology Evew aed + Exception Handling: - An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. ~ To manage OS resources carefully, we should handle exception. -To handle exception we should use following keywords: * try -to inspect the exception * throw - to generate the exception * catch - to handle the exception * throws - to redirect the exception * finally - to release the local resources. - java lang. Throwable is super class of Error and exception in java. - Exceptional conditions that are internal to the application are exceptions. ~ Exceptional conditions that are extemal to the application, and that the application usually cannot recover from are errors. + Throwable class: - Constructors: * public Throwable() * public Throwable(String message) * public Throwable(Throwable cause) + public Throwable(String message,Throwable cause) - Methods: * public final void addSuppressed(Throwable exception) * public StackTraceBlement{] getStackTrace() * public Throwable getCauseQ) * public String getMessage() + public void primtStackTrace() + Types of Exception: - Checked and UnChecked are the types of exception. These are the types of exception designed for compiler. = Checked Exception * java.lang Exception and all its sub classes except RuntimeException class are classified as checked exception classes. * Iis compulsory to handle checked exception otherwise compiler generates error. * eg InterruptedException, ClassNotFoundException etc - UnChecked Exception * java.lang-RuntimeException and all its sub classes are classified as checked exception classes. * Itis optional to handle unchecked exception,rat -& SUNBEAM. . —— 7 Institute of Information Technology PREC Leaee U) ion, ClassCastException etc, 4 suneeam Learning Initiative *e, + StackTrace : - Astack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred. = Astack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown. + Syntax: - wy = { BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader(System.in)), System.out.print("Enter num "5 int num1 = Integerparselnt(reader.readLine()); ‘System. out.print("Enter num2 ” {int num2 = Integer parselnt(reader-readLine()); int result = num1 / num2; | System.out.printta("Result “result; | reader.closeQ); } catch (NumberFormatException e) { e,printStackTraceQ); y catch (ArithmeticException e) { e printStackTrace(); , catch (IOException e) { e-printStackTraceQ); } - It is possible to handle all the exceptions in single catch block. try { BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader(System.in)); ee ee ee SunBeam Snstitute of Information Technology, Pune & Karad Page 2 38° @ sunBeam_ Institute of Information Technology 6. System.out.print("Enter num) "; int num{ = Integer.parselnt(reader.readLine()); System.out.prin(("Entermum2 =: "js int num2 = Integer.parselnt(reader.readLineQ)); int result = num / num! System.outprintin("Result: "+result); reader.clase(); } catch (NumberFormatException | ArithmeticException | IOException e) ( e-primtStackTrace(); } - If you want to release local resources then you should define finally block ‘Scanner sc = null; ty { se = new Seanner(Systeu.in); Systemoulprint("Entermumt =: "J int Auml ~ seanextImi(); System. out print("Enter num2 Y int num? = se.nextInt(); int result = num} /num2; System.out peintin("Result “result); { — e-printStackTrace(s } finally { sc.close(); } i | 3 catch ( ArithmeticException | InputMismatchException e) = try-with-resources * Arresource is an object that must be closed after the program is finished with it * Instance of class which implements either AutoCloseable or Closeable interface is called resource, eed ‘SunBeam Institute of Information Technology, Pane & Karad Page 3 SunBe = 8F System.out printin("Result “+result); } —_ catch ( ArithmeticException | InputMismatchException e) —T11 : | e.printStackTrace(); L } ie | & SUNBEAM - . = Institute of Information Technology suman Learning Initiative Java Notes - Chapter 8-- Exception Handling * If we use resource with try then there is no need to close the resource in finally. When block of code gets executed normally or by throwing exception then close method of resource gets called automatically. * consider the following code: ‘try( Scanner sc = new Scanner(System.in); ) { Systemoutprint("Enter num! : ——"); .cnextintQ; System out print("Enter num2 int num2 = sc.nextintQ; int result = numt / num2; int num: j ~ A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. - Some exceptions are designed to handle. If we do not handle it then compiler generates error. Consider the following code: public static void print { | for{ int i= 151 < 10; ++i) { I System.out printin(i); ‘Thread sleep(300); //Compiler error } ) = sleep method throws InterruptedException, which is checked exception, We must handle it HT public static void print() { Fy ty { for{ int i= 151 < 10; ++i) { System,out.printin(i); Thread.sleep(300); Now Ok } } SunBeam Institute of Information Technology, Pune & Karad Page 4 a —————————— |SUNBEAM... Institute of Information Technology E catch (InterruptedException e) { e.printStackTrace(); J Learning Initiative BOM coca isc neu cular) 3 - If we want to redirect exception to caller of the method then we can use throws clause. public static void print() throws InterruptedException £ fort inti { System.out.println(i); ‘Thread sleep(300); <10; ++i) } } - throws clause can be used to redirect any checked as well as unchecked exception. | Generic Catch: ~ Exception lass ea keep referance of any checked as well as unchecked exception hence it is used to write generic catch, ~ Remember, compiler do not allows us to handle super type exception first. So gemeric ‘catch must appear at fast. + Summary: ~ using try, catch, throw, throws and finally we can handle exception in java. = try block may have multiple catch block but single try block must have at lest one catch finally or resource. - we can handle multiple exceptions in single catch block also. = generic catch must appear at last. - Handling checked exceptions is compulsory. If we do not handle it then compler gives err, To handle checked exception we should use either try-catch block or we should redirect exception to caller method using throws clause. ~ To release local resources we should use finally block. - JVM always execute finally block. If we write System.exit(0) in try and catch block then JVM do execute finalty block. + Chained Exceptions: ~ Generally exceptions are handled by throwing new exception. This process of handling exception is called exception chaining, Following Methods and constructors in Throwable that support chained exceptions: SunBeatn Institute of Information Technology, Pune & Karad Page 5 — + Cortiative Page 5 | | 6 SUNBEAM _ "Se = Institute. of Information Technology P= * Throwable(Throwable) * Throwable(String, Throwable) * Throwable initCause(Throwable) _* Throwable getCause() ~ consider the following example: try { “TODO } catch (SQLException e) { throw new SerevletException("‘Other SQLException”, e); // Exception Chaining } _ = + Consider the following code snippets: L ] int{] arr = new int{ }{ 10, 20, 30 }; int element = arf 3 J; /ArrayindexOutOfBoundsException ‘Suing str = "Sandeep"; char ch = str.charAt(7); /StringIndexOutOfBoundsException ‘ArrayList
list = new ArrayList<>Q; listadd(10); listadd(20); | list.add(30); int element = list get(3); /indexOutOfBoundsException ‘Object obj Méowncasting String str = ( String Jobj; / ClassCastException ew Integer( 10); String str = "A123"; Lt int number = Integer.parselnt(str); // NumberFormatException ‘SunBeam Institute of Information Technology, Pune & Karad. x Learning Initiative ‘| Page 6@. SUNBEAM... re Institute of Information Technology sunbeam ie PONE cee Su en Cuts | + Generics: F Like object, we can pass data type as a argument to the function. Hence parameterized type is - genetics. In C+, itis called as template, - First let us discuss generic class using java.lang.Object class. Consider the following code, class Box { private Object object; public Object gerObject() { retum object; } Public void setObject(Object object) { Le this.object = object; } — } Box box = new Box(); int mum ~ 10; ia box. serChjert(num1)j/fbox.setObject(new Integer(nurnl)); int num2 = (inJbox.getObject; Ok Le 2. L Box Lox = new Box0; ,_ Date dtl = new Date); box.sethject(ata); MUpCasting | Date dt2 = (Date)box.getUbject; _ /DownCasting 3 — Box box = new Box; Date dt1 = new Date); | box.setObject(dtl); + ss+ HUpCasting. i String str = (String)box.getObjectQ; /DownCasting : ClassCastException i +M ‘ + Why Generics? ! 1. Generics gives us stronger type checking at compile time, i 2. It completely eliminates explicit type casting. i 3. Using generics we can write generic algorithm. i = qL Initiative & Learning ive Let's us consider following cod [dass Box< T> iT is Type parameter { 1 private T object; | public T getObject() ( return object; } public void setObject(T object) | { this.object = object; Box
box =new Box
Q; _ //Error In above code, int is type argument. Type argument used in generics must be reference type. = ‘Box
box = new Box
Q; /OK If we want to store primitive values in genetic collection then we should use wrapper l class. Box
box = new Box
(); box.setObject(new Date()); String str = (String)box.getObject(); /Compiler error : src and dest must be Date type. Box
box = new Box
(; box.setObject(new Date()); Date date = box.getObject(); OK * Most Commonly used type parameters in java: T - Type N= Number E = Element Ko. Key e———_—_— SunBeam Institute of Zaformation Technology, Pune & Karad Page 2 aeSUNBEAM *Ynstitate of Iriformation Technology A,U - Second Type Parameters. We can specify multiple type parameters ton, interface Map
( ‘void put( K key, V value ); K getkey(; V getValue(); } class HashTable
implements Map
{ private K key; private V value; public void put( K key, V value ) { #/PODO : Assigninent for programnier } @Override | public K getkKey() 1 { retumn this.key; 2 Covers fable V getValue() pene return this.value; : al | } public class Programa { public static void main(String[] args) { ‘Map
map = new HashTable<>(); * UnBow map put(1, “Sandeep"); pu map.put(2, "Prathamesh’ I: { map.put(3, "Soham"); : | ‘SunBeam Institute of Information Technology, Pune & Karad Page 3 SunBeam ainstitute of Information Technology a r @- SUNBEAM... Initiative coeeam Learning initiative ia CMs eeu + Bounded Type Parameter : - Sometimes we need to put restrictions on a type that can we used as type argument. Using bounded type parameter we can put restriction on type argument. class Box< Nextends Number > __//N extends Number => is bounded type parameter. ‘ private N object; public N getObject() ‘ retum object; oy void setObject(N abject) ‘ this.object = object; } } Box-Integer> box = new Box<>(); Allowed 2 Box
box = new Box<>(); Not allowed +Wild Card: ~In generics ?is called wild card which indicates unknown type. ~ There are 3 types of wild card in generics. 1. UnBounded Wild Card. 2. Upper Bounded Wild Card. 3, Lower Bounded Card. + UnBounded Wild Card : public static votd printList( List list) t for (Object object: list) { System.out printin(object); } a SunBeam Institute of Information Technology, Pune & Karad Page 4 «aInstitute of Information Technology & SUNBEAM. Learning Initiative |; List
list = new ArrayList<>(); #MODO: Add element in list? Program, printLis(list1), i i ‘ i ' List
list2 = new Vector<>0); ITODO: Add element in list2 Program.printList(list2); : WTODO: Add element in list3 Program,printList(list3); ~ As shown in above code, list can store reference of any List<> collection which contains any type of element. : + Upper Bounded Wild Card: public static void printList( List list } { , i : List
list3 = new LinkedList<>Q; fe | Vd } ' for (Number uunibee: list) | { i System out.printIn(number); } List
listl = new ArrayList<>(; MTODO: Add element in list Program. printList(ist2); List
list2 = new Vector<>(); WTODO: Add element in list2 | Progeam.printList(list2); List
list3 = new ArrayList<>(); MTODO: Add element in list3 Program.printList(list3); HINot Allowed | te of Information Technology, Pune & Karad Page 5Page 5 SUNBEAM ~ Fé Institute of Information Technology BEN ened As shown in above code, list can store reference of any umber. + Lower Bounded Wild Card: public static void printList( List list ) { for (Object object: list) { System out printin(object); } } 7 - List
list = new ArrayList<>Q; MTODO: Add element in listt Programs printList(listl); List
list2 = new Vector<>(Q); | fMODO: Add element in list2 Program.printList(list2); Not Allowed List
list3 = new ArmayList<>0; /EODO: Add element in list3 Progeam.printList(list3); Not Allowed = As shown in above code, list can stare reference of any List<> collection which contains elements of integer or its super type. public static void printLisi( List
list ) { mobo } Public static void main(Stringl] args) { List
list1 = new ArrayList
(); Program.printList(listl); Error ~ In case of type argument, inheritance is not allowed. As shown in above code, type argument used in List is Number and type argument used iz ArrayList is integer. It must be same, ye ed ‘SunBeam Institute of Information Technology, Pune & Karad Page 6 4sInstitute of Information Technology 6& sunBeam a) Placement Initative GE anes + Marker Interface: = An interface which do not contain any member is called marker interface. - following are the marker interface: » java.lang.Cloneable ~ java.util. EventListener * java.util RandomAccess * javaio Serializable * javacmi.Remote + Commonly used interfaces in java: - java.lang.Cloneable - java.lang AutoCloseable - java.lang.Comparable
- java.util, Comparator
~java.lang.{terable
~ java.uti.{terator
- java.lang Runnable + Cloneable: - Its interface declared in java.lang package. ~ Ibis marker interface. ~ consider the following code: Complex cl = new Complex(); Complex c2= cl; //Shallow Copy of references ~ If we want to create new object from existing object then we should override clone() method, @Override public Complex clone() throws CloneNotSupportedException t Complex other = ( Complex )super.clone(); return other; } ~ If we want to create shallow copy of current object then we should use "super.clone()" - Without implementing Cloneable interface, if we try to use clone method then it throws CloneNotSupportedException. + Comparable: = It is interface declared in java.lang package. “int compareTo(T 0)" is method declared in Comparable interface. ; 'SUNBEAM Institute of Information Technology Learning ERC CORR cue Cae ~ If we want to sort array of object of same type then we should use Comparable interface. ~ Consider the following example: class Employee implements Comparable
{ @Override public int compareTo(Employee other) { if( this.empid < other.empid ) return -1; clse if{this.empid > otherempid ) return 1; else return 0; | } public class Program { public static Employee(] getEmployees() { } public static void main(String{] args) { Employee(] arr = Program.getEmployees(); Arayssort(arr); a + Comparator: = Itis interface declared in java.util package. - It is functional interface. - "int compare(T 01,T 02)" is method of Comparator interface. - If we want to sort aray of objects of different types then we should use Comparator interface. - Consider following example: abstract class Person{ } class Student extends Person{ class Employee extends Person{ class SortByld implements Comparator
in - a so rE SunBeam Institute of Information Technology, Pune & Karad Page 2 Pdpublic int compare(Person p1, Person p2) { sODO return 0; } y public class Program { public static Person{] getPersons() { } public static void main(String|] args) { Person{] persons = Program. getPersons(); jew SontByld0; Comparator
comparatoi Arrays som(persons,comparator); 1 + Iterator: ~ Itis smart pointer which is used to traverse the collection. ~In java for each loop is called iterator. ~ We can traverse elements of array or object which implements java lang, lerable interface Consider the folloiwing code Class Node { } Class LinkedList implements Iterable
{ private Node head = null; #t0DO @Override public lterator
iterator() { bl fterator
itr = new LinkedListIterator( this,head ); fe return itr; iB ) H } 7 Hf ‘SnBeam insu of Information Technology, Pane & Karad Pages |) | Se L a iInstitute of Information Technology 6 SUNBEAM BENE M ics aha Cees ae) class LinkedL istiterator implements fterator
{ Node trav; LinkedListlterator( Node trav ) { this trav = tray; } @Override | public boolean hasNext() { return this.trav != null; } Override public Integer next() { int data = trav.data; trav = travnext; return data; } } Page3 |) SunBeam Institute of Information Technology, Pune & Karad Learning Initiative Page 4& SUNBEAM. Institute of Information Technology ia cureeain Placement itive eect kates En eure + Nested Class: - In Java we can write cfass inside scope of another class, it is called as nested class. = Outer class can be declared as package level private or public only but nested class canbe declared as private, package level private, protected or public. = If we want to design class for implemertation of another class then it should be nested. - Why Use Nested Classes? * itis a way of logically grouping classes that are only used in one place: Ta class is useful to only one other clas, ten i is logical to embed itn tat class and Keep the two together. * Tt increases encapsulation: Consider two top-level classes, A and B, wlieve B neds access to monbers of A that would others be declared privet By hiding cass B within class A. A's memes canbe declared private and B can access them. In addition, B itself can be hidden froma the outside world. | * Itcan lead to more readable and maintainable code: } Nesting small classes within top-level classes places the code closer to where it is used. = Types of Nested Classes: * Inner class: # Tf we declare nested class as a non-static then itis called as inner class. | # class A WAclass £ class B //Inmer class /ASB.class { JTODO i #A.Bb=new AQ.new BO; instantiation #As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated| with an instance, it cannot define any static members itself. # For the sake of simplicity consider non static nested class as non-static method of the class. # using object (of inner class) we can access members of inner class inside method of outer class. # Members of Outer class are directly accessible in methods of inner class, 80 SS ».| P| ‘SunBea Sutosing deiated| hh Learning Initiative lass # Shadowing: class Outer { private int uml = 10; lass Inner { | private int nurm\ = 20; public void print( ) { int num! = 30; System.out.printIn(Outer.this.num1); //10 ‘ystem.out.printin(this.num1); 120 System.out.println(num!); 1130 } # If implementation of nested class is dependent on outer class then nested class should be declared as non static( Inner class ). # There are two special kinds of inner classes: local classes and anonymous classes. * Static Nested class: # if we declare nested class as static then itis called as static nested dass. # class A JAclass { static class B_//static nested class _//ASB.class { /T0DO 2 } # _ ABb=newA.BQ;_//Instantiation # As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested _ SunBeam Institute of Information Technology, Pune & Karad Page 2 5& SUNBEAM. Institute of Information Technology ch RS sunBEAm Learning Initiative ERC eR oe ee eed class cannot refer directly to instance variables or methods defined only through an object reference. s enclosing class them can # for the sake of simplicity, consider static nested class as static_method of the class. # Using object (of static nested class) we can access members of static nested class inside method of outer class. # Static members of Outer class are directly accessible in methods of static nested class. To access non static members it is necessary 10 use abject. # If implementation of nested class do not dependent on outer class then nested class should be declared as static. - Example of nested class. class LinkedList { private static class Node { Wt0D0 } private Node head; public class LinkedListIterator { Node node = head; sTODO + Local Class: ~ In java, we can write class inside block/method. It is called as local class. ~ Local class can be categorized as: * Method local inner class * Method local anonymous inner class = Method local inner class: —— ‘SunBeam Institute of Information Technology, Pune & Karad Page 3‘thod of be r Learning initiative a ve. @ SUNBEAM as ~ Institute ‘of Information" Technology: > areean Java: Notes - Chapter 11 - Nested Class * Local class cannot be declared as static hence itis alsg.called as method local inner class. ae ; * Instance of local class are accessible within method only. + Method Local Anonymous Inner Class: * We can define class without name, itis called anonymous class. * In java, we can create anonymous class within block/method only so it cannot be static Hence anonymous class is also called as method local inner class. * Anonymous classes enable you to make your code more concise. * The anonymous class expression consists of the following: # The new operator # The name of an interface to implement or a class to extend. # Parentheses that contain the arguments ¢o a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, #A body, which is a class declaration body. * Example 1: eae Runnable r= new Runnable() { @Override public void run() { System.out printin("Inside run"); ) b run * Example 2: abstract class Shape { public abstract void calculateArea(); } public class Program —— SunBeam Institute of Information Technology, Pune & Karad age 4 LL@ SUNBEAM. Institute of Information Technology Learning Initiative suneealt er ee EYER Gs public static void main(Stringt] args) { Shape sh = new Shape() i @Override public void calculateArea() f { i System.ont.printIn("“calculateArea(y"); | } i i sh.calculateArea(); } ) * Example : hi Dbject obj = new Object() { @Override i public String toString() | | setum "string"; ff System.out printin(obj.toString()); ——— Page 5 ‘Technology, Pune & Karad s#SUNBEAM - Institute of Information Technology PEM ek cit) eek ast ue rclacs ‘An object which contains more than one element is called collection. In java data structure classes are called collection classes. Collection classes are also called as container classes. Library of reusable classes which are used to develop the application is called framework. Library of reusable collection classes which are used to develop java application is called java's collection framework. Java is abstraction technology so, developer should not worry about implementation of collection rather he/she should worry about its use. To use java collection framework, we should import java.util package. We are going to use following interfaces in collection framework. java.lang,Iterable java.util. erator java.lang,Comparable java.util. Comparator java.util. Enumeration Java.util.Collection java.util. List Java.util-ListIterator java.util Set java.util SortedSet java.util. NavigableSet javastil. Queue java.util. Deque Java.util. Map java.util. Map Entry java.util. SortedMap java.util NavigableMap + Collection: ~ Its root interface in java collection framework. - The JDK does not provide any direct implementations of this interface. ~ This interface is typically used to pass collections around and manipulate them where maximum generality is desired. - Methods Of Collection Interface * boolean addE e) * boolean addAll(Collection c) * boolean contains(Object 0) * boolean containsAll(Collection c) 55-@& SUNBEAM.» Institute of Information Technology STBEAM * boolean remove(Object 0) * boolean removeAil(Collection c) * boolean retainAl|(Collection c) * void clear() * boolean isEmpty() » int size() * Object!) toAmay() *
T[] toAmay(TT] a) * default boolean removelf(Predicate filter) * default Stream
stream) * default Stream
parallelStream() * default SpliteratorsE> spliterator() + List: - It is sub interface of Collection interface. ~ ArrayList, Vector, Stack, LiukedList etc implements List interface. These are reffered as List collection, - List collections store data in orderedi‘serqrential fashion (unsorted | - From List collection, user can access element rising integer index, = In list collection we can insert duplicate elements. - List collections allows us to insert multiple null elements. - We can travserse elements of list collection using Iterator and Listiterator. ~ If we want to store elements of reference type in List collection then reference type should contain equals method. ~ Due to inheritance all above methods are implicitly methods of List. Following are List specific ‘methods. * vold ada(int index, element) * boolean addAll(int index, Collection c) * E get(int index) * E set(int index, E element) * int indexOf(Object 0) * int lastindexOf(Object 0) * Listlterator
listIterator() * Listlterator
listIterator(int index) * boolean remove(Object 0) * List
subList(int fromindex, int tolndex) —— ‘SunBeara institute of Information Technology, Pune & Karad Page 2 50 TTould ific Page? & SunBeam- >= Institute of Information Technology samning Initiative nd Eewia: * default void sor(Comparator c) * default void replaceal(UnaryOperator
operator} Following are the synchronized collection classes in java: 1. Vector 2. Stack 3. HashTable + ArrayList: - Itis dynamically growable/shrinkable array. ~ Itis unsynchronized collection, ~ using Collections synchronizedList() method, we can make it synchronized. = Itstores data in ordered/sequential fashion [ unsorted J. - From ArrayList, user can access element using integer index. In ArrayList we can insert duplicate elements. - Hallows us to insert multiple null elements. - We can travserse elements of ArrayList using Iterator and Listlterator. - If we want to store elements of reference type in ArrayList then reference type should contain equals method. = Initial capacity of ArrayList is 10 elements. - If ArrayList is full then its capacity gets increased by half of its exsiting capacity. ~ Ctor declared in ArrayList: * public ArrayList() //Initial capacity - 10 * public ArrayList(int initialCapacity) * public ArrayList(Collection c) ~ Methods declared in ArrayList: * public void ensureCapacity(int minCapacity) * public void trimToSize() * public void forE.ach(Consumér action) + Vector: - It is dynamically growabte/shrinkable array. ~ itis in java since JDK 1.0. Itis legacy class. - Itis synchronized collection. res data in ordered/sequential fashion { unsorted SunBeam Institute of Information ‘Technology, Pune & Karad Page 3_&- SUNBEAM. ..."e & institute of Information Technology i d Ee eRe tet le ocies ~ From Vector, user can access element using integer index, - In Vector we can insert duplicate elements, It allows us to insert multiple null elements, = We can traverse elements of Vector using Iterator , Listlterator and Enumeration. - If we want to store elements of reference type in Vector then reference type should contain equals method. ~ Initial capacity of Vector is 10 elements. - If Vector is full then its capacity gets increased its exsiting capacity. ~ Ctor declared in Vector: * public Vector() * Vector(int initialCapacity) * public Vector(Collection c) ~ Methods declared in Vector: * public void ensureCapacity(int minCapacity) * public void addElement(ti obj), * public int capacity() Not exist in ArrayList * public void copylnto(Object{] anArray) * public £ elementAtcint index) * public Enumeration
elements() * public E firstElement() * public void forBach(Consumer action) * public voit! iusertElementAt(E obj,int index) * public E lastElement() * public bootean removeFlement(Object ob}) * public void removeElementAt(int index) * public void removeAllElements() * public void setBlementAtCE obj,int index) * public votd setSize(int newSize) * public void trimToSize() + Stack: = It is sub Class of Vector = Its synchronized collection ~The Stack class represents a last-in-first-out (LIFO) stack of objects. - A more complete and consistent set of LIFO stack operations is provided by the Deque interface: Deque
stac! ew ArrayDeque
(); ‘SunBeam Institute of Information Technology, Pune & Karadative ged i i IE i i @& SUNBEAM. ve Institute of Information Technology Oye Eco PEs oer ~ Methods declared in Stack: * public boolean empty() * public E peek) public E pop() * public E push(& item) * public int search(Object o) + LinkedList: - Itimplements List and Deque interface - Its implementation is based on Doubly Linked List. - Implementation of LinkedList is not synchronized. - We can make it synchronized using Collections.synchronizedList() method. = It stores data in ordered/sequential fashion [ unsorted ]. - From LinkedList, user can access element using integer index. - In LinkedList we can insert duplicate elements. = It allows us o insert multiple nuli elements. - If we want to store elements of reference type in L.inkedList then reference type should contain equals method. ~ Ctor declared in LinkedList: * public LinkedList() * public LinkedList(Collection c) ~ Methods declared in LinkedList: * public void addFirst(E e) * public void addLast(E e) * public Iterator
descendinglterator() * public E getFirst() * public E getLast() * public E element() * public E removeFirst() * public E removeLast() + Enumeration: = It is interface declared in java.util package ~ Using Enumeration we can traverse collection only in forward direction, - The functionality of this interface is duplicated by the Iterator interface. In addi Iterator adds an optional remove operation, and has shorter method names. - Methods of Enumeratior ‘SunBeam Institute of Information Technology, Pune & Karad ie eam Learning Initiative so_ SUNBEAM... institute of Information Technology Leaming Initiative fe ere + boolean hasMoreElements() + EnextElement() -eg Vector
vector = new Vector<>(); vector.ada(10); vector.add(20); vector.add(30); Enumeration
e = vector.elements(); t while( e.basMoreEtements()) ! ‘ i int element = e.nextElement(); i ‘System.out.printin(element); } + Iterator: -Itis a interface declared in java.util package - iterator takes the place of Enumeration in the Java Collections Framework. = Iterators differ from enumerations in two ways: * Iterators allow the caller to remove elements from the underlying collection during the iteration. * Method names have been improved. ~ Methods of Iterator: * boolean hasNext() *Enext() * default void remove() * default void forEachRemaining(Consumer action) -eg Yector
vector = new Vector<>(); vector.add(10); vectoradd(20); vector.add(30); Ierator
vector = new Vector<>(); vector.add(10); vector.add(20); vector.add(30); Listiterator
itr = vectorlistIterator(); while( itrhasNext()) System.out.prini(itznext+" "); 1110 20 30 ‘System.out printin(); while(itrhasPrevious()) System.out.print(itrprevious(}#" —") 1130 20.10 + ConcurrentModificationException: ~ This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. - For example, itis not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these Se ed ‘SunBeam Institute of Information Technology, Pune & Karad Page? or@ SunBeam = Institute of Information Technology a sunBeam Learning Initiative FEN choo ce ela Uke ae circumstances. Some Iterator implementations may choose to throw this exception if this behavior is detected = Iterators that do this are known as fajl-fast iterators. -eg List
list = new ArrayList
(; listadd("1"); listadd("2"); listadd("3"); listadd("4"); listadd( 5"); erator
itr = list.iterator(); while( inchasNext()) { String value = itznext(); System.out.printin("Value : “+value); if value.equals("3") listremove("3");_ /ConcurrentModificationException } + Set: - It is sub interface of Collection, - HashSet, LinkedHashSet, TreeSet etc. implements Set interface, These are Set Collections. ~ Set models the mathematical set abstraction. = The Set interface contains only methods inherited from Collection and adds the restriction tha duplicate elewieuts are prohibited. ~ Methods of Set interface: * boolean add(& e) * boolean addAll(Collection c) * boolean contains(Object 0) * boolean containsAll(Collection ©) * boolean remove(Object 0) * boolean removeA\l(Collection c) * boolean retainAll(Collection c) * void clear() * boolean istimpty() * int sizeQ) * Object{] toArrayO) ‘SunBeam Institute of Information Technology, Pune & Karad Page 8 @ ST8 » SUNBEAM-: Me Institute of Information Technology hi FR Learning Initiative EES peer *
TT] toAmay(TI] a) * default boolean removelf(Predicate filter) * default Stream
stream() * default Stream
parallelStream() * default Spliterator
spliterator() +SortedSet: - It is sub interface of Set. It maintains its elements in ascending order, sorted according to the elements’ natural ordering ( Comparable ) or according to a Comparator provided at SortedSet creation time. ~ Methods declared in SortedSet: *E first *E last) * SontedSet
headSet(E toElement) * SontedSet
tailSet(E fromElement) * SortedSet
subSet(E fromE}ement,E toElement) +Navigableset: = It isa sub interface of SortedSet. ~ It is sortedSet having navigation methods. ~ TreeSet class implements NavigableSet interface ~ Methods declared in NavigableSet: * E ceiling(E e) * E floor(E e) +E higher(E e) *E lower(E e) +E pollFirst() *E pollLast() * Iterator
descendinglterator() * NavigableSet
descendingSet() + TreeSet: - It isa class which implements NavigableSet interface ~Itis based on TreeMap collection. It do not contain duplicate elements — We can not store null elements in TreeSet. ‘SunBeam Institute of Information Technology, Pune & Karad Page 9| & sunBeam ey = Institute of Information Technology he. 3 suneeam Learning Initiati java Notes.- Chapter 12 - Collection Framework f - It is unsynchronized collection. - Using Collections.synchronizedSortedSet() method we can make it synchronized. = It stores data in sorted format on the basis of either Comparable or Comparator. - If we want to store elements of reference type in TreeSet then Reference type must implement Comparable or Comparator interface + Searching Algorithm: 1. Linear search / Sequential Search = We can use it search element in any sorted as well as unsorted collection. - If collection contains large number of elements then it is time consuming 2, Binary Search ~ We can use it only on sorted array ~Ttis faster than Linear search 3. Hashing ~ If we want to seatch element in constant time then we should use hashing It is based on hashcode. An integer number that can be generated by processing state of the object is called hashcode. Hash function is responsible for generating hashcode. If ebjects are hashed to the same slot then it is called as collision. = To avoid colliston we can use collision removal techniques( Open addressing, separate chaining etc.) ~ In seperate chaining, arcay of linked list is maintained. Each linked list is called as bucket. - Load Factor = ( no of buckets )/ bo of elements, + HashSet: = Itisa class wich implements Set interface. = Itis based on HashTable. - Itdo not contain duplicate elements - It can contain null element ~Itis unsynchronized collection. - using Collections.synchronizedSet we can make it sychronized. ~ HashSet is much faster than TreeSet but do not give guarantee of ordering. - An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. ~ The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. - One thing worth keeping in mind about HashSet is that iteration is linear in the sum of the number of entries and the number of buckets (the capacity). Thus, choosing an initial capacity that's too high ‘can waste both space and time. On the other han, choosing an initial capacity that's too low wastes time by copying the data structure each time it’s forced to increase its capacity. If you don't specify an ‘SunBeam Institute of Information Technology, Pune & Karad Page 10et. vad mber o high astes 6 SUNBEAM.._| a Institute of Information Technology st, there was some advantage to choosing a prime number as the initial capacity. This is no longer true. Internally, the capacity is always rounded up to a power of two, - If we want to add object of reference type in HashSet then refrence type should override equals and hashCode method. - Ctor declared in HashSet: * public HashSetQ) * public HashSet(Collection ¢) * public HashSet(int initialCapacity, float loadFactor) | public HashSet(int initialCapacity) } 4 ~ Methods declared in HashSet: * public boolean add(E e) * public void clear() * public Object clone() * public boolean contains(Object 0) * public boolean isEmpty() * public Iterator
iterator() * public boolean remove(Object 0) public int sizeQ) * public Spliterator
spliterator() +LinkedHashSet: - Itis a subclass of HashSet = Its implimentation is based on HashTable and LinkedList. - It gives gurantee of order of elements. - Itruns nearly as fast as HashSet. - It do not contain duplicate elements - Itcan contain null element ~Itis unsynchronized collection. - using Collections synchronizedSet we can make it sychronized. +* Queue: = Itis sub interface of Collection, - PriorityQueue implements Queue interface ~~ Queue Collection maintains elements in FIFO. ~ Queue implementations generally do not allow insertion of null elementsom => Institute of Information Technology oe Eee eke cat ube fethods declared in Queue: * boolean add(E e) *E element) * boolean offer(E e) *E peek() +E poll) * Eremove() Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll) Examine element) peek) + Deque: ~The name deque is short for "double eutled queue" and is usnally pronounced "deck", - It is sub interface of Queue - This interface defines methods to access the elements at both ends of the deque. First Element (Head) Last Element (Tail) Throws exception Special value Throws exception Special value Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e) Remove removeFirsi() pOlFirst) —removeLast() pollLast() Examine getFirst) peekFirst() getLast() peekLast() - LinkedList class implements Deque interface. +Map: = It is interface declared in java.util package. . = Itisa part of collection framework but it do not extend Collection interface - This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface. ———— SunBeam Institute of Information Technology, Pune & Karad Page 12 66_ ye -@ SunBeam Institute of Information Technology Teaming initiative Java: Notes - Chapter: 12 Collection Framework roperties, HashTable, HashMap, LinkedHlashMap, TreeMap et is also called as Map collection. = Map collection stores elements in key/Value pair format. ~A map cannot contain duplicate keys but it can contain duplicate values. ~ Each key can map to at most one value. ~ Abstract methods declared in Map: * void clear() * boolean containsKey(Object key) * boolean contains Value(Object value) * Set
> entrySet() * V get(Object key) * boolean isEmpty() * Set
keySet() * V put(K key,V value) * void putAll(Map m) * Vcemove(Object key) * int size() * Collection
values() plements Map interface. It +Map.Entry: = It is nested interface declared in Map. - Methods of Entry interface: *K getKey *V getValue() * VsetValue(V value) +HashTable: = Itis class which implements Map interface. ~ Since it has implemented Map interface, it stores elements in key/value pair format. ~ In HashTable Key and value can not be null, - Key must be unique, value can be duplicate = It is synchronized collection. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method, - Ctor declared in Hash Table: public Hashtable) * public Hashtable(int initialCapacity) SunBeam Institute of Information Technology, Pune & Karad Page 13 a espe We eSUNBEAM. . Institute of Information Technology ie) ™ public Hashtable int initialCapacity, float loadBactor) * public Hashtable(Map t) + HashMap: ~ It is Hash table based implementation of the Map interface. = The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls, ~ In HashMap key and value can be nul - Key must be unique, value can be duplicate ~ Implementation of HashMap is unsynchronized. - Using Collections.synctironizedMap method we can make it synchronized, ~To successfully store and retrieve objects from a HasMap, the objects used as keys must implement the hashCode method and the equals method, ~ Ctur declared ini HashMap; * public HashMap() * public HashMap(int initialCapacity) public HashMap(nt initialCapacity, float load Factor) * public HashMap(Map t) + LinkedHaslMap: ~ Hash table and linked list implementation of the Map interface, with predictable iteration order. ~ This implementation differs from HashMap in that it maintains a doubly-linked list running through all ofits entries. ~ In LinkedHashMap key and value can be null - Key must be unique, value can be duplicate - Implementation of LinkedHashMap is unsynchronized - Using Collections.synrhronizedMap method we can make it synchronized. + SortedMap: = It is sub interface of Map. ~ A SortedDap is a Map that maintains its entries in ascending order, sorted according to the keys’ natural ordering, or according to a Comparator provided at the time of the SortedMap creation. ~ Methods declarvd in Sorted map. * Comparator comparator() * K firstKey() * SortedMap
headMap(K toKey) a a EE SunBeam Institute of Information Technology, Pune & Karad Page 14 6= ™E .& SUNBEAM...’ == Institute of Information Technology om ioe teeming intlative * K lastKey() * SortedMap
subMap(K fromKey, K toKey) * SortedMap
tailMap(K fromKey) + NavigableMap: ~ Itis sub interface of SortedMap. = Itis sortedMap having navigation methods. A NavigableMap may be accessed and traversed in either ascending or descending key order, - Methodes of NavigableMap: * Map-Entry
ceilingEntry(K key) * K ceilingKey(K key) * NavigableSet
descendingKeySet() * NavigableMap
descendingMap() * Map Entry
firstEntry() * Map Entry4K,V> NoorEntry(K key) * K floorkey(K key) * Map Bnty
highesEntry(K key) * Map Entry
lastEntry() * Map Entty
lowerEntry(K key) *K lowerKey(K key) * NavigableSet
navigableKeySet() * Map Entry
pollFirstEntry() * Map Entry
pollLastEntry() + TreeMap: ~ A Red-Black tree based NavigableMap implementation. - The map is sorted according to the natural ordering of its keys( Comparable ), or by a Comparator provided at map creation time. - In TreeMap, Key cannot be null but value can be null. - Itis unsynchronized collection, ~ To make it synchronized we should use Collections synchronizedSonedMap() method, ~ If we want to use object of reference type as a key then réference type should implement either Comparable or Comparator interface, Page 15,6& SUNBEAM. = Institute of Information Technology suneam Placement Intative Java Notes-- Chapter 13.- File /O + Persistence: = Its minor pillar of oops. = It is the process of maintain state ofthe object either file or databases. + File: ~ Acontainer which holds collection of records om HDD is called file. - General classification of files: * Binary files (dat) can open with specific application. - requires less processing hence itis faster. ~ e.g. Jpg, mp3, .class etc * Text files( ost) ~ can open with any text editor. - requires more processing hence itis slower. + Stream: - It is an object which is used to perfarm operations on file(read/write’append) —~ + Standard Streams in java: ~ System.in ~> associated with keyboard - System.out --> associated with monitor - System.err —> associated with monitor + File related terminology: - Path : It consist of root directory, sub directories, path seperator and file names. e.g c:\Sandeep\ava\SimpleHello\sre\Program java - Absolute path : It is a path of file from root directory. e.g c\Sandeep\Java\SimpleHello\src\Program,java - Relative path : It is path of file from curret directory. eg Asr\Program,java - Path Seperators: Windows = \ Linux - of ' Mac OS, - = dot) + File 10: - To manipulate files, we should use interfaces and classes declared in java.io package. ~ Types declared in io package are device independent. 0SUNBEAM... “Institute of Informati tion Technology * c& i Learning Initiative ° i eek) ~ Interfaces declared in java.io package: « * FilenameFilter * Flushable * Closeable * Datalnput * DataOurput * Objectinput * ObjectOutput * Serializable - Classes declared in java.io package: * Console *File * InputStream * OutputStream * FileinpuStream * FileOutputStream * BufferedinputStream * BufferedOutputStreant * DatalnputStream * DataOutputStream * ObjectinputStream * ObjectOurputStream_ * PrintStream Above classes are required to manipulate binary files * Reader * Writer * FileReader * FileWriter * BufferedReader * BufferedWriter * InputStreamReader —— ‘SunBeam Institute of Information Technology, Pune & Karad Page 2 — —}- n6 SUNBEAM . Institute of Information Technology Native cme » PrintWriter above classes are required to manipulate text files + java.io.File: - It represents files and directories of of OS. - Instances of the File class are immutable; that is, once created, the pathname represented by a File object witl never change. File ctor: * File(String pathname) ~ Some of the important methods of File class. * public boolean createNewFile() throws IOException * public boolean delete() * public boolean exists() * public String getName() * public long getFreeSpace() % public long getUsableSpace() * public long getTutaiSpace() * public boolean isDirectory() * public boolean isFileQ) = public long lastModified”) * public long length) * public File{] listFiles() * public File(]listFiles(FileFilter filter) public boolean mkdir() File file = new File("/media/sandeep/DOCUMENTS/E-BookiC++"); if( file.exists()) { Filef] files = file.listPiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { iffname.endsWith(" pdf") retum true; ‘SunBeam Institute of Information Technology, Pune & Karad Page 3 2retum false; YD for (File € : files) System.out.println(E.getNameQ); - The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, fileatributes, and file systems, This API may be used to overcome many of the limitations of the ava.io.File class. +1/0 Streams: ~ An /O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. - Stceams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. - No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses ant input stream to read data from a source. - java.lang.Object | javaio.Inputstream |- java.io. OutputStream [-Javaio Reader |-Javaio.Weiter - Byte Streams : * Programs use byte streams to perform input and output of 8-bit bytes. * All byte stream classes are descended from InputStream and QutputStream, ‘Program to write single character at a time in file public static void writeRecord( String pathname ) throws Exception { try( FileOutputStream outputStream = new FileOutputStream(pathname)) { char ch SunBeam Institute of Information Technology, Pune & Karad Page 4 nS SUNBEAM. ay | Institute of Information Technology rem a Java-Notes - Chapter 43 = File /0 iam while( ch <="Z') { i outputStream.write(ch); +h; } | | J | of | //Program to read single character at a time in file public static void readRecord( String pathname ) throws Exception | | try( FileInputStream inputStream = new FilelnputStream(pathname)) | ( int data; | ‘while( ( data = inputStream.tead{ ) ) != -1) | { char ch = (charjdata; | ‘System.out.print(ch+" y d } * Examples we've seen is unbuffered {/O. This means each read or write request is_handled directly by the underlying OS. This can make a program much less efficient, since each such request often | triggers disk access, network activity, or some other operation that is relatively expensive. * To reduce this kind of overhead, the Java platform implements buffered VO streams. Buffered input \ streams read data from a memory aree known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output APT is, | called only when the buffer is ful. ' * There are four buffered stream classes used to wrap unbuffered streams: BofferedtnpueStceam and BufferedOutputStream create buffered byte streams, while BufferedReader and ButferedWriter create buffered character streams. * A program can convert an unbuffered stream into a buffered stream : InputStream = new BufferedInputStream(new FileInpuiStream(pathiname)}; outputStream = new BufferedOutputStream(new FileOutputStream(pathname)); ———— SunBeam Institute of Information ‘Technology, Pune & Karad Page 5 ”@ SUNBEAM... =, institute of Information Technology rerrett ive FEED i enone ce een - Data Streams: * Data streants support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the Datalnput interface or the DataOutput interface. outputStream = new DataOutputStream(new BufferedOutputStream(...)); * A data output stream lets an application write primitive Java data types fo an output stream = inputStream = new DatalnputStream(new ButferedInputStream(...); * A data input stream lets an application read primitive Java data types from an underlying input stream. * Notice that DataStreams detects an end-of-file condition by catching EOFException, * Algo notice that each specialized write in DataStreams is exactly matched by the corresponding specialized read. ~ Object Streams: * Object streams support 1/0 of objects. * The object stream classes are ObjectlnputStream and ObjectOurputStream. * These classes implement Objectinput and ObjectOutput, which are subinterfaces of Datalnput and DataOutput, * readObject() is method of ObjectInputStream and writeObject is method of ObjectOuypitSteeam, * Process of converting state of the object into bytes is called serialization and converting bytes into Object is called deserialization. ** To serialize state, class must implement Serializable marker interface. * Without implementing Serializable interface, if we try to serialize state of the object then JVM throws NotSerializableException, * If we do not serialize state of any specific field then we should declare such field as transient. * State of static and transient field can not be serialized. * serial VersionUID is used to ensure that same class (that was used during serialization ) is loaded during deserialization, serialVersionUID is used for version control of object. * e.g, private static final long serial VersionUID = -5410036443708494562L; * __{iSerialization ————— SunBeam Institute of Information Technology, Pune & Karad age 6
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 (6129)
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
Brené 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 (934)
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)
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)
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)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
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 (1987)
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)
ME8694 Hydraulics and Pneumatics MCQ
PDF
100% (2)
ME8694 Hydraulics and Pneumatics MCQ
19 pages
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)
Zolo Hostels For Girls and Boys
PDF
No ratings yet
Zolo Hostels For Girls and Boys
3 pages
Tender 1905
PDF
No ratings yet
Tender 1905
7 pages
SSC CGL Tier 2 Quantitative Abilities 18-Nov-2020
PDF
No ratings yet
SSC CGL Tier 2 Quantitative Abilities 18-Nov-2020
16 pages
SBI Clerk Mains 2020 (Quants, Reasoning & English)
PDF
No ratings yet
SBI Clerk Mains 2020 (Quants, Reasoning & English)
18 pages
Check Eligibility
PDF
No ratings yet
Check Eligibility
5 pages
SSC CGL Tier 2 Quantitative Abilities 16-Nov-2020
PDF
No ratings yet
SSC CGL Tier 2 Quantitative Abilities 16-Nov-2020
17 pages
ESIC UDC Mains 19-Mar-2016
PDF
No ratings yet
ESIC UDC Mains 19-Mar-2016
15 pages
Final Nagarro For Affilited Clge
PDF
No ratings yet
Final Nagarro For Affilited Clge
2 pages
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)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
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
Principles: Life and Work
From Everand
Principles: Life and Work
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
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
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
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
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
Steve Jobs
From Everand
Steve Jobs
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Yes Please
From Everand
Yes Please
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
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
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
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
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
ME8694 Hydraulics and Pneumatics MCQ
PDF
ME8694 Hydraulics and Pneumatics MCQ
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
Zolo Hostels For Girls and Boys
PDF
Zolo Hostels For Girls and Boys
Tender 1905
PDF
Tender 1905
SSC CGL Tier 2 Quantitative Abilities 18-Nov-2020
PDF
SSC CGL Tier 2 Quantitative Abilities 18-Nov-2020
SBI Clerk Mains 2020 (Quants, Reasoning & English)
PDF
SBI Clerk Mains 2020 (Quants, Reasoning & English)
Check Eligibility
PDF
Check Eligibility
SSC CGL Tier 2 Quantitative Abilities 16-Nov-2020
PDF
SSC CGL Tier 2 Quantitative Abilities 16-Nov-2020
ESIC UDC Mains 19-Mar-2016
PDF
ESIC UDC Mains 19-Mar-2016
Final Nagarro For Affilited Clge
PDF
Final Nagarro For Affilited Clge
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel