Quick answer: The Core Java best practices that matter most for freshers are: use clear names, keep methods short, make fields private and final where you can, replace magic values with enums and constants, code to interfaces such as List, return empty collections instead of null, handle exceptions specifically, close resources with try-with-resources and write small tests for your logic.
Code that works is only the first step. These core Java best practices help you write code that a teammate can read, that does not break when you change one line, and that you can explain in an interview without stumbling.
You do not need a big project to use them. A 100-line console app gets better with each habit below. Every example was run on Java 17.
Core Java best practices at a glance
| Area | Do this | Avoid this |
|---|---|---|
| Names | totalMarks, isEligible() |
t, flag, doIt() |
| Methods | One job, about 20 lines or less | A 200-line main |
| Fields | private, and final when possible |
Public fields anyone can change |
| Values | Enums and named constants | Magic numbers and strings |
| Types | List<String> names = new ArrayList<>() |
ArrayList<String> everywhere |
| Nulls | Return an empty list or Optional |
Return null and hope |
| Errors | Catch specific exceptions | catch (Exception e) {} |
| Resources | try-with-resources | Forgetting to close |
| Checking | Small JUnit tests | Only manual testing |
Write code people can read
Name things for what they mean
Java naming conventions are simple, and interviewers expect them:
- Classes:
PascalCasenouns, such asLibraryBook. - Methods and variables:
camelCase, such ascalculateFine()anddaysLate. - Constants:
UPPER_SNAKE_CASE, such asMAX_BOOKS. - Booleans: read like a question, such as
isOverdueorhasPaid.
If you need a comment to explain a variable name, change the name instead.
Keep methods small
A method should do one thing. If you find yourself writing "and" in the method name, such as readAndValidateAndSave(), split it into three. Small methods are easier to test and easier to reuse.
Pro tip: Use your IDE. In IntelliJ IDEA, select a block of code and press Ctrl+Alt+M to extract it into a new method. Then give it a clear name.
Core Java clean code: replace magic values
Here is a fine calculator written the way many beginners write it:
double fine(int days, String type) {
if (type.equals("R")) return days * 2;
if (type.equals("P")) return days * 5;
return 0;
}
What are "R" and "P"? What happens if someone passes "r"? Here is the same logic with an enum, a record and a constant:
import java.util.List;
public class Library {
enum BookType {
REFERENCE(2.0), PREMIUM(5.0);
private final double finePerDay;
BookType(double finePerDay) { this.finePerDay = finePerDay; }
double finePerDay() { return finePerDay; }
}
record Loan(String title, BookType type, int daysLate) {
Loan {
if (daysLate < 0) throw new IllegalArgumentException("daysLate cannot be negative");
}
double fine() { return type.finePerDay() * daysLate; }
}
static final double MAX_FINE = 100.0;
static double totalFine(List<Loan> loans) {
double total = 0;
for (Loan loan : loans) total += loan.fine();
return Math.min(total, MAX_FINE);
}
public static void main(String[] args) {
List<Loan> loans = List.of(
new Loan("Java Basics", BookType.REFERENCE, 3),
new Loan("Spring in Action", BookType.PREMIUM, 4));
System.out.println(loans.get(0));
System.out.println("Total fine: " + totalFine(loans));
}
}
Loan[title=Java Basics, type=REFERENCE, daysLate=3]
Total fine: 26.0
What changed:
- The enum makes wrong values impossible. You cannot pass
"r"by accident, and the rate sits next to the type it belongs to. - The record gives a constructor, getters,
equals,hashCodeandtoStringin one line. The compact constructor checks input once, when the object is created. - The constant
MAX_FINEhas a name, so the rule is clear to the next reader. - The parameter type is
List<Loan>, notArrayList<Loan>, so the method accepts any list.
Core Java guidelines for safer code
Make fields private and final
Mark a field final if it should never change after the constructor. Fewer moving parts means fewer bugs. Expose behaviour through methods, such as withdraw(amount), rather than a public setBalance() that lets anyone skip the rules.
Do not return null for "nothing"
If a search finds no students, return an empty list. If it finds one student or none, return Optional<Student>. The caller can then write findByRoll(101).orElse(null) or .ifPresent(...), and the "nothing found" case cannot be forgotten.
Handle exceptions with a purpose
- Catch the specific exception you expect.
- Handle it where you can do something useful, or let it pass upward.
- Never leave a
catchblock empty. - Throw
IllegalArgumentExceptionearly when a method gets bad input. Failing fast gives a clear message at the right line.
Close resources with try-with-resources
Files, database connections and network streams must be closed. try-with-resources closes them for you, even when an exception is thrown:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class ReadLines {
public static void main(String[] args) throws IOException {
String data = "roll,name\n101,Asha\n102,Vikram";
try (BufferedReader reader = new BufferedReader(new StringReader(data))) {
reader.readLine(); // skip the header
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
System.out.println(parts[1] + " has roll " + parts[0]);
}
}
}
}
Asha has roll 101
Vikram has roll 102
The same pattern works with Files.newBufferedReader(path) and with JDBC Connection objects, which you will use later in the course.
Core Java tips for performance and testing
A few performance habits are worth learning early. The rest can wait until you measure a real problem.
- Join strings in a loop with
StringBuilder, not+. - Pick the right collection:
HashMaporHashSetfor fast lookup,ArrayListfor ordered lists. - Use primitives (
int,long) in heavy loops instead of wrapper types. - Do not optimise code you have not measured.
Then test your logic. A JUnit 5 test for the fine calculator looks like this:
@Test
void fineIsCappedAtMaximum() {
var loan = new Library.Loan("Old Atlas", Library.BookType.PREMIUM, 30);
assertEquals(100.0, Library.totalFine(List.of(loan)));
}
Thirty days at 5 rupees would be 150, so the test proves the cap works. Write three tests for each important method: a normal case, an edge case and a bad input.
Common mistake: Treating these core Java tips as rules to show off. Clean code is about the reader. A three-line program does not need an interface, a factory and a design pattern.
A fresher's clean code checklist
Before you push a project to GitHub, can you say yes to these?
- Every class and method name explains itself.
- No method is longer than one screen.
- Fields are
private, andfinalwhere possible. - There are no magic numbers or strings.
- No
catchblock is empty. - Files and connections are closed with try-with-resources.
- Important logic has at least a few tests.
- The README explains how to run the project. Our guide to writing a good README shows how.
Apply the list to one of our core Java project ideas, and compare your code with the bugs in common core Java mistakes.
In CodeBegun's Java Full Stack with AI course, trainers review project code against habits like these, and placement preparation runs alongside the course. Placement support includes mock interviews, referrals and 5+ interview opportunities through a 60+ company network, subject to the placement policy and eligibility. That means chances to interview, not a promised job. The employer makes the final choice. The Java full stack course guide explains the full syllabus.
Frequently asked questions
What is the first Core Java best practice a fresher should learn?
Clear naming. A variable called totalMarks explains itself, while a variable called t needs a comment. Good names make every other practice easier, and interviewers notice them at once.
Should I use records in Java projects?
Yes, for simple data carriers such as a Student or an OrderLine. A record gives you a constructor, accessors, equals, hashCode and toString in one line. Records need Java 16 or newer.
Is it bad to catch Exception in Java?
Catching Exception everywhere hides real bugs. Catch the specific exception you expect, such as NumberFormatException, and handle it where you can do something useful, like asking for input again.
Do freshers need to write unit tests?
It helps a lot. A few JUnit tests for your core logic show interviewers that you check your own work. Start with three tests per important method: a normal case, an edge case and a bad input.
How do I show clean Java code in my resume projects?
Keep classes small and named after what they do, add a README that explains the design, write a few tests, and keep your Git history readable. Be ready to explain why you made each choice.
Want a trainer to review your Java code line by line? Book a free demo class in our Madhapur, Hyderabad classroom or live online, or see the Java Full Stack with AI course.
