SlideShare a Scribd company logo
1
What you get today.
Common to all.
Annotations
Log entries
Enumerations
Object creation.
Collections
Exception handling
Generics
2Java for SE
toString
•Always override toString.
•When practical, the toString method should return all of the
interesting information contained in the object.
•Keep updating whenever a new attribute added to the class.
•Let IDE to generate it for you.
3Java for SE
equals()
•Obey the general contract when overriding equals.
•A well defined equals method must follow,
Reflexivity
Symmetry
Transitivity
Consistent
For any non-null reference it should return,false.
•It is really hard to implement a correct equals method so use IDE
for generate it.
4Java for SE
hashcode()
•Always override hashCode when you override equals.
• You must override hashCode in every class that overrides equals
•It is some thing like a fingerprint of the object.
•“hashCode” method must consistently return the same integer
whenever it invoked for same object.
•If hashcose returns true for both object then equals also returns
true but not the vice versa.
•Let the IDE to generate a hashcode for you.
5Java for SE
Commons to all - summery
•Always override toString.
•Obey the general contract when overriding equals.
•Always override hashCode when you override equals.
•Override clone judiciously.
•Consider implementing Comparable.
6Java for SE
Generics
Let's’ assume, we wanted to define a collection of course objects.
We define a List data structure,
List data = new ArrayList();
Issue here is , it can contain any type of data. Processing a
heterogeneous collection will be a nightmare.
With Java 5 we can generalize collections to use only specific
data types (type safety), we call it generics.
List<Course> data = new ArrayList<Course> ();
7Java for SE
Generics and byte code.
A. List data = new ArrayList();
B. List<Course> data = new ArrayList<Course> ();
Let's’ assume we have define a non generalized list in class A
and Generalized list class B . Once compiled you get two byte
codes.
Will they be same ?
YES , When compiling, java will remove all the Generics after
they being evaluated and make sure collections does not contain
heterogeneous data. That's why you are not getting same code if
you're generate the source from byte code.
8Java for SE
Use generics everywhere.
Ensure type safety to your method inputs.
void createCourses(List<Course> courses){
}
Ensure type safety to your method outputs
List<Course> createCourses(List<Course> courses){
return new ArrayList<Course>();
}
9Java for SE
Collection Framework
Collection
Map List
10Java for SE
List
Map
Use MAP implementation if your data can be model as a Key
Value pair.
Some notable implementations
•HashMap.
•WeakHashMap
You can use an object as Key for the map but using null value
as key is not permitted.
11Java for SE
Map Performance
Searching an entry from a Map should take consistent
amount of time.It does not matter you have 10000 record or 1
record in the map. We call it O(1) performance.
But this depends on a factor called a load factor.
Load Factor = available data size / total capacity.
It's being proven that, O(1) only be achievable if the load
factor is near to 0.75
12Java for SE
Map Performance
Searching an entry from a Map should take consistent
amount of time.It does not matter you have 10000 record or 1
record in the map. We call it O(1) performance.
But this depends on a factor called a load factor.
Load Factor = available data size / total capacity.
It's being proven that, O(1) only be achievable if the load
factor is near to 0.75
13Java for SE
Map Performance
What will happen if you instantiate a Map as follow.
Map<String,String> users = new HashMap<>();
Other Constructors
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K,? extends V> m)
14Java for SE
List
If your data is linear or having multiple copies of same data
or containing null data, this is the better data structure for the
scenario.
There are two basic implementations.
•ArrayList.
‒Array based implementation which is having better performance
but you do not have ability to traverse through the list.
•LinkList.
‒Doubly link list based implementation which is enabling traversals
through the list.
15Java for SE
Set
If your data is nonlinear or having null value ( not all
implementations ) but there are not any duplicate values this will
be suitable for use.
Commonly used implementations.
•HashSet.
‒Hash Table based implementation but there is no grantee on the
order.
•LinkedHashSet.
‒Hash Table and link list based implementation which is having
predictable order.
Performance of both above will be determine by the load factor
16Java for SE
Natural Ordering
There are two types of ordering in a collection,
•Insert order - you can access data from the way you have inserted.
•Natural order- Data will be stored based on the properties of the
inserted object.
Example Scenario
You have set of student objects but you need to get the youngest
student whenever you get the first element but this need to be
fast as possible.
In such scenario you can use TreeSet implementation which
restructure the set based on the comparator provided.
17Java for SE
Avoid return null values.
What is the issue here ?
List<Course> retreiveCourses(List<Course> courses){
List<Course> courses= null;
// Invoke db but it returns null
return courses;
}
● Caller has to be careful since method may return null values
instead of a List.This will introduce more checks in callers
side.
● Returning a Null from a method is an anti pattern.
18Java for SE
Collections.
Collections is a utility class which provide plenty of useful
methods. Collection class provide few immutable , singleton
objects to safeguards us from returning null values.
Option 1 :
public static final List EMPTY_LIST
Option 2:
List<String> s = Collections.emptyList();
We can use both options instead of returning a null, but use
Option 2 since Option 1 does not provide the type safety.
19Java for SE
Collections.
Some other useful methods in collections.
By default, most of the collection are not thread safe, but with the
help of Collections we can make them safe.
List list = Collections.synchronizedList(new ArrayList());
Collections.replaceAll
Collections.sort
Collections.reverse
20Java for SE
Diamond Operator
Old approach:
Map<String,MyClass> classes = new HashMap<String,MyClass>();
New approach:
Map<String,MyClass> classes = new HashMap<>();
21Java for SE
Static factory method
Consider static factory methods instead of constructors.
In normal way , we invoke public constructor for creating an
object. Static factory method is an alternative which has more
benefits when compared to the constructors.
Sample from Boolean class
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
22Java for SE
Benefits of a static factory
method
•Unlike constructors, they have names.
•Unlike constructors,they are not required to create a new object
each time they’re invoked.
•Unlike constructors,they can return an object of any subtype of their
return type.
•they reduce the verbosity of creating parameterized type instances.
23Java for SE
Object creation.
•Consider static factory methods instead of constructors.
•Consider a builder when faced with many constructor parameters.
24Java for SE
Builder
Problem
NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27);
Bad Solution
NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);
Demo : builder pattern
25Java for SE
Immutability.
Create immutable unless you have good reason to be mutable.
What is an immutable object ?
Object which is not able to modify once it's being created.
What are the advantages of immutability ?
•Immutable objects are inherently thread-safe; they require no
synchronization so you can share them freely.
•Immutable objects are simple.
26Java for SE
Make a class immutable
•Don’t provide any methods that modify the object’s state.
•Ensure that the class can’t be extended.
•Make all fields final.
•Make all fields private.
•Ensure exclusive access to any mutable components.
27Java for SE
Well known immutable
class
•String is the well known immutable class
28Java for SE
Exception hierarchy.
29Java for SE
Check or Unchecked
•Use checked exceptions, if you think that caller should handle
the exception.
•Use runtime exceptions to indicate a programming errors. Such
as precondition violations.
30Java for SE
Standard exceptions
31Java for SE
Exception Occasion for Use
IllegalArgumentException Non-null parameter value is
inappropriate
IllegalStateException Object state is inappropriate for
method invocation
NullPointerException Parameter value is null where
prohibited
IndexOutOfBoundsException Index parameter value is out of
range
UnsupportedOperationExceptionObject does not support method
Do not ignore
try {
...
} catch (SomeException e) {
}
At the very least, the catch block should contain a comment
explaining why it is appropriate to ignore the exception.
32Java for SE
Catch what you can
handle.
try {
...
} catch (Exception e) {
}
•Catch only what you can handle, else throw it to higher level.
•Use smallest bucket to handle exception.
‒Do not use Exception class to catch all of your exceptions.
33Java for SE
Multi Catch Exceptions
Before
catch (IOException ex) {
logger.log(ex);
throw ex;
catch (SQLException ex) {
logger.log(ex);
throw ex;
}
Now
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
34Java for SE
Annotation
Annotations, a form of metadata, provide data about a program
that is not part of the program itself.By adding an annotation,
you can modify the functionality of the code without modifying.
Each annotation has two properties,
1. Where it can be used ( Retention Policy )
Ex . Class , Method, Attribute
2. Which time its being considered
Ex . Run time, Compile time, Source code
35Java for SE
Predefined annotations
There are plenty of predefined annotations, here we have listed
few commonly used.
•Deprecated - Indicate this is outdated and will be removed.
•Override - Instruct compiler, method is overridden from the parent.
•SuppressWarnings - Instruct compiler to ignore any warning
‒Ex : If you use a List without generic, compiler will throw a warning
‒This is a very risky annotation, do not use it if you know what you
are doing..
36Java for SE
Data Validation
Object orientation is all about, objects and message passing
among them. The common way of message passing is calling a
method or a function so its developers responsibility to protect
the internals of the object from the passed data.
Data Validation Strategies.
•Accept known good.
•Reject known bad.
•Sanitize
•No validation.
You should follow the top to bottom order when you do a data
validation.
37Java for SE
Accept known good.
This strategy is also known as "whitelist" or "positive" validation. The idea is
that you should check that the data is one of a set of tightly constrained
known good values. Any data that doesn't match should be rejected. Data
should be:
•Strongly typed at all times.
•Length checked and fields length minimized.
•Range checked if a numeric
•Unsigned unless required to be signed.
•Syntax or grammar should be checked prior to first use or inspection
If you expect a postcode, validate for a postcode (type, length and syntax):
38Java for SE
Accept known good.
Sample post code validation
public String isPostcode(String postcode) {
return (postcode != null && Pattern.matches("^(((2|8|9)d{2})|((02|08|09)d{2})|([1-
9]d{3}))$", postcode)) ? postcode : "";
}
More info :
https://www.owasp.org/index.php/Data_Validation
39Java for SE
Log file.
Log file is the first location you should look at in case of an
incident, since in most cases you do not have luxury to do a
remote debugging is not permitted.
Follow are few properties of a good log entry.
•It should be readable and meaningful.
•Log should be lightweight.
•Make sure log does not introduce a new bug.
•It should fall into correct log type.
•Always try to minimize the memory consumption by the log entry.
40Java for SE
Choose correct log type.
•ERROR
‒If you encounter an exception or an error make sure to log under
this type.
LOGGER.error(" Exception while order creation " , e));
•WARN
‒If you think something bad can happen due to some reason, then
log a warning message.
LOGGER.warn(" Disconnected from order processing service" ));
41Java for SE
Choose correct log type.
•DEBUG
‒If you need to log more data for tracking an issue ( during
the development phase)
LOGGER.debug(" order processing initiated for order id : " + 100 + "
by " + userID ));
•INFO
‒Use these type of logs to keep track of informations.
LOGGER.info(" Nightly order bulk processing process started ");
42Java for SE
Reduce memory
consumption by a log entry
When we log a debug entry, most of the time it associate with
plenty of string operations. Let's take below log entry.
List<MyClass> classes = new ArrayList<MyClass>();
LOGGER.debug("Class objects " + classes);
Better way to log highly memory consuming log entry.
if(LOGGER.isDebugEnabled()){
LOGGER.debug("Class objects " + classes);
}
43Java for SE
Enum
An enum type is a special data type that enables for a variable to
be a set of predefined constants.
Advantages of using enum.
•You can group constants with enum.
•They are compile time constants which means they are type safe.
•By default enum is singleton.
•Like other classes they can have constructors, attributes or methods.
•You can use enums for switch cases.
Always use enum type instead of int constants.
44Java for SE
Enumpublic enum Planet {
MERCURY (3.303e+23, 2.4397e6),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}
45Java for SE
Further Reading
Effective java is one of the few books
where any java developer should read.
46Presentation Title Arial Bold 7 pt
Image by Photographer's Name (Credit in black type) or
Image by Photographer's Name (Credit in white type)

More Related Content

What's hot

Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
André Faria Gomes
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 

What's hot (20)

Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
L11 array list
L11 array listL11 array list
L11 array list
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 

Similar to Java for newcomers

Java - Collections
Java - CollectionsJava - Collections
Java - Collections
Amith jayasekara
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
Mudit Gupta
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
İbrahim Kürce
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
Richard Styner
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
rangariprajwal4554
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java Collections.pptx
Java Collections.pptxJava Collections.pptx
Java Collections.pptx
AbhishekKudal2
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
Arpit Poladia
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Java 8
Java 8Java 8
Java best practices
Java best practicesJava best practices
Java best practices
Անուշիկ Միրզոյան
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
Rakesh Madugula
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppttutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
AbdisamedAdam
 
java02.ppt
java02.pptjava02.ppt
java02.ppt
MENACE4
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
BRIJESHKUMAR733739
 

Similar to Java for newcomers (20)

Java - Collections
Java - CollectionsJava - Collections
Java - Collections
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java Collections.pptx
Java Collections.pptxJava Collections.pptx
Java Collections.pptx
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Java 8
Java 8Java 8
Java 8
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppttutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
 
java02.ppt
java02.pptjava02.ppt
java02.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 

Recently uploaded

spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
riddhimaagrawal986
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 

Recently uploaded (20)

spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 

Java for newcomers

  • 1. 1
  • 2. What you get today. Common to all. Annotations Log entries Enumerations Object creation. Collections Exception handling Generics 2Java for SE
  • 3. toString •Always override toString. •When practical, the toString method should return all of the interesting information contained in the object. •Keep updating whenever a new attribute added to the class. •Let IDE to generate it for you. 3Java for SE
  • 4. equals() •Obey the general contract when overriding equals. •A well defined equals method must follow, Reflexivity Symmetry Transitivity Consistent For any non-null reference it should return,false. •It is really hard to implement a correct equals method so use IDE for generate it. 4Java for SE
  • 5. hashcode() •Always override hashCode when you override equals. • You must override hashCode in every class that overrides equals •It is some thing like a fingerprint of the object. •“hashCode” method must consistently return the same integer whenever it invoked for same object. •If hashcose returns true for both object then equals also returns true but not the vice versa. •Let the IDE to generate a hashcode for you. 5Java for SE
  • 6. Commons to all - summery •Always override toString. •Obey the general contract when overriding equals. •Always override hashCode when you override equals. •Override clone judiciously. •Consider implementing Comparable. 6Java for SE
  • 7. Generics Let's’ assume, we wanted to define a collection of course objects. We define a List data structure, List data = new ArrayList(); Issue here is , it can contain any type of data. Processing a heterogeneous collection will be a nightmare. With Java 5 we can generalize collections to use only specific data types (type safety), we call it generics. List<Course> data = new ArrayList<Course> (); 7Java for SE
  • 8. Generics and byte code. A. List data = new ArrayList(); B. List<Course> data = new ArrayList<Course> (); Let's’ assume we have define a non generalized list in class A and Generalized list class B . Once compiled you get two byte codes. Will they be same ? YES , When compiling, java will remove all the Generics after they being evaluated and make sure collections does not contain heterogeneous data. That's why you are not getting same code if you're generate the source from byte code. 8Java for SE
  • 9. Use generics everywhere. Ensure type safety to your method inputs. void createCourses(List<Course> courses){ } Ensure type safety to your method outputs List<Course> createCourses(List<Course> courses){ return new ArrayList<Course>(); } 9Java for SE
  • 11. Map Use MAP implementation if your data can be model as a Key Value pair. Some notable implementations •HashMap. •WeakHashMap You can use an object as Key for the map but using null value as key is not permitted. 11Java for SE
  • 12. Map Performance Searching an entry from a Map should take consistent amount of time.It does not matter you have 10000 record or 1 record in the map. We call it O(1) performance. But this depends on a factor called a load factor. Load Factor = available data size / total capacity. It's being proven that, O(1) only be achievable if the load factor is near to 0.75 12Java for SE
  • 13. Map Performance Searching an entry from a Map should take consistent amount of time.It does not matter you have 10000 record or 1 record in the map. We call it O(1) performance. But this depends on a factor called a load factor. Load Factor = available data size / total capacity. It's being proven that, O(1) only be achievable if the load factor is near to 0.75 13Java for SE
  • 14. Map Performance What will happen if you instantiate a Map as follow. Map<String,String> users = new HashMap<>(); Other Constructors HashMap() HashMap(int initialCapacity) HashMap(int initialCapacity, float loadFactor) HashMap(Map<? extends K,? extends V> m) 14Java for SE
  • 15. List If your data is linear or having multiple copies of same data or containing null data, this is the better data structure for the scenario. There are two basic implementations. •ArrayList. ‒Array based implementation which is having better performance but you do not have ability to traverse through the list. •LinkList. ‒Doubly link list based implementation which is enabling traversals through the list. 15Java for SE
  • 16. Set If your data is nonlinear or having null value ( not all implementations ) but there are not any duplicate values this will be suitable for use. Commonly used implementations. •HashSet. ‒Hash Table based implementation but there is no grantee on the order. •LinkedHashSet. ‒Hash Table and link list based implementation which is having predictable order. Performance of both above will be determine by the load factor 16Java for SE
  • 17. Natural Ordering There are two types of ordering in a collection, •Insert order - you can access data from the way you have inserted. •Natural order- Data will be stored based on the properties of the inserted object. Example Scenario You have set of student objects but you need to get the youngest student whenever you get the first element but this need to be fast as possible. In such scenario you can use TreeSet implementation which restructure the set based on the comparator provided. 17Java for SE
  • 18. Avoid return null values. What is the issue here ? List<Course> retreiveCourses(List<Course> courses){ List<Course> courses= null; // Invoke db but it returns null return courses; } ● Caller has to be careful since method may return null values instead of a List.This will introduce more checks in callers side. ● Returning a Null from a method is an anti pattern. 18Java for SE
  • 19. Collections. Collections is a utility class which provide plenty of useful methods. Collection class provide few immutable , singleton objects to safeguards us from returning null values. Option 1 : public static final List EMPTY_LIST Option 2: List<String> s = Collections.emptyList(); We can use both options instead of returning a null, but use Option 2 since Option 1 does not provide the type safety. 19Java for SE
  • 20. Collections. Some other useful methods in collections. By default, most of the collection are not thread safe, but with the help of Collections we can make them safe. List list = Collections.synchronizedList(new ArrayList()); Collections.replaceAll Collections.sort Collections.reverse 20Java for SE
  • 21. Diamond Operator Old approach: Map<String,MyClass> classes = new HashMap<String,MyClass>(); New approach: Map<String,MyClass> classes = new HashMap<>(); 21Java for SE
  • 22. Static factory method Consider static factory methods instead of constructors. In normal way , we invoke public constructor for creating an object. Static factory method is an alternative which has more benefits when compared to the constructors. Sample from Boolean class public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } 22Java for SE
  • 23. Benefits of a static factory method •Unlike constructors, they have names. •Unlike constructors,they are not required to create a new object each time they’re invoked. •Unlike constructors,they can return an object of any subtype of their return type. •they reduce the verbosity of creating parameterized type instances. 23Java for SE
  • 24. Object creation. •Consider static factory methods instead of constructors. •Consider a builder when faced with many constructor parameters. 24Java for SE
  • 25. Builder Problem NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27); Bad Solution NutritionFacts cocaCola = new NutritionFacts(); cocaCola.setServingSize(240); cocaCola.setServings(8); cocaCola.setCalories(100); cocaCola.setSodium(35); cocaCola.setCarbohydrate(27); Demo : builder pattern 25Java for SE
  • 26. Immutability. Create immutable unless you have good reason to be mutable. What is an immutable object ? Object which is not able to modify once it's being created. What are the advantages of immutability ? •Immutable objects are inherently thread-safe; they require no synchronization so you can share them freely. •Immutable objects are simple. 26Java for SE
  • 27. Make a class immutable •Don’t provide any methods that modify the object’s state. •Ensure that the class can’t be extended. •Make all fields final. •Make all fields private. •Ensure exclusive access to any mutable components. 27Java for SE
  • 28. Well known immutable class •String is the well known immutable class 28Java for SE
  • 30. Check or Unchecked •Use checked exceptions, if you think that caller should handle the exception. •Use runtime exceptions to indicate a programming errors. Such as precondition violations. 30Java for SE
  • 31. Standard exceptions 31Java for SE Exception Occasion for Use IllegalArgumentException Non-null parameter value is inappropriate IllegalStateException Object state is inappropriate for method invocation NullPointerException Parameter value is null where prohibited IndexOutOfBoundsException Index parameter value is out of range UnsupportedOperationExceptionObject does not support method
  • 32. Do not ignore try { ... } catch (SomeException e) { } At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception. 32Java for SE
  • 33. Catch what you can handle. try { ... } catch (Exception e) { } •Catch only what you can handle, else throw it to higher level. •Use smallest bucket to handle exception. ‒Do not use Exception class to catch all of your exceptions. 33Java for SE
  • 34. Multi Catch Exceptions Before catch (IOException ex) { logger.log(ex); throw ex; catch (SQLException ex) { logger.log(ex); throw ex; } Now catch (IOException|SQLException ex) { logger.log(ex); throw ex; } 34Java for SE
  • 35. Annotation Annotations, a form of metadata, provide data about a program that is not part of the program itself.By adding an annotation, you can modify the functionality of the code without modifying. Each annotation has two properties, 1. Where it can be used ( Retention Policy ) Ex . Class , Method, Attribute 2. Which time its being considered Ex . Run time, Compile time, Source code 35Java for SE
  • 36. Predefined annotations There are plenty of predefined annotations, here we have listed few commonly used. •Deprecated - Indicate this is outdated and will be removed. •Override - Instruct compiler, method is overridden from the parent. •SuppressWarnings - Instruct compiler to ignore any warning ‒Ex : If you use a List without generic, compiler will throw a warning ‒This is a very risky annotation, do not use it if you know what you are doing.. 36Java for SE
  • 37. Data Validation Object orientation is all about, objects and message passing among them. The common way of message passing is calling a method or a function so its developers responsibility to protect the internals of the object from the passed data. Data Validation Strategies. •Accept known good. •Reject known bad. •Sanitize •No validation. You should follow the top to bottom order when you do a data validation. 37Java for SE
  • 38. Accept known good. This strategy is also known as "whitelist" or "positive" validation. The idea is that you should check that the data is one of a set of tightly constrained known good values. Any data that doesn't match should be rejected. Data should be: •Strongly typed at all times. •Length checked and fields length minimized. •Range checked if a numeric •Unsigned unless required to be signed. •Syntax or grammar should be checked prior to first use or inspection If you expect a postcode, validate for a postcode (type, length and syntax): 38Java for SE
  • 39. Accept known good. Sample post code validation public String isPostcode(String postcode) { return (postcode != null && Pattern.matches("^(((2|8|9)d{2})|((02|08|09)d{2})|([1- 9]d{3}))$", postcode)) ? postcode : ""; } More info : https://www.owasp.org/index.php/Data_Validation 39Java for SE
  • 40. Log file. Log file is the first location you should look at in case of an incident, since in most cases you do not have luxury to do a remote debugging is not permitted. Follow are few properties of a good log entry. •It should be readable and meaningful. •Log should be lightweight. •Make sure log does not introduce a new bug. •It should fall into correct log type. •Always try to minimize the memory consumption by the log entry. 40Java for SE
  • 41. Choose correct log type. •ERROR ‒If you encounter an exception or an error make sure to log under this type. LOGGER.error(" Exception while order creation " , e)); •WARN ‒If you think something bad can happen due to some reason, then log a warning message. LOGGER.warn(" Disconnected from order processing service" )); 41Java for SE
  • 42. Choose correct log type. •DEBUG ‒If you need to log more data for tracking an issue ( during the development phase) LOGGER.debug(" order processing initiated for order id : " + 100 + " by " + userID )); •INFO ‒Use these type of logs to keep track of informations. LOGGER.info(" Nightly order bulk processing process started "); 42Java for SE
  • 43. Reduce memory consumption by a log entry When we log a debug entry, most of the time it associate with plenty of string operations. Let's take below log entry. List<MyClass> classes = new ArrayList<MyClass>(); LOGGER.debug("Class objects " + classes); Better way to log highly memory consuming log entry. if(LOGGER.isDebugEnabled()){ LOGGER.debug("Class objects " + classes); } 43Java for SE
  • 44. Enum An enum type is a special data type that enables for a variable to be a set of predefined constants. Advantages of using enum. •You can group constants with enum. •They are compile time constants which means they are type safe. •By default enum is singleton. •Like other classes they can have constructors, attributes or methods. •You can use enums for switch cases. Always use enum type instead of int constants. 44Java for SE
  • 45. Enumpublic enum Planet { MERCURY (3.303e+23, 2.4397e6), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } } 45Java for SE
  • 46. Further Reading Effective java is one of the few books where any java developer should read. 46Presentation Title Arial Bold 7 pt Image by Photographer's Name (Credit in black type) or Image by Photographer's Name (Credit in white type)

Editor's Notes

  1. &amp;lt;number&amp;gt;
  2. Let IDE , to avoid bugs ( NPE )
  3. Reflexivity -- Object must be equal to itself Symmetry -- two objects must agree on whether they are equal Transitivity -- if one object is equal to a second and the second object is equal to a third Once you’ve violated the equals contract, you simply don’t know how other objects will behave when confronted with your object
  4. Good hash function should not generate same hash for two objects
  5. Do a demo on how to generate them with IDE
  6. Learn about wile cars, which introduce flexibility to contain hetrogeniuose
  7. WeakHashMap key will be automatically removed by the GC if ref is no longer exist
  8. WeakHashMap key will be automatically removed by the GC if ref is no longer exist
  9. WeakHashMap key will be automatically removed by the GC if ref is no longer exist
  10. Default will be .75 with 16 size
  11. There are empty collections for set , map , list If field being used, compiler will throw a warning Try out other methods, ex, sorted set
  12. Sync methods for list, set map Check out all other methods
  13. Sync methods for list, set map Check out all other methods
  14. What most important is readability Limit the object creation
  15. JavaBean may be in an inconsistent state partway through its construction
  16. JavaBean may be in an inconsistent state partway through its construction
  17. Disadvantage is for each distinct value you have to create a new object Not extend by making constructor private
  18. Discuss string pool
  19. Use standard exception whenever necessary. Because people get clear idea
  20. Demo auto closable
  21. It is recommended to use predefined annotations, offered by the java or framework And define a custom annotation when you does not need to modify existing functionality.
  22. This available for info, debug, warn , error also There is a tradeoff, between memory and the readability.
  23. This available for info, debug, warn , error also There is a tradeoff, between memory and the readability.
  24. Lightweight, we have seen log which take more time than actual functionalities
  25. Lightweight, we have seen log which take more time than actual functionalities
  26. Debug , make sure to log as much as possible data with debug level log Info is not for logging data, its for logging a information message
  27. This available for info, debug, warn , error also There is a tradeoff, between memory and the readability.
  28. You can grup them , give a meaningful name. You can not add strings to switch cases