SlideShare ist ein Scribd-Unternehmen logo
1 von 63
More Topics on Java
Ahmed Misbah
Agenda
• Class Loader
• Object Class
• Collections
• Exception Handling
• Files and I/O
• Serialization
Rules
• Phones silent
• No laptops
• Questions/Discussions at anytime welcome
• 10 minute break every 1 hour
CLASS LOADER
Backstory
Class Loader
• The Java Classloader is a part of the Java
Runtime Environment that dynamically loads
Java classes into the Java Virtual Machine on
demand (i.e. Lazy Loading)
• When the JVM is started, three class loaders
are used:
– Bootstrap class loader (native implementation)
– Extensions class loader (loads code in extensions
dir)
– System class loader (loads code found on
java.class.path)
Custom Class Loaders
• The Java class loader is written in Java. It is
therefore possible to create your own class
loader without understanding the finer details
of the Java Virtual Machine
• This makes it possible (for example):
1. To load or unload classes at runtime
2. To change the way the byte code is loaded
3. To modify the loaded byte code
Building a SimpleClassLoader
• A class loader starts by being a subclass of
java.lang.ClassLoader
• The only abstract method that must be
implemented is loadClass()
Building a SimpleClassLoader
• The flow of loadClass() is as follows:
– Verify class name
– Check to see if the class requested has already
been loaded
– Check to see if the class is a "system" class
– Attempt to fetch the class from this class loader's
repository
– Define the class for the VM
– Resolve the class
– Return the class to the caller
OBJECT CLASS
Object Class
• The Object class is the parent class of all the
classes in java by default. In other words, it is
the topmost class of java
Object Class
public final Class getClass()
returns the Class class object of this
object. The Class class can further be used
to get the metadata of this class.
public int hashCode()
returns the hashcode number for this
object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws
CloneNotSupportedException
creates and returns the exact copy (clone)
of this object.
public String toString()
returns the string representation of this
object.
protected void finalize()throws
Throwable
is invoked by the garbage collector before
object is being garbage collected.
Object Class
public final void notify()
wakes up single thread, waiting on this
object's monitor.
public final void notifyAll()
wakes up all the threads, waiting on this
object's monitor.
public final void wait(long
timeout)throws InterruptedException
causes the current thread to wait for the
specified milliseconds, until another
thread notifies (invokes notify() or
notifyAll() method).
public final void wait(long timeout,int
nanos)throws InterruptedException
causes the current thread to wait for the
specified miliseconds and nanoseconds,
until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws
InterruptedException
causes the current thread to wait, until
another thread notifies (invokes notify()
or notifyAll() method).
Project Lombok!
COLLECTIONS
Collections
• Collections in java is a framework that provides
an architecture to store and manipulate the
group of objects
• All the operations that you perform on a data
such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by
Java Collections
• Java Collection simply means a single unit of
objects. Java Collection framework provides
many interfaces (Set, List, Queue, etc.) and
classes (ArrayList, Vector, LinkedList,, HashSet,
LinkedHashSet, TreeSet, etc.)
Hierarchy of Collection Framework
Collection Interface
public boolean add(Object element) is used to insert an element in this collection.
public boolean addAll(Collection c)
is used to insert the specified collection
elements in the invoking collection.
public boolean remove(Object element)
is used to delete an element from this
collection.
public boolean removeAll(Collection c)
is used to delete all the elements of specified
collection from the invoking collection.
public boolean retainAll(Collection c)
is used to delete all the elements of invoking
collection except the specified collection.
public int size()
return the total number of elements in the
collection.
public void clear()
removes the total no of element from the
collection.
public boolean contains(Object element) is used to search an element.
public boolean containsAll(Collection c)
is used to search the specified collection in
this collection.
public Iterator iterator() returns an iterator.
public Object[] toArray() converts collection into array.
public boolean isEmpty() checks if collection is empty.
public boolean equals(Object element) matches two collection.
public int hashCode() returns the hashcode number for collection.
Java.util.Collections Class
• The java.util.Collections class consists
exclusively of static methods that operate on
or return collections
Sample Methods in Collections class
• static <T> int binarySearch(List<? extends
Comparable<? super T>> list, T key)
This method searches the specified list for the
specified object using the binary search
algorithm
• static <T> int binarySearch(List<? extends T>
list, T key, Comparator<? super T< c)
This method searches the specified list for the
specified object using the binary search
algorithm.
Sample Methods in Collections class
• static <T> T min(Collection<? extends T> coll,
Comparator<? super T> comp)
This method returns the minimum element of
the given collection, according to the order
induced by the specified comparator.
• static <T> T max(Collection<? extends T> coll,
Comparator<? super T> comp)
This method returns the maximum element of
the given collection, according to the order
induced by the specified comparator.
Sample Methods in Collections class
• static void reverse(List<?> list)
This method reverses the order of the elements
in the specified list.
• static <T> void sort(List<T> list, Comparator<?
super T> c)
This method sorts the specified list according to
the order induced by the specified comparator.
Comparable Interface
• Comparable interface is used to order the
objects of user-defined class
• public int compareTo(Object obj): is used to
compare the current object with the specified
object.
Comparator Interface
• Comparator interface is used to order the
objects of user-defined class
• public int compare(Object obj1,Object obj2):
compares the first object with second object
EXCEPTION HANDLING
Why?
• Beginners usually start off by returning error
codes
• The inner working of your program should not
have a protocol
From the Clean Code book
if (deletePage(page) == E_OK) {
if (registry.deleteReference(page.name) == E_OK) {
if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
logger.log("page deleted");
} else {
logger.log("configKey not deleted");
}
} else {
logger.log("deleteReference from registry failed");
}
} else {
logger.log("delete failed");
return E_ERROR;
}
Bad
try {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
catch (Exception e) {
logger.log(e.getMessage());
}
Good
Motive:
Error Codes  awful nested IFs
But using Exceptions  now, we can read the normal flow
Three Categories of Exceptions(1/3)
1. Checked exceptions: is an exception that
occurs at the compile time, these are also
called as compile time exceptions. These
exceptions cannot simply be ignored at the
time of compilation, the Programmer should
take care of (handle) these exceptions
Three Categories of Exceptions(2/3)
2. Unchecked exceptions: is an exception that
occurs at the time of execution, these are
also called as Runtime Exceptions, these
include programming bugs, such as logic
errors or improper use of an API. Runtime
exceptions are ignored at the time of
compilation
(e.g.ArrayIndexOutOfBoundsException and
NullPointerException).
Three Categories of Exceptions(3/3)
3. Errors: These are not exceptions at all, but
problems that arise beyond the control of the
user or the programmer. Errors are typically
ignored in your code because you can rarely
do anything about an error. For example, if a
stack overflow occurs, an error will arise.
They are also ignored at the time of
compilation
Exception Hierarchy
Catching an Exception(1/2)
Catching an Exception(2/2)
• Since Java 7 you can handle more than one
exceptions using a single catch block, this
feature simplifies the code
Finally block
• The finally block follows a try block or a catch
block. A finally block of code always executes,
irrespective of occurrence of an Exception
• Using a finally block allows you to run any
cleanup-type statements that you want to
execute, no matter what happens in the
protected code
FILES AND I/O
Java I/O
• Java I/O (Input and Output) is used to process
the input and produce the output based on
the input
• Java uses the concept of stream to make I/O
operation fast. The java.io package contains
all the classes required for input and output
operations
Stream
• A stream is a sequence of data. In Java a
stream is composed of bytes.
• In java, 3 streams are created for us
automatically. All these streams are attached
with console:
1. System.out: standard output stream
2. System.in: standard input stream
3. System.err: standard error stream
OutputStream and InputStream
OutputStream class
• OutputStream class is an abstract class. It is
the superclass of all classes representing an
output stream of bytes. An output stream
accepts output bytes and sends them to some
sink
public void write(int)throws IOException:
is used to write a byte to the current
output stream.
public void write(byte[])throws
IOException:
is used to write an array of byte to the
current output stream.
public void flush()throws IOException: flushes the current output stream.
public void close()throws IOException:
is used to close the current output
stream.
InputStream class
• InputStream class is an abstract class. It is the
superclass of all classes representing an input
stream of bytes.
public abstract int read()throws
IOException:
reads the next byte of data from the input
stream.It returns -1 at the end of file.
public int available()throws IOException:
returns an estimate of the number of
bytes that can be read from the current
input stream.
public void close()throws IOException: is used to close the current input stream.
When to use what?
• For simple and primitive reads and writes, use
FileInputStream and FileOutputStream
• For writing byte array into multiple files, use
ByteArrayOutputStream and ByteArrayInputStream
• For reading data from multiple streams, use
SequenceInputStream
• Java FileWriter and FileReader classes are used to
write and read data from text files.
• Java Buffered Stream classes uses an internal buffer to
store data. It adds more efficiency than to write data
directly into a stream. So, it makes the performance
fast.
SERIALIZATION
Serialization in Java
• Serialization in java is a mechanism of writing
the state of an object into a byte stream
• The reverse operation of serialization is called
deserialization.
java.io.Serializable Interface
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Example of Java Serialization
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Example of Java Deserialization
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInput
Stream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}
}
Transient Keyword
• If you don't want to serialize any data member
of a class, you can mark it as transient
Can I Serialize to XML or JSON?
• Yes!
• http://flexjson.sourceforge.net/
• https://docs.oracle.com/javase/7/docs/api/jav
a/beans/XMLEncoder.html
Thank You!
Questions?

Weitere ähnliche Inhalte

Was ist angesagt? (19)

Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Iterator
IteratorIterator
Iterator
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 

Ähnlich wie More topics on Java

JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.pptKhizar40
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance ConceptsEmprovise
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 

Ähnlich wie More topics on Java (20)

JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
core java
core javacore java
core java
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 

Mehr von Ahmed Misbah

6+1 Technical Tips for Tech Startups (2023 Edition)
6+1 Technical Tips for Tech Startups (2023 Edition)6+1 Technical Tips for Tech Startups (2023 Edition)
6+1 Technical Tips for Tech Startups (2023 Edition)Ahmed Misbah
 
Migrating to Microservices Patterns and Technologies (edition 2023)
 Migrating to Microservices Patterns and Technologies (edition 2023) Migrating to Microservices Patterns and Technologies (edition 2023)
Migrating to Microservices Patterns and Technologies (edition 2023)Ahmed Misbah
 
Practical Microservice Architecture (edition 2022).pdf
Practical Microservice Architecture (edition 2022).pdfPractical Microservice Architecture (edition 2022).pdf
Practical Microservice Architecture (edition 2022).pdfAhmed Misbah
 
Istio as an enabler for migrating to microservices (edition 2022)
Istio as an enabler for migrating to microservices (edition 2022)Istio as an enabler for migrating to microservices (edition 2022)
Istio as an enabler for migrating to microservices (edition 2022)Ahmed Misbah
 
DevOps for absolute beginners (2022 edition)
DevOps for absolute beginners (2022 edition)DevOps for absolute beginners (2022 edition)
DevOps for absolute beginners (2022 edition)Ahmed Misbah
 
TDD Anti-patterns (2022 edition)
TDD Anti-patterns (2022 edition)TDD Anti-patterns (2022 edition)
TDD Anti-patterns (2022 edition)Ahmed Misbah
 
Implementing FaaS on Kubernetes using Kubeless
Implementing FaaS on Kubernetes using KubelessImplementing FaaS on Kubernetes using Kubeless
Implementing FaaS on Kubernetes using KubelessAhmed Misbah
 
Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3
Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3
Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3Ahmed Misbah
 
Introduction to TDD
Introduction to TDDIntroduction to TDD
Introduction to TDDAhmed Misbah
 
Getting Started with DevOps
Getting Started with DevOpsGetting Started with DevOps
Getting Started with DevOpsAhmed Misbah
 
DevOps for absolute beginners
DevOps for absolute beginnersDevOps for absolute beginners
DevOps for absolute beginnersAhmed Misbah
 
Microservice test strategies for applications based on Spring, K8s and Istio
Microservice test strategies for applications based on Spring, K8s and IstioMicroservice test strategies for applications based on Spring, K8s and Istio
Microservice test strategies for applications based on Spring, K8s and IstioAhmed Misbah
 
Cucumber jvm best practices v3
Cucumber jvm best practices v3Cucumber jvm best practices v3
Cucumber jvm best practices v3Ahmed Misbah
 
Welcome to the Professional World
Welcome to the Professional WorldWelcome to the Professional World
Welcome to the Professional WorldAhmed Misbah
 
Career Paths for Software Professionals
Career Paths for Software ProfessionalsCareer Paths for Software Professionals
Career Paths for Software ProfessionalsAhmed Misbah
 
Effective User Story Writing
Effective User Story WritingEffective User Story Writing
Effective User Story WritingAhmed Misbah
 
DDT Testing Library for Android
DDT Testing Library for AndroidDDT Testing Library for Android
DDT Testing Library for AndroidAhmed Misbah
 
Software Architecture
Software ArchitectureSoftware Architecture
Software ArchitectureAhmed Misbah
 

Mehr von Ahmed Misbah (20)

6+1 Technical Tips for Tech Startups (2023 Edition)
6+1 Technical Tips for Tech Startups (2023 Edition)6+1 Technical Tips for Tech Startups (2023 Edition)
6+1 Technical Tips for Tech Startups (2023 Edition)
 
Migrating to Microservices Patterns and Technologies (edition 2023)
 Migrating to Microservices Patterns and Technologies (edition 2023) Migrating to Microservices Patterns and Technologies (edition 2023)
Migrating to Microservices Patterns and Technologies (edition 2023)
 
Practical Microservice Architecture (edition 2022).pdf
Practical Microservice Architecture (edition 2022).pdfPractical Microservice Architecture (edition 2022).pdf
Practical Microservice Architecture (edition 2022).pdf
 
Istio as an enabler for migrating to microservices (edition 2022)
Istio as an enabler for migrating to microservices (edition 2022)Istio as an enabler for migrating to microservices (edition 2022)
Istio as an enabler for migrating to microservices (edition 2022)
 
DevOps for absolute beginners (2022 edition)
DevOps for absolute beginners (2022 edition)DevOps for absolute beginners (2022 edition)
DevOps for absolute beginners (2022 edition)
 
TDD Anti-patterns (2022 edition)
TDD Anti-patterns (2022 edition)TDD Anti-patterns (2022 edition)
TDD Anti-patterns (2022 edition)
 
Implementing FaaS on Kubernetes using Kubeless
Implementing FaaS on Kubernetes using KubelessImplementing FaaS on Kubernetes using Kubeless
Implementing FaaS on Kubernetes using Kubeless
 
Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3
Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3
Istio as an Enabler for Migrating Monolithic Applications to Microservices v1.3
 
Introduction to TDD
Introduction to TDDIntroduction to TDD
Introduction to TDD
 
Getting Started with DevOps
Getting Started with DevOpsGetting Started with DevOps
Getting Started with DevOps
 
DevOps for absolute beginners
DevOps for absolute beginnersDevOps for absolute beginners
DevOps for absolute beginners
 
Microservice test strategies for applications based on Spring, K8s and Istio
Microservice test strategies for applications based on Spring, K8s and IstioMicroservice test strategies for applications based on Spring, K8s and Istio
Microservice test strategies for applications based on Spring, K8s and Istio
 
Cucumber jvm best practices v3
Cucumber jvm best practices v3Cucumber jvm best practices v3
Cucumber jvm best practices v3
 
Welcome to the Professional World
Welcome to the Professional WorldWelcome to the Professional World
Welcome to the Professional World
 
Career Paths for Software Professionals
Career Paths for Software ProfessionalsCareer Paths for Software Professionals
Career Paths for Software Professionals
 
Effective User Story Writing
Effective User Story WritingEffective User Story Writing
Effective User Story Writing
 
AndGen+
AndGen+AndGen+
AndGen+
 
DDT Testing Library for Android
DDT Testing Library for AndroidDDT Testing Library for Android
DDT Testing Library for Android
 
Big Data for QAs
Big Data for QAsBig Data for QAs
Big Data for QAs
 
Software Architecture
Software ArchitectureSoftware Architecture
Software Architecture
 

Kürzlich hochgeladen

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Kürzlich hochgeladen (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

More topics on Java

  • 1. More Topics on Java Ahmed Misbah
  • 2. Agenda • Class Loader • Object Class • Collections • Exception Handling • Files and I/O • Serialization
  • 3. Rules • Phones silent • No laptops • Questions/Discussions at anytime welcome • 10 minute break every 1 hour
  • 6.
  • 7.
  • 8. Class Loader • The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine on demand (i.e. Lazy Loading) • When the JVM is started, three class loaders are used: – Bootstrap class loader (native implementation) – Extensions class loader (loads code in extensions dir) – System class loader (loads code found on java.class.path)
  • 9.
  • 10. Custom Class Loaders • The Java class loader is written in Java. It is therefore possible to create your own class loader without understanding the finer details of the Java Virtual Machine • This makes it possible (for example): 1. To load or unload classes at runtime 2. To change the way the byte code is loaded 3. To modify the loaded byte code
  • 11.
  • 12. Building a SimpleClassLoader • A class loader starts by being a subclass of java.lang.ClassLoader • The only abstract method that must be implemented is loadClass()
  • 13. Building a SimpleClassLoader • The flow of loadClass() is as follows: – Verify class name – Check to see if the class requested has already been loaded – Check to see if the class is a "system" class – Attempt to fetch the class from this class loader's repository – Define the class for the VM – Resolve the class – Return the class to the caller
  • 14.
  • 15.
  • 16.
  • 17.
  • 19. Object Class • The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java
  • 20. Object Class public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of this class. public int hashCode() returns the hashcode number for this object. public boolean equals(Object obj) compares the given object to this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public String toString() returns the string representation of this object. protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
  • 21. Object Class public final void notify() wakes up single thread, waiting on this object's monitor. public final void notifyAll() wakes up all the threads, waiting on this object's monitor. public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). public final void wait(long timeout,int nanos)throws InterruptedException causes the current thread to wait for the specified miliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
  • 24. Collections • Collections in java is a framework that provides an architecture to store and manipulate the group of objects • All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections • Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, etc.) and classes (ArrayList, Vector, LinkedList,, HashSet, LinkedHashSet, TreeSet, etc.)
  • 26.
  • 27.
  • 28. Collection Interface public boolean add(Object element) is used to insert an element in this collection. public boolean addAll(Collection c) is used to insert the specified collection elements in the invoking collection. public boolean remove(Object element) is used to delete an element from this collection. public boolean removeAll(Collection c) is used to delete all the elements of specified collection from the invoking collection. public boolean retainAll(Collection c) is used to delete all the elements of invoking collection except the specified collection. public int size() return the total number of elements in the collection. public void clear() removes the total no of element from the collection. public boolean contains(Object element) is used to search an element.
  • 29. public boolean containsAll(Collection c) is used to search the specified collection in this collection. public Iterator iterator() returns an iterator. public Object[] toArray() converts collection into array. public boolean isEmpty() checks if collection is empty. public boolean equals(Object element) matches two collection. public int hashCode() returns the hashcode number for collection.
  • 30. Java.util.Collections Class • The java.util.Collections class consists exclusively of static methods that operate on or return collections
  • 31. Sample Methods in Collections class • static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) This method searches the specified list for the specified object using the binary search algorithm • static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T< c) This method searches the specified list for the specified object using the binary search algorithm.
  • 32. Sample Methods in Collections class • static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) This method returns the minimum element of the given collection, according to the order induced by the specified comparator. • static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) This method returns the maximum element of the given collection, according to the order induced by the specified comparator.
  • 33. Sample Methods in Collections class • static void reverse(List<?> list) This method reverses the order of the elements in the specified list. • static <T> void sort(List<T> list, Comparator<? super T> c) This method sorts the specified list according to the order induced by the specified comparator.
  • 34. Comparable Interface • Comparable interface is used to order the objects of user-defined class • public int compareTo(Object obj): is used to compare the current object with the specified object.
  • 35. Comparator Interface • Comparator interface is used to order the objects of user-defined class • public int compare(Object obj1,Object obj2): compares the first object with second object
  • 37. Why? • Beginners usually start off by returning error codes • The inner working of your program should not have a protocol
  • 38. From the Clean Code book if (deletePage(page) == E_OK) { if (registry.deleteReference(page.name) == E_OK) { if (configKeys.deleteKey(page.name.makeKey()) == E_OK){ logger.log("page deleted"); } else { logger.log("configKey not deleted"); } } else { logger.log("deleteReference from registry failed"); } } else { logger.log("delete failed"); return E_ERROR; } Bad try { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } catch (Exception e) { logger.log(e.getMessage()); } Good Motive: Error Codes  awful nested IFs But using Exceptions  now, we can read the normal flow
  • 39. Three Categories of Exceptions(1/3) 1. Checked exceptions: is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care of (handle) these exceptions
  • 40. Three Categories of Exceptions(2/3) 2. Unchecked exceptions: is an exception that occurs at the time of execution, these are also called as Runtime Exceptions, these include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation (e.g.ArrayIndexOutOfBoundsException and NullPointerException).
  • 41. Three Categories of Exceptions(3/3) 3. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation
  • 44. Catching an Exception(2/2) • Since Java 7 you can handle more than one exceptions using a single catch block, this feature simplifies the code
  • 45. Finally block • The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception • Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code
  • 46.
  • 48. Java I/O • Java I/O (Input and Output) is used to process the input and produce the output based on the input • Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations
  • 49. Stream • A stream is a sequence of data. In Java a stream is composed of bytes. • In java, 3 streams are created for us automatically. All these streams are attached with console: 1. System.out: standard output stream 2. System.in: standard input stream 3. System.err: standard error stream
  • 51. OutputStream class • OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink public void write(int)throws IOException: is used to write a byte to the current output stream. public void write(byte[])throws IOException: is used to write an array of byte to the current output stream. public void flush()throws IOException: flushes the current output stream. public void close()throws IOException: is used to close the current output stream.
  • 52.
  • 53. InputStream class • InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes. public abstract int read()throws IOException: reads the next byte of data from the input stream.It returns -1 at the end of file. public int available()throws IOException: returns an estimate of the number of bytes that can be read from the current input stream. public void close()throws IOException: is used to close the current input stream.
  • 54.
  • 55. When to use what? • For simple and primitive reads and writes, use FileInputStream and FileOutputStream • For writing byte array into multiple files, use ByteArrayOutputStream and ByteArrayInputStream • For reading data from multiple streams, use SequenceInputStream • Java FileWriter and FileReader classes are used to write and read data from text files. • Java Buffered Stream classes uses an internal buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
  • 57. Serialization in Java • Serialization in java is a mechanism of writing the state of an object into a byte stream • The reverse operation of serialization is called deserialization.
  • 58. java.io.Serializable Interface import java.io.Serializable; public class Student implements Serializable{ int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } }
  • 59. Example of Java Serialization import java.io.*; class Persist{ public static void main(String args[])throws Exception{ Student s1 =new Student(211,"ravi"); FileOutputStream fout=new FileOutputStream("f.txt"); ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(s1); out.flush(); System.out.println("success"); } }
  • 60. Example of Java Deserialization import java.io.*; class Depersist{ public static void main(String args[])throws Exception{ ObjectInputStream in=new ObjectInputStream(new FileInput Stream("f.txt")); Student s=(Student)in.readObject(); System.out.println(s.id+" "+s.name); in.close(); } }
  • 61. Transient Keyword • If you don't want to serialize any data member of a class, you can mark it as transient
  • 62. Can I Serialize to XML or JSON? • Yes! • http://flexjson.sourceforge.net/ • https://docs.oracle.com/javase/7/docs/api/jav a/beans/XMLEncoder.html