SlideShare une entreprise Scribd logo
1  sur  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.

Contenu connexe

Tendances

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 

Dernier (20)

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

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.