Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs

book cover: Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs Organizations worldwide rely on Java code to perform mission-critical tasks, so that code must be reliable, robust, fast, maintainable, and secure. Java Coding Guidelines brings together expert guidelines, recommendations, and code examples to help you meet these demands. You'll find 75 guidelines, each presented consistently and intuitively. For each guideline, conformance requirements are specified; for most, noncompliant code examples and compliant solutions are also offered. The authors explain when to apply each guideline and provide references to even more detailed information. Reflecting pioneering research on Java security, Java™ Coding Guidelines offers updated techniques for protecting against both deliberate attacks and other unexpected events. You'll find best practices for improving code reliability and clarity, and a full chapter exposing common misunderstandings that lead to suboptimal code. Intended primarily for software professionals working in Java Standard Edition (SE) 7 Platform environments, this guide is also useful to those working with Java Micro Edition (ME), Java Enterprise Edition (EE), and other contemporary Java language platforms.

authors: Fred Long, Dhruv Mohindra, Robert C. Seacord, Dean F. Sutherland, and David Svoboda (with a foreword by James A. Gosling, father of the Java programming language)

Related Training and Products

Secure Coding in C and C++ Training Course
This four-day course provides a detailed explanation of common programming errors in C and C++ and describes how these errors can lead to code that is vulnerable to exploitation. The course concentrates on security issues intrinsic to the C and C++ programming languages and associated libraries. The intent is for this course to be useful to anyone involved in developing secure C and C++ programs regardless of the specific application.

Secure Coding Training Course
An ongoing development effort in collaboration with the Software Engineering Institute's CERT Division, this course focuses on common security issues in C and C++ development. With security expert Robert Seacord serving as lead content author, the course addresses a key need in professional education for software developers. Topics to be covered include the secure and insecure use of integers, arrays, strings, dynamic memory, formatted input/output functions, and file I/O. Continued development is being funded by partnerships with industry.

Source Code Analysis Laboratory (SCALe)
SCALe consists of commercial, open source, and experimental analysis that is used to analyze various code bases, including those from the DoD, energy delivery systems, medical devices, and more. SCALe provides value to the customer, but it also aids research into the effectiveness of coding rules and analysis.

Get the Book

Visit the Informit website to order Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs.

Order the Book Today

"A must-read for all Java developers. . . . Every developer has a responsibility to author code that is free of significant security vulnerabilities. This book provides realistic guidance to help Java developers implement desired functionality with security, reliability, and maintainability goals in mind."
—Mary Ann Davidson, Chief Security Officer, Oracle Corporation

Fred Long is a senior lecturer in the Department of Computer Science, Aberystwyth University, in the United Kingdom. He is chairman of the British Computer Society's Mid-Wales Branch. Fred has been a visiting scientist at the Software Engineering Institute (SEI) since 1992. Recently, his research has involved the investigation of vulnerabilities in Java. Fred is also a coauthor of The CERT Oracle Secure Coding Standard for Java (Addison-Wesley, 2012).

Dhruv Mohindra is a technical lead in the security practices group that is part of the CTO's office at Persistent Systems Limited, India, where he provides information security consulting solutions across various technology verticals such as cloud, collaboration, banking and finance, telecommunications, enterprise, mobility, life sciences, and health care. Dhruv has worked for CERT at the Software Engineering Institute and continues to collaborate to improve the state of security awareness in the programming community. Dhruv is also a coauthor of The CERT Oracle Secure Coding Standard for Java (Addison-Wesley, 2012).

Robert Seacord began programming (professionally) for IBM in 1982 and has been programming in C since 1985, and in C++ since 1992. Robert is currently a Senior Vulnerability Analyst with the CERT/Coordination Center (CERT/CC) at the Software Engineering Institute (SEI). As a member of the Vulnerability Analysis Team, Robert works with other CERT team members to analyze software vulnerability reports and assess the risk to the internet and other critical infrastructures, identify underlying causes of vulnerabilities, and develop coding practices to improve the security of software systems.

Dean F. Sutherland is a senior software security engineer at CERT. Dean received his PhD in software engineering from Carnegie Mellon in 2008. Before his return to academia, he spent 14 years working as a professional software engineer at Tartan, Inc. He spent the last 6 of those years as a senior member of the technical staff and a technical lead for compiler backend technology. Dean is also a coauthor of The CERT Oracle Secure Coding Standard for Java (Addison-Wesley, 2012).

David Svoboda is a software security engineer at CERT/SEI. He also maintains the CERT Secure Coding standard websites for Java, as well as C, C++, and Perl. David has been the primary developer on a diverse set of software development projects at Carnegie Mellon since 1991, ranging from hierarchical chip modeling and social organization simulation to automated machine translation (AMT). David is also a coauthor of The CERT Oracle Secure Coding Standard for Java (Addison-Wesley, 2012).

Foreword (by James Gosling)



About the Authors

Chapter 1 Security

Limit the lifetime of sensitive data
Do not store unencrypted sensitive information on the client side
Provide sensitive mutable classes with unmodifiable wrappers
Ensure that security-sensitive methods are called with validated arguments
Prevent arbitrary file upload
Properly encode or escape output
Prevent code injection
Prevent XPath Injection
Prevent LDAP injection
Do not use the clone () method to copy untrusted method parameters
Do not use Object.equals () to compare cryptographic keys
Do not use insecure or weak cryptographic algorithms
Store passwords using a hash function
Ensure that SecureRandom is properly seeded
Do not rely on methods that can be overridden by untrusted code
Avoid granting excess privileges
Minimize privileged code
Do not expose methods that use reduced-security checks to untrusted code
Define custom security permissions for fine-grained security
Create a secure sandbox using a security manager
Do not let untrusted code misuse privileges of callback methods

Chapter 2 Defensive Programming

Minimize the scope of variables
Minimize the scope of the @SuppressWarnings annotation
Minimize the accessibility of classes and their members
Document thread-safety and use annotations where applicable
Always provide feedback about the resulting value of a method
Identify files using multiple file attributes
Do not attach significance to the ordinal associated with an enum
Be aware of numeric promotion behavior
Enable compile-time type checking of variable arity parameter types
Do not apply public final to constants whose value might change in later releases
Avoid cyclic dependencies between packages
Prefer user-defined exceptions over more general exception types
Try to gracefully recover from system errors
Carefully design interfaces before releasing them
Write garbage-collection-friendly code

Chapter 3 Reliability

Do not shadow or obscure identifiers in subscopes
Do not declare more than one variable per declaration
Use meaningful symbolic constants to represent literal values in program logic
Properly encode relationships in constant definitions
Return an empty array or collection instead of a null value for methods that return an array or collection
Use exceptions only for exceptional conditions
Use a try-with-resources statement to safely handle closeable resources
Do not use assertions to verify the absence of runtime errors
Use the same type for the second and third operands in conditional expressions
Do not serialize direct handles to system resources
Prefer using iterators over enumerations
Do not use direct buffers for short-lived, infrequently used objects
Remove short-lived objects from long-lived container objects

Chapter 4 Program Understandability

Be careful using visually misleading identifiers and literals
Avoid ambiguous overloading of variable arity methods
Avoid in-band error indicators
Do not perform assignments in conditional expressions
Use braces for the body of an if, for, or while statement
Do not place a semicolon immediately following an if, for, or while condition
Finish every set of statements associated with a case label with a break statement
Avoid inadvertent wrapping of loop counters
Use parentheses for precedence of operation
Do not make assumptions about file creation
Convert integers to floating point for floating-point operations
Ensure that the clone method calls super.clone
Use comments consistently and in a readable fashion
Detect and remove superfluous code and values
Strive for logical completeness
Avoid ambiguous or confusing uses of overloading

Chapter 5 Programmer Misconceptions

Do not assume that declaring a reference volatile guarantees safe publication of the members of the     referenced object
Do not assume that the sleep (), yield (), or getState () methods provide synchronization semantics
Do not assume that the remainder operator always returns a nonnegative result for integral operands
Do not confuse abstract object equality with reference equality
Understand the differences between bitwise and logical operators
Understand how escape characters are interpreted when strings are loaded
Do not use overloaded methods to differentiate between runtime types
Never confuse the immutability of a reference with that of the referenced object
Use the serialization methods writeUnshared() and readUnshared() with care
Do not attempt to help the garbage collector by setting local reference variables to null

Appendix A: Android




[Apache 2013]
"Apache Tika: A Content Analysis Toolkit." The Apache Software Foundation (2003).

[API 2006]
"Java Platform, Standard Edition 6 API Specification," Oracle (2006/2011).

[API 2013]
"Java Platform, Standard Edition 7 API Specification," Oracle (2013).

[Black 2004]
Black, Paul E., and Paul J. Tanenbaum. "Partial order." "Dictionary of Algorithms and Data Structures." Edited by Paul E. Black. U.S. National Institute (2004). of Standards and Technology.

[Bloch 2001]
Bloch, Joshua. Effective Java: Programming Language Guide. Boston, MA: Addison-Wesley, 2001.

[Bloch 2005]
Bloch, Joshua and Neal Gafter. Java Puzzlers: Traps, Pitfalls, and Corner Cases. Boston, MA: Addison-Wesley, 2005.

[Bloch 2008]
Bloch, Joshua. Effective Java: Programming Language Guide, 2nd Edition. Upper Saddle River, NJ: Addison-Wesley, 2008.

[Campione 1996]
Campione, Mary and Kathy Walrath. The Java Tutorial: Object- Oriented Programming for the Internet. Reading, MA: Addison-Wesley, 1996.

[Chan 1998]
Chan, Patrick, Rosanna Lee, & Douglas Kramer. The Java Class Libraries: Supplement for the Java 2 Platform, Vol. 1, 2nd Edition. Upper Saddle River, NJ: Prentice Hall, 1998.

[Cohen 1981]
Cohen, D. "On Holy Wars and a Plea for Peace," IEEE Computer, 14(10):48–54 (1981).

[Conventions 2009]
Code Conventions for the Java Programming Language. Oracle (2009).

[Coomes 2007]
Coomes, John, Peter Kessler, & Tony Printezis. "Garbage Collection-Friendly Programming." Java SE Garbage Collection Group, Sun Microsystems, JavaOne Conference, 2007.

[Core Java 2004]
Horstmann, Cay S., and Gary Cornell. Core Java™ 2, Vol. I: Fundamentals, Seventh Edition. Upper Saddle River, NJ: Prentice Hall, 2004.

[Coverity 2007]
Coverity Prevent User's Manual (3.3.0). Coverity, 2007.

[Daconta 2003]
Daconta, Michael C., Kevin T. Smith, Donald Avondolio, & W. Clay Richardson. More Java Pitfalls. Indianapolis, IN: Wiley 2003.

[Davis 2008]
Davis, Mark, and Ken Whistler. Unicode Standard Annex #15: Unicode Normalization Forms, 2008.

[Dennis 1966]
Dennis, Jack B., and Earl C. Van Horn. 1966. "Programming Semantics for Multiprogrammed Computations." Communications of the ACM, 9(3):143–155 (1966). doi: 10.1145/365230.365252.

[Dougherty 2009]
Dougherty, Chad, Kirk Sayre, Robert C. Seacord, David Svoboda, & Kazuya Togashi. Secure Design Patterns (CMU/SEI-2009-TR-010). Software Engineering Institute, Carnegie Mellon University, 2009.

[ESA 2005]
ESA (European Space Agency). Java Coding Standards. Prepared by ESA Board for Software Standardisation and Control (BSSC), 2005.

[FindBugs 2008]
FindBugs. FindBugs Bug Descriptions (2008/2011).

[Flanagan 2005]
Flanagan, David. Java in a Nutshell, Fifth Edition. Sebastopol, CA: O'Reilly Media, 2005.

[Fortify 2013]
Fortify Software Security Research Group with Gary McGraw. A Taxonomy of Coding Errors That Affect Security (see Java/JSP), 2008/2011.

[GNU 2013]
GNU Coding Standards, §5.3, "Clean Use of C Constructs." (GNU Coding Standards were written by Richard Stallman and other GNU Project volunteers.) (2013).

[Goetz 2004]
Goetz, Brian. "Java Theory and Practice: Garbage Collection and Performance: Hints, Tips, and Myths about Writing Garbage Collection-Friendly Classes." IBM developerWorks (2004).

[Goetz 2006]
Goetz, Brian, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, & Doug Lea. Java Concurrency in Practice. Boston, MA: Addison-Wesley, 2006.

[Goetz 2007]
Goetz, Brian. "Java Theory and Practice: Managing Volatility: Guidelines for Using Volatile Variables." IBM developerWorks (2006).

[Gong 2003]
Gong, Li, Gary Ellison, and Mary Dageforde. Inside Java 2 Platform Security: Architecture, API Design, and Implementation, Second Edition. Upper Saddle River, NJ: Prentice Hall, 2003.

[Goodliffe 2006]
Pete Goodliffe. Code Craft: The Practice of Writing Excellent Code. San Francisco: No Starch Press, 2006.

[Grand 2002]
Grand, Mark. Patterns in Java, Vol. 1, Second Edition. New York: Wiley, 2002.

[Grubb 2013]
Penny Grubb, and Armstrong A. Takang. Software Maintenance Concepts and Practice, Second Edition. River Edge, NJ: World Scientific, 2013.

[Guillardoy 2012]
Guillardoy, Esteban (Immunity Products). Java 0-Day Analysis (CVE-2012-4681), August 28, 2012.

[Hatton 1995]
Hatton, Les. Safer C: Developing Software for High-Integrity and Safety-Critical Systems. New York: McGraw-Hill, 1995 (ISBN 0-07-707640-0).

[Hawtin 2006]
Hawtin, Thomas. "[drlvm][kernel_classes] ThreadLocal Vulnerability." MarkMail, 2006.

[Havelund 2010]
Klaus Havelund, and Al Niessner. JPL Coding Standard, Version 1.1, January 25, 2010.

[Hirondelle 2013]
Hirondelle Systems. "Passwords Never Clear in Text," 2013.

[JLS 2011]
Gosling, James, Bill Joy, Guy Steele, Gilad Bracha, & Alex Buckley. Java Language Specification: Java SE 7 Edition. Oracle America, 2011.

[Jovanovic 2006]
Jovanovic, Nenad, Christopher Kruegel, & Engin Kirda. "Pixy: A Static Analysis Tool for Detecting Web Application Vulnerabilities" (short paper). In Proceedings of the 2006 IEEE Symposium on Security and Privacy (S&P'06). Oakland, CA (2006): pp. 258–263.

[JPL 2005]
Arnold, Ken, James Gosling, & David Holmes. The Java™ Programming Language, Fourth Edition. Boston, MA: Addison-Wesley, 2005.

[JVMSpec 1999]
The Java Virtual Machine Specification. Oracle, 1999. http://docs.oracle.com/javase/specs/.

[JVMSpec 2012]
The Java Virtual Machine Specification Java SE 7 Edition. Oracle, 2012.

[Kalinovsky 2004]
Kalinovsky, Alex. Covert Java: Techniques for Decompiling, Patching, and Reverse Engineering. Indianapolis, IN: SAMS, 2004.

[Knoernschild 2001]
Knoernschild, Kirk. JavaDesign: Objects, UML, and Process. Boston, MA: Addison-Wesley, 2001.

[Lea 1999]
Lea, Doug. Concurrent Programming in Java: Design Principles and Patterns, Second Edition. Reading, MA: Addison-Wesley, 1999.

[Lo 2005]
Lo, Chia-Tien Dan, Witawas Srisa-an, and J. Morris Chang. "Security Issues in Garbage Collection." STSC Crosstalk, October (2005).

[Long 2011]
Long, Fred, Dhruv Mohindra, Robert C. Seacord, Dean F. Sutherland, & David Svoboda. The CERT Oracle Secure Coding Standard for Java. Boston, MA: Addison-Wesley, 2011.

[Manion 2013]
Manion, Art. "Anatomy of Java Exploits," CERT/CC Blog, January 15, 2013.

[Martin 1996]
Martin, Robert C. Granularity. The C++ Report 8(10):57–62 (1996).

[McGraw 1999]
McGraw, Gary, and Edward W. Felten. Securing Java: Getting Down to Business with Mobile Code. New York: Wiley, 1999.

[Mettler 2010]
Mettler, Adrian and David Wagner. "Class Properties for Security Review in an Object-Capability Subset of Java." Proceedings of the 5th ACM (2010).

[Miller 2009]
Miller, Alex. "Java™ Platform Concurrency Gotchas." JavaOne Conference, 2009.

[Netzer 1992]
Netzer, Robert H. B., and Barton P. Miller. "What Are Race Conditions? Some Issues and Formalization." ACM Letters on Programming Languages and Systems, 1(1):74–88, 1992.

[Oaks 2001]
Oaks, Scott. Java Security. Sebastopol, CA: O'Reilly, 2001.

[Oracle 2008]
Permissions in the Java™ SE 6 Development Kit (JDK). Oracle, 2008.

[Oracle 2010a]
Java SE 6 HotSpotVirtual Machine Garbage Collection Tuning. Oracle, 2010.

[Oracle 2010b]
New I/O APIs. http://docs.oracle.com/javase/1.5.0/docs/guide/nio/. Oracle, 2010.

[Oracle 2011a]
Java PKI Programmer's Guide. Oracle, 2011.

[Oracle 2011b]
Java™ Platform, Standard Edition 6 Documentation. Oracle, 2006.

[Oracle 2011c]
Package javax.servlet.http. Oracle, 2011. 

[Oracle 2012a]
API for Privileged Blocks. Oracle, 1993/2012.

[Oracle 2012b]
"Reading ASCII Passwords from an InputStream Example," Java Cryptography Architecture (JCA) Reference Guide. Oracle, 2012.

[Oracle 2012c]
Java Platform Standard Edition 7 Documentation. Oracle, 2012.

[Oracle 2013]
"Oracle Security Alert for CVE-2013-0422." Oracle (2013).

[OWASP 2005]
OWASP (Open Web Application Security Project).  A Guide to Building Secure Web Applications and Web Services, 2005.

[OWASP 2008]
OWASP. Open Web Application Security Project Homepage, 2008.

[OWASP 2009]
OWASP. Session Fixation in Java (2009).

[OWASP 2011]
OWASP. Cross-Site Scripting (XSS) (2011).

[OWASP 2012]
OWASP. "Why Add Salt?" Hashing Java (2012).

[Paar 2009]
Paar, Christof, and Jan Pelzl. Understanding Cryptography, A Textbook for Students and Practitioners (companion website contains online cryptography course that covers hash functions). Berlin: Springer, 2009.

[Pistoia 2004]
Pistoia, Marco, Nataraj Nagaratnam, Larry Koved, & Anthony Nadalin. Enterprise Java Security: Building Secure J2EE Applications. Boston, MA: Addison-Wesley, 2004.

[Policy 2002]
Default Policy Implementation and Policy File Syntax, Document revision 1.6. Sun Microsystems/Oracle, 2002/2010.

[Reddy 2000]
Achut Reddy. Java Coding Style Guide (2000).

[Rogue 2000]
Vermeulen, Allan, Scott W. Ambler, Greg Bumgardner, & Eldon Metz. The Elements of Java Style. New York: Cambridge University Press, 2000.

[SCG 2010]
Secure Coding Guidelines for the Java Programming Language, version 4.0. Oracle, 2010.

[Seacord 2008]
Seacord, Robert C. The CERT C Secure Coding Standard. Boston, MA: Addison-Wesley, 2008.

[Seacord 2012]
Seacord, Robert, Dormann, Will, McCurley, James, MIller, Philip, Stoddard, Robert, Svoboda, David, & Welch, Jefferson. Source Code Analysis Laboratory (SCALe) (CMU/SEI-2012-TN-013). Pittsburgh, PA: Software Engineering Institute, Carnegie Mellon University, 2012.

[Seacord 2013]
Seacord, Robert C. Secure Coding in C and C++, Second Edition. Boston, MA: Addison-Wesley, 2013.

[SecuritySpec 2008]
Java Security Architecture Oracle (2008/2010).

[Sen 2007]
Sen, Robi. "Avoid the Dangers of XPath Injection." IBM developerWorks, 2007.

[Sethi 2009]
Sethi, Amit. "Proper Use of Java's SecureRandom." Cigital Justice League Blog, 2009.

[SIGPLAN 2010]
SIGPLAN Workshop on Programming Languages and Analysis for Security (PLAS '10). ACM, Article 7, doi: 10.1145/1814217.1814224 (2010).

[Steinberg 2005]
Steinberg, Daniel H. "Using the Varargs Language Feature." Java Developer Connection Tech Tips, January 4, 2005.

[Sterbenz 2006]
Sterbenz, Andreas, and Charlie Lai. "Secure Coding Antipatterns: Avoiding Vulnerabilities." JavaOne Conference, 2006.

[Sutherland 2010]
Sutherland, Dean F., and William L. Scherlis. "Composable Thread Coloring." In Proceedings of the 15th ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming. New York: ACM, 2010.

[Tools 2011]
JDK Tools and Utilities Specification. Oracle (2011).

[Tutorials 2008]
The Java Tutorials Oracle (2008).

[Unicode 2009]
The Unicode Consortium. The Unicode Standard, Version 5.2.0, defined by The Unicode Standard, Version 5.2. Mountain View, CA: The Unicode Consortium (2009).

[Unicode 2013]
The Unicode Consortium. The Unicode Standard, Version 6.2.0, defined by Unicode 6.2.0. Mountain View, CA: The Unicode Consortium (2013).

[Viega 2005]
Viega, John. CLASP Reference Guide, Volume 1.1. Secure Software, 2005.

[W3C 2003]
"The World Wide Web Security FAQ." World Wide Web Consortium (W3C), 2003.

[Ware 2008]
Ware, Michael S. Writing Secure Java Code: A Taxonomy of Heuristics and an Evaluation of Static Analysis Tools (thesis). James Madison University, 2008.

[White 2003]
White, Tom. "Memoization in Java Using Dynamic Proxy Classes." O'Reilly onJava.com (August 20, 2003).

[Zadegan 2009]
Zadegan, Bryant. "A Lesson on Infinite Loops," (2009).

Location Currently Reads Should Read

Ch. 4, p. 175 (first line of the text)

conditional expressions

condition expressions

Ch. 4, p. 178 (first and fourth lines of the text)

conditional expressions

condition expressions