SlideShare uma empresa Scribd logo
1 de 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?

Mais conteúdo relacionado

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 

Último (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 

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