Free course ยท Beginner
Java Programming Foundations
What you will learn
- Set up the JDK and an editor, and run a class from the terminal without copying commands you do not understand
- Use types, variables and casting correctly, and know why an int divided by an int loses the decimals
- Write classes with constructors, fields and methods โ the object model interviews start from
- Choose between ArrayList and HashMap for a given job, and say why out loud
- Handle exceptions with try-with-resources instead of letting the program die
- Answer the twenty Java questions fresher interviews repeat, with an example for each
Course curriculum
5 modules ยท 15 lessons ยท a worked example and a practice task in every lesson
Module 1Java from zero3 lessons
Weeks 1โ2 โ the toolchain, types and text. Slow on purpose: everything later is built on these three weeks.
Your first class and the main method
Everything in Java lives inside a class, and a program starts at public static void main(String[] args). The words look strange because they are precise, not decorative.
The lesson
A Java program is a class with a
mainmethod, and the JVM runs that method last โ everything you write is called from somewhere, andmainis where the calling starts.public static void main(String[] args)is a mouthful you can type for a week until it becomes automatic.Compile with
javac Hello.java, which producesHello.class, then runjava Helloโ compile once, run anywhere the JVM exists. That two-step is the reason Java ended up in banks and service companies, and it is the first thing an interviewer asks a fresher to describe.The mistakes are a file name that does not match the public class name, and a forgotten semicolon at the end of a statement. Both produce messages that name the line and the file, so read the first error rather than the tenth โ one mistake in Java often produces a cascade.
public class Hello { public static void main(String[] args) { System.out.println("Hello, Asha"); } } // The file name MUST match the public class: Hello.java // Compile: javac Hello.java Run: java HelloExample A file named Hello.java containing public class Hello with a main method prints one line; rename the file without renaming the class and it will not compile. Java enforces the rule that the public class and the filename agree.
Practice Write, compile with javac and run with java โ not in an IDE โ and then send the same program a command-line argument and print it back.
Types, variables and casting
Java is statically typed: every variable has a type fixed at compile time. That is why Java programs fail at compile time instead of at 3am, and why interviews start with types.
The lesson
Java is statically typed: you declare the type and it does not change.
int,long,double,boolean,charandStringcover fresher work โ note thatStringstarts with a capital, because it is a class and the others are primitives. Declaring the type is what stops a whole class of bugs before they compile.Narrowing needs an explicit cast and loses information:
(int) 9.8gives 9, and integer division is why7 / 2is 3. Widening is automatic and safe. If you need exact money arithmetic, neither is good enough โ useBigDecimal, which is what a service-company interviewer is checking when they ask about double.The mistakes are comparing strings with
==instead of.equals()โ==compares references, which happen to match inside the string pool and fail on text from a file โ and reading a number as a String fromScannerand then doing arithmetic on it.Integer.parseInt()is the bridge.int age = 21; // whole number double marks = 88.5; // decimal boolean placed = false; char grade = 'A'; String name = "Asha"; // a class, not a primitive int rounded = (int) marks; // narrowing CAST drops the decimals String text = Integer.toString(age); int back = Integer.parseInt(text); // text -> numberExample int a = 7; int b = 2; a / b is 3, not 3.5 โ integer division truncates. Write (double) a / b and it becomes 3.5. Knowing this one line separates candidates who have run Java from candidates who have read about it.
Practice Write a small calculator that takes the four operations and prints results as decimals, then check the division case carefully.
Strings and StringBuilder
A String is immutable: every "change" builds a new object. That single fact is behind half the Java questions in a fresher interview.
The lesson
A
Stringin Java is immutable: every method that appears to change it returns a NEW string. That makes strings safe to pass around and it also means concatenating inside a loop builds a new string each round, which is how a fresher program becomes slow on a real file.Use
StringBuilderwhen you are assembling text in a loop โ.append()then.toString()โ and the built-inStringmethods the rest of the time:length,charAt,substring,indexOf,split,replace,trim,toUpperCase, andString.formator%sfor output.equalsIgnoreCaseis what you want for comparing user input.The mistake is
==for string comparison, and the second is string concatenation inside a loop over ten thousand rows. Both are common enough that interviewers ask about them by name, so learn the reason rather than the rule.String s = "Hello"; System.out.println(s.length()); // 5 System.out.println(s.toUpperCase()); // HELLO System.out.println(s.substring(1, 3)); // el System.out.println(s.contains("ell")); // true // Building many Strings in a loop? StringBuilder avoids the copies. StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) sb.append(i).append("-"); System.out.println(sb.toString());Example Concatenating in a loop of 10000 rows creates 10000 discarded Strings; StringBuilder appends into one buffer and is the version to use. equals() compares content, == compares references โ a distinction that shows up in every written test.
Practice Reverse a sentence, count the words and replace one word โ first with String methods, then with StringBuilder, and note the difference in readability.
Module 2Objects and collections3 lessons
Weeks 3โ5 โ the object model and the two collections you will use forever. This is the core of every Java interview.
Classes, objects and constructors
A class is the design and an object is the thing built from it. A constructor is the method that runs when you build one, and it is where you make an object impossible to create in a broken state.
The lesson
A class is the blueprint and an object is the thing built from it:
class Student { String name; int marks; }thenStudent s = new Student(). Fields hold the state, methods hold the behaviour, and a constructor sets the object up so it is never half-built.The four ideas to be able to define out loud: encapsulation (fields private, access through methods), inheritance (
extends, for an is-a relationship), polymorphism (one method name, several implementations) and abstraction (an interface describing what, not how). Service companies test these in the first ten minutes, and a fresher who can give an example from their own project stands out.The mistake is public fields edited from everywhere, which is what makes a small project impossible to change later. Make fields private, add getters and setters where they are actually needed, and pass values through the constructor instead of setting five fields after
new.public class Student { private final String name; private int marks; public Student(String name, int marks) { // constructor this.name = name; this.marks = marks; } public String getName() { return name; } public void addMarks(int extra) { this.marks += extra; } } Student s = new Student("Asha", 72); s.addMarks(6);Example class Student with a constructor Student(String name, int marks) rejects an empty name at the door. A setter that validates later is a weaker design, and interviewers ask which you would pick and why.
Practice Model a Student and a Course: two classes, constructors, private fields, getters, and a method that prints one line per student.
Inheritance, interfaces and why service companies ask
Inheritance shares behaviour from a parent class; an interface is a contract a class promises to keep. "Why is an interface better than an abstract class here?" is a standard first-round question.
The lesson
Inheritance extends a class:
class SavingsAccount extends Accountinherits the fields and methods and can override behaviour. An interface declares what a class can do โinterface Payable { double calculatePay(); }โ and any class implementing it must supply the method, which is how unrelated types join a common contract.In practice interfaces age better than inheritance. A class can implement many interfaces and extend only one, so a design built on interfaces stays changeable. The phrase to remember in an interview: prefer composition and interfaces, use inheritance for genuine is-a relationships.
The mistake is a deep inheritance chain made to reuse three lines of code, which becomes impossible to reason about by the fourth level. Copy the three lines, or move them into a helper. Reuse is not a reason to couple two classes for ever.
interface Payable { double amount(); } abstract class Worker { abstract String role(); } class Intern extends Worker implements Payable { public String role() { return "intern"; } public double amount() { return 15000; } } // Java has no multiple inheritance of CLASSES; interfaces give many types. // Prefer an interface when you only need a capability (Comparable, Runnable).Example A Print interface with one print() method lets three unrelated report classes be stored in one list and printed in a loop. An abstract base class would force them to share a family tree they do not have.
Practice Write one interface, implement it in three classes, store them in a List<Print> and print all three through the interface.
ArrayList, HashMap and choosing between them
ArrayList keeps order and gives you item number n in constant time. HashMap keeps key-value pairs and gives you the value for a key in constant time. Reaching for the wrong one is the most common design mistake in junior code.
The lesson
ArrayList<String>is an ordered list you can grow:.add,.get(i),.size(),.containsโ the workhorse for rows, names and results.HashMap<String, Integer>maps a key to a value with average O(1) lookup and is how you count, group and de-duplicate.The collection to reach for is decided by the question. Ordered, index-based access โ a list. Look up a value by its key โ a map. Unique values only, no counting โ a
HashSet. Sorted output โ aTreeMapor sort the list at the end. Saying which one and why is a standard fresher interview answer, so decide out loud.The mistake is
containsinside a loop over a large list, which is a hidden O(nยฒ), when aHashSetwould make the whole thing one pass. The second is forgetting that a map returnsnullfor a missing key โ usegetOrDefaultinstead of adding one after the fact.List<String> names = new ArrayList<>(); // ordered, indexed names.add("Asha"); names.get(0); // O(1) names.contains("Asha"); // O(n) scan - slow in a loop Map<String, Integer> counts = new HashMap<>(); // keyed lookup counts.put("Pune", counts.getOrDefault("Pune", 0) + 1); counts.get("Pune"); // ~O(1) // Need insertion order? LinkedHashMap. Sorted keys? TreeMap.Example A list of students finds "the student with id 1042" by walking every entry; a HashMap<Integer, Student> answers in one step. With 10 rows it does not matter, with 100000 it decides whether the feature ships.
Practice Store the same 200 records in both structures, find one record in each, and write two lines on which you would use in a program that also needs the records sorted.
Module 3Exceptions, files and the interview set3 lessons
Weeks 6โ8 โ handling failure, reading real data, and rehearsing the questions that decide the outcome.
Exceptions and try-with-resources
Checked exceptions must be handled or declared, unchecked ones are usually bugs. Neither should ever be swallowed with an empty catch block โ that is how a system fails silently.
The lesson
An exception is a failure travelling up the call stack until somebody handles it.
try { โฆ } catch (IOException e) { โฆ } finally { โฆ }is the shape: the risk in the try, the handling in the catch, the clean-up in finally โ andthrow new IllegalArgumentException("age must be positive")is how your own code reports a bad input rather than returning a wrong number.Checked exceptions must be declared or caught, which is why file work in Java looks noisy:
throws IOExceptionon the method, or a catch around it.try-with-resourcesโtry (BufferedReader r = Files.newBufferedReader(path)) { โฆ }โ closes the file for you even when it throws, which is the modern replacement for a finally block.The mistakes are an empty catch block that swallows the error silently, which turns a bug into mysterious missing data, and catching
Exceptioneverywhere so nothing is ever reported precisely. Catch the narrowest type you can, and always do something with it: log it or tell the user.try { int n = Integer.parseInt("abc"); } catch (NumberFormatException e) { System.out.println("Not a number: " + e.getMessage()); } finally { // runs whether or not an exception was thrown } // try-with-resources closes the reader for you, even on error. try (BufferedReader r = new BufferedReader(new FileReader("data.txt"))) { String line; while ((line = r.readLine()) != null) System.out.println(line); } catch (IOException e) { System.out.println("Could not read: " + e.getMessage()); }Example try (BufferedReader r = new BufferedReader(new FileReader(path))) closes the file even when the read throws. Using plain FileReader without try-with-resources leaks a file handle every time.
Practice Read a file, handle a missing filename and a malformed line separately, and print a different message for each. Never leave a catch block empty.
Reading a file and writing a report
Reading a CSV into objects and writing a summary out is the shape of the first task in most enterprise teams. It is also the smallest project that proves you can work in a real codebase.
The lesson
The fresher file task is always the same: read a CSV, do something to each row, write a report.
Files.readAllLines(Path.of("data.csv"))gives you the lines, splitting each on a comma gives you the fields, andFiles.writeStringor aBufferedWriterwrites the output.Write it as three methods โ read, process, write โ and the whole thing becomes testable and explainable in an interview. Handle a missing file with a readable message rather than a stack trace, and skip the blank last line rather than crashing on it, which is what real exports always contain.
The mistakes are hard-coding an absolute path from your own laptop, and using
split(",")on text where a field contains a comma inside quotes. Useline.split(",", -1)so trailing empty fields are kept, and print the first three rows before trusting any of the parsing.Map<String, Integer> totals = new LinkedHashMap<>(); try (BufferedReader r = new BufferedReader(new FileReader("raw.csv"))) { r.readLine(); // skip the header String line; while ((line = r.readLine()) != null) { String[] cells = line.split(","); if (cells.length < 3 || cells[1].isBlank()) continue; totals.merge(cells[1].trim(), Integer.parseInt(cells[2].trim()), Integer::sum); } } try (PrintWriter w = new PrintWriter("report.csv")) { totals.forEach((city, n) -> w.println(city + "," + n)); }Example Reading line by line with split(",") and building a Student per line gives you a list you can total, sort and print โ the same program an MIS team would ask a fresher to write.
Practice Add a malformed line to your CSV on purpose and make the program report the line number and keep going instead of crashing.
The twenty questions fresher interviews repeat
The written round and the technical interview ask the same core set every year: String immutability, equals versus ==, the four pillars, ArrayList versus LinkedList, HashMap internals, and "what happens when an exception is thrown".
The lesson
The same questions come back in almost every fresher Java round, so they are worth answering from memory: the difference between
==and.equals(),ArrayListagainstLinkedList,StringagainstStringBuilder, what a constructor does, method overloading against overriding, the four OOP pillars with your own example, and what aHashMapcollision is.Also in the set: checked against unchecked exceptions,
finalagainstfinally, whymainis static, what the JVM is doing when you runjava Hello, what an interface is for, and a small problem โ reverse a string, count characters, find the second largest in an array โ written in front of them.The mistake is memorising definitions without an example. "Polymorphism is having many forms" scores nothing next to "in my project, one
Notificationinterface had an email and an SMS implementation". Prepare one line of your own for each, and the round stops feeling like a viva.Overload vs override . == vs .equals() . String immutability . ArrayList vs LinkedList vs HashMap . checked vs unchecked exceptions . interface vs abstract class . final vs static . pass-by-value . HashMap internal working . garbage collection . throw vs throws . constructor chaining . Comparable vs Comparator. Answer each in three lines: what it is . why it exists . one code sketch.Example Rehearse each answer out loud with one example from your own code. "I used a HashMap in this project because..." beats a definition every time.
Practice Record yourself answering all twenty in under a minute each, then listen back once and note which answers went vague.
Module 4The standard library, in depth3 lessons
Streams, sorting and dates: the parts of the Java library every fresher interview touches.
Streams: loops that say what they mean
A stream turns a loop into a pipeline: filter, map, sort, collect. It removes the index, the temporary list and the off-by-one, and it reads like the sentence describing the job.
The lesson
Streams are not automatically faster; their value is clarity. Keep them for short pipelines and go back to a loop when the body grows past a step or two.
filter keeps some elements, map changes each one, collect gathers the result, forEach acts - those four cover most of what an interview asks.
List<String> aNames = names.stream() .filter(n -> n.startsWith("A")) .map(String::toUpperCase) .sorted() .collect(Collectors.toList()); int total = students.stream() .filter(s -> s.getMarks() >= 40) .mapToInt(Student::getMarks) .sum();Example names.stream().filter(n -> n.startsWith("A")).sorted().collect(Collectors.toList()) keeps the A-names, in order, in one expression.
Practice Rewrite a loop over students as a stream that keeps the passed ones and prints their names, sorted.
Comparable, Comparator and sorting
Comparable makes a class know its own natural order; Comparator sorts by any rule you like, including several at once. Sorting objects by two fields is a routine task and a routine question.
The lesson
Use Comparable for the one obvious order of the type and Comparator for every other order, so callers choose rather than the class deciding.
Comparator.comparing with method references removes the boilerplate compareTo body that used to make sorting look harder than it is.
class Student implements Comparable<Student> { public int compareTo(Student o) { return Integer.compare(id, o.id); } } students.sort(Comparator.comparing(Student::getMarks) .reversed() .thenComparing(Student::getName));Example students.sort(Comparator.comparing(Student::getMarks).reversed().thenComparing(Student::getName)) sorts by marks descending, then by name.
Practice Sort five students first by marks descending and then by name, using a Comparator chain.
Dates, times and Optional
Java's old Date class is a trap; java.time.LocalDate and LocalDateTime are the ones to use. Optional is the return type that says 'this might be missing' instead of returning null.
The lesson
LocalDate has a date and no time, LocalDateTime adds the time, ZonedDateTime adds the zone - pick the least you need and daylight-saving bugs disappear.
Optional is for return values, not fields or parameters; used in the wrong place it makes code noisier than the null it replaced.
LocalDate today = LocalDate.now(); LocalDate due = today.plusDays(7); long days = ChronoUnit.DAYS.between(today, due); Optional<Student> s = repo.find(42); String name = s.map(Student::getName).orElse("unknown");Example LocalDate.now().plusDays(7) is a week from today; Optional.ofNullable(find(id)).orElseThrow() turns a missing value into a clear failure.
Practice Compute a due date seven days from today, and write a method that returns an Optional instead of null.
Module 5A real program, end to end3 lessons
Structure, test and publish a console application a reviewer can actually run.
A console app with layers
Split the program into a model class, a repository that reads and writes the file, and a menu that talks to the user. Three small pieces are easier to test and to change than one long main.
The lesson
The separation is not ceremony; it is what lets you swap the CSV for a database later without touching the menu, and it is what interviewers probe when they ask how you would structure it.
Keep main thin: parse input, call the service, print the result. A two-hundred-line main is a main nobody can test.
public class Main { public static void main(String[] args) { StudentRepository repo = new CsvStudentRepository("students.csv"); StudentService service = new StudentService(repo); service.toppers(3).forEach(System.out::println); } }Example Main parses the menu choice, StudentService holds the rules, StudentRepository reads the CSV - each class explainable in one sentence.
Practice Restructure your file-reading program into three classes with one job each.
Unit tests with JUnit
A unit test calls one method and checks the result. For a fresher it is proof the code works, and for a team it is the safety net that lets anyone change code without fear.
The lesson
Test the edges, not the middle - an empty list, a single element, a value exactly on a threshold - because that is where bugs live.
A test that never fails is not a test; change the code on purpose, watch it go red, then put it back. That red proves the test does something.
class StudentServiceTest { @Test void averageOfMarks() { var service = new StudentService(new FakeRepo(List.of(70, 80))); assertEquals(75.0, service.average(), 0.001); } @Test void averageOfNothingIsZero() { var service = new StudentService(new FakeRepo(List.of())); assertEquals(0.0, service.average(), 0.001); } }Example assertEquals(75.0, service.average(List.of(70, 80)), 0.001) runs with one command and fails loudly the moment the rule breaks.
Practice Write three JUnit tests for your service: a normal case, an empty input and a boundary value.
Packaging, running and publishing
A jar that runs with java -jar, a README that says how to build it, and a Git repository a reviewer can open - that trio turns 'I know Java' into something someone can check.
The lesson
Interviewers rarely run your code, but the README and the commit history are read. A clean repo with small commits says more about how you work than a resume bullet.
For a bigger project Maven or Gradle is expected; for a first jar the plain javac and jar commands are enough and show you understand what the tool would do for you.
javac -d out $(find src -name '*.java') jar cfe app.jar Main -C out . java -jar app.jar git init && git add . && git commit -m "Console student report" git remote add origin <url> && git push -u origin mainExample javac -d out src/*.java then jar cfe app.jar Main -C out . gives one file; java -jar app.jar runs it anywhere Java is installed.
Practice Build a runnable jar for your console app, write the README, and push it to GitHub.
About Java Programming Foundations
Read, write and debug Java the way a first job asks for it โ classes, collections, exceptions and a small console application you can explain.
Engineering and MCA students, and anyone targeting the mass-hiring drives where Java and SQL are the two skills on the paper. Especially useful if college taught you syntax and never made you build anything.
What you will be able to do at the end
- Set up the JDK and an editor, and run a class from the terminal without copying commands you do not understand
- Use types, variables and casting correctly, and know why an int divided by an int loses the decimals
- Write classes with constructors, fields and methods โ the object model interviews start from
- Choose between ArrayList and HashMap for a given job, and say why out loud
- Handle exceptions with try-with-resources instead of letting the program die
- Answer the twenty Java questions fresher interviews repeat, with an example for each
How the course is structured
3 modules and 9 lessons, arranged so each one ends with something you have built. Every lesson carries a worked example and a practice task โ the practice is the course, the reading is only the setup. Plan for 8 weeks ยท about 6 hours a week.
The full syllabus โ every lesson, its example and its practice task โ is in the Course curriculum below. Nothing is locked and nothing needs an account.
Your weekly routine
- Three 2-hour blocks a week, one of them spent only typing code, not reading.
- Ten minutes on the last session before starting the next one, re-reading your own code.
- One timed written-test practice set every fortnight.
What you will have built by the end
- A student marksheet program โ reads a CSV, computes totals and grades, writes a report
- A small library or inventory manager using classes, an interface and two collection types
- A written answer sheet for the twenty repeating interview questions, each with an example from your own code
Where this leads for a fresher
- Graduate engineer trainee at a services company
- Junior Java developer after a training bootcamp
- Backend or integration roles with Spring in the stack
- Banking and insurance technology teams that run on Java
Titles vary between companies; the evidence does not. A deployed project, a set of queries you can explain, or a case study with real testing behind it is what a fresher interview has to work with.
Frequently asked questions
Java or Python first?
If your target companies put Java on the paper โ the large services firms mostly do โ start with Java. Python is faster to become productive in; Java is faster to get hired into at a services company. Neither is wasted time: the loops, conditions and functions transfer.
Do I need to know data structures and algorithms first?
No. This course teaches the Java you need before DSA makes sense; the Interview DSA Crash Course is the natural next step, and it assumes you can write a loop and a class.
Is this course free?
Yes โ every module, example and practice task is free to read, and the tools on the Career Portal that go with it are free to use.
I never understood object-oriented programming in college. Will this fix it?
It is written for exactly that. Classes are introduced by building two of them, not by defining four pillars first. If you want to know how much of your gap is Java rather than interview skill, the free Career Pulse check scores both.
Not sure which of these you need first? The free Career Pulse check scores your skills, communication and goal clarity in about three minutes and tells you which gap to close first. Take the free check.