SlideShare a Scribd company logo
1 of 13
JAVA best practices
● Avoid magic numbers, use private static final (constants)
● Avoid double negatives, e.g. if(!notFound())
● Don’t put constants in interfaces use import static instead
● Use enums not constants
● Don’t do string concatenation in a loop
● Never make an instance fields of class public . Use private field +
GETTER_FUNCTION() and SETTER_FUNCTION()
Try to use Primitive types instead of Wrapper class
● Wrapper classes are great. But at same time they are slow.
● Primitive types are just values, whereas Wrapper classes are stores
information about complete class.
int x = 10;
Integer x1 = new Integer(10);
● Also if you are using a wrapper class object then never forget to initialize it to
a default value(null).
JAVA best practices
JAVA best practices
Avoid creating unnecessary objects and always prefer to do Lazy initialization. Initialize only when
required
public class Countries {
private List countries;
public List getCountries() {
if(null == countries) {
countries = new ArrayList();
}
return countries;
}
}
Abstract classes compared to interfaces
You cannot instantiate them, and they may contain a mix of methods declared with or without an
implementation.
The only methods that have implementations in interfaces are default and static methods.
In interfaces all fields are automatically public, static, and final, and all methods that declared or
defined (as default methods) are public
In abstract classes fields can be not static and final, and concrete methods can be public, protected,
and private.
You can extend only one class, whether or not it is abstract, whereas you can implement any number
of interfaces
When use?
abstract class
o You want to share code among several closely related classes.
o You expect that classes that extend your abstract class have many common methods or fields, or require
access modifiers other than public (such as protected and private).
o You want to declare non-static or non-final fields. This enables you to define methods that can access and
modify the state of the object to which they belong.
interface
o You expect that unrelated classes would implement your interface.
o You want to specify the behavior of a particular data type, but not concerned about who implements its
behavior.
Switch or If
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated
types (discussed in Enum Types), the String class(in Java SE 7 and later), and a few special classes
that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and
Strings).
If the number of switch labels is N, a chain of ifs takes O(N) to dispatch, while a switch always
dispatches in O(1). This is how it is done: compiler places addresses of switch labels into an array,
computes an index based on the label values, and performs a jump directly, without comparing the
switch expression to value one by one. In case of strings used as switch labels, the compiler produces
a hash table, which looks up an address in O(1) as well.
Loop optimization
At first set the length in variable then use that variable
for(int i = 0; i < ob.length();++i){
// some code
}
int length = ob.length();
for(int i = 0; i < length;++i){
// some code
}
Loop optimization
● The loop can be improved even more by changing the loop to count backwards. The JVM is
optimized to compare to integers between -1 and +5. So rewriting a loop to compare against 0
will produce faster loops. So for example, the loop on the right could be changed to use the
following for loop instruction: for (int j = len-1; j >= 0; j—)
● Once the processing requirement of a loop has been completed, use the break statement to
terminate the loop. This saves the JVM from iterating through the loop doing the evaluations of
the termination criteria.
Loop optimization
If a computation produces the same value in every loop iteration, move it out of the loop
for i = 1 to N {
Integer x = 100*N + 10*i
}
var1 = 100*N
for i = 1 to N {
Integer x = var1 + 10* i
}
Collections
1. Set
● No particular order
● There are two libraries for set collections HashSet and TreeSet.HashSet is faster than TreeSet because TreeSet
provides iteration of the keys in order
1. List
● Linear manner. (An array is an example of a list where objects are stored into the list based upon the data
structure’s index.)
● There are 4 classes included in a list: ArayList, Vector, Stack, LinkedList(each Node consists of a value, prev
and next pointers)
● ArrayList is the fastest
● Vector is slower because of synchronization
Collections
3. Map
● Paired structure key value retrieved by key
● There are 3 classes included in map collection: HashMap, HashTable, TreeMap,
● Using for searching when you want to retrieve an object
● HashTables and HashMaps are fast
Unlike the Vector collection class, ArrayLists and HashMaps are not synchronized classes. When using multithreaded
applications use ArrayLists and HashMaps to improve performance when synchronized access to the data is not a
concern.
You should always declare your variable as a List so that the implementation can be changed later as needed.
NullPointerException
● Avoid returning null from method, instead return empty collection or empty array. By returning
empty collection or empty array you make sure that basic calls like size(), length() doesn't fail
with NullPointerException.
● Never call .equals(null) equals is a method, if you try to invoke it on a null reference, you'll get a
NullPointerException.
● Call equals() and equalsIgnoreCase() methods on known String literal rather unknown object
Object unknownObj = null
if(“str”.equals(unknownObj)){
System.out.println(“better way”);
}
● Use StringUtils.isBlank(), isNumeric(), isWhiteSpace(), isEmpty() methods
Modify Strings with StringBuilder
String objects are immutable.
● You may think you’re changing a String, but you’re actually creating a new object.
● Danger of OutOfMemoryErrors.
● Poor performance.
StringBuilder is mutable.
● All changes are to the same object.

More Related Content

What's hot

What's hot (20)

Java best practices
Java best practicesJava best practices
Java best practices
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Java String
Java String Java String
Java String
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
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
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
String in java
String in javaString in java
String in java
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 

Similar to Java best practices

5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptxteddiyfentaw
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environmentsJ'tong Atong
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Data Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptxData Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptxR S Anu Prabha
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxdonnajames55
 
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 programmingKeshav 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 programmingKeshav Kumar
 
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and TensorfowAaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and TensorfowAminaRepo
 

Similar to Java best practices (20)

kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Learning core java
Learning core javaLearning core java
Learning core java
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Data Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptxData Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptx
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Java
JavaJava
Java
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
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
 
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and TensorfowAaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
 

Recently uploaded

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 

Recently uploaded (20)

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 

Java best practices

  • 1. JAVA best practices ● Avoid magic numbers, use private static final (constants) ● Avoid double negatives, e.g. if(!notFound()) ● Don’t put constants in interfaces use import static instead ● Use enums not constants ● Don’t do string concatenation in a loop ● Never make an instance fields of class public . Use private field + GETTER_FUNCTION() and SETTER_FUNCTION()
  • 2. Try to use Primitive types instead of Wrapper class ● Wrapper classes are great. But at same time they are slow. ● Primitive types are just values, whereas Wrapper classes are stores information about complete class. int x = 10; Integer x1 = new Integer(10); ● Also if you are using a wrapper class object then never forget to initialize it to a default value(null). JAVA best practices
  • 3. JAVA best practices Avoid creating unnecessary objects and always prefer to do Lazy initialization. Initialize only when required public class Countries { private List countries; public List getCountries() { if(null == countries) { countries = new ArrayList(); } return countries; } }
  • 4. Abstract classes compared to interfaces You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. The only methods that have implementations in interfaces are default and static methods. In interfaces all fields are automatically public, static, and final, and all methods that declared or defined (as default methods) are public In abstract classes fields can be not static and final, and concrete methods can be public, protected, and private. You can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces
  • 5. When use? abstract class o You want to share code among several closely related classes. o You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). o You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong. interface o You expect that unrelated classes would implement your interface. o You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  • 6. Switch or If A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class(in Java SE 7 and later), and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings). If the number of switch labels is N, a chain of ifs takes O(N) to dispatch, while a switch always dispatches in O(1). This is how it is done: compiler places addresses of switch labels into an array, computes an index based on the label values, and performs a jump directly, without comparing the switch expression to value one by one. In case of strings used as switch labels, the compiler produces a hash table, which looks up an address in O(1) as well.
  • 7. Loop optimization At first set the length in variable then use that variable for(int i = 0; i < ob.length();++i){ // some code } int length = ob.length(); for(int i = 0; i < length;++i){ // some code }
  • 8. Loop optimization ● The loop can be improved even more by changing the loop to count backwards. The JVM is optimized to compare to integers between -1 and +5. So rewriting a loop to compare against 0 will produce faster loops. So for example, the loop on the right could be changed to use the following for loop instruction: for (int j = len-1; j >= 0; j—) ● Once the processing requirement of a loop has been completed, use the break statement to terminate the loop. This saves the JVM from iterating through the loop doing the evaluations of the termination criteria.
  • 9. Loop optimization If a computation produces the same value in every loop iteration, move it out of the loop for i = 1 to N { Integer x = 100*N + 10*i } var1 = 100*N for i = 1 to N { Integer x = var1 + 10* i }
  • 10. Collections 1. Set ● No particular order ● There are two libraries for set collections HashSet and TreeSet.HashSet is faster than TreeSet because TreeSet provides iteration of the keys in order 1. List ● Linear manner. (An array is an example of a list where objects are stored into the list based upon the data structure’s index.) ● There are 4 classes included in a list: ArayList, Vector, Stack, LinkedList(each Node consists of a value, prev and next pointers) ● ArrayList is the fastest ● Vector is slower because of synchronization
  • 11. Collections 3. Map ● Paired structure key value retrieved by key ● There are 3 classes included in map collection: HashMap, HashTable, TreeMap, ● Using for searching when you want to retrieve an object ● HashTables and HashMaps are fast Unlike the Vector collection class, ArrayLists and HashMaps are not synchronized classes. When using multithreaded applications use ArrayLists and HashMaps to improve performance when synchronized access to the data is not a concern. You should always declare your variable as a List so that the implementation can be changed later as needed.
  • 12. NullPointerException ● Avoid returning null from method, instead return empty collection or empty array. By returning empty collection or empty array you make sure that basic calls like size(), length() doesn't fail with NullPointerException. ● Never call .equals(null) equals is a method, if you try to invoke it on a null reference, you'll get a NullPointerException. ● Call equals() and equalsIgnoreCase() methods on known String literal rather unknown object Object unknownObj = null if(“str”.equals(unknownObj)){ System.out.println(“better way”); } ● Use StringUtils.isBlank(), isNumeric(), isWhiteSpace(), isEmpty() methods
  • 13. Modify Strings with StringBuilder String objects are immutable. ● You may think you’re changing a String, but you’re actually creating a new object. ● Danger of OutOfMemoryErrors. ● Poor performance. StringBuilder is mutable. ● All changes are to the same object.