Reviewing Core Java Fundamentals and Common Programming Questions
Course: Core Java Training
Topic: Reviewing Core Java Fundamentals and Common Programming Questions
Course Link: Core Java Training – JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Core Java Fundamentals
Core Java refers to the fundamental concepts and standard libraries used to develop Java applications. It includes Java syntax, variables, data types, operators, control statements, arrays, strings, object-oriented programming, exception handling, collections, file handling, multithreading, and modern Java features such as lambda expressions and streams.
Reviewing Core Java fundamentals helps developers strengthen their programming knowledge, identify gaps in understanding, prepare for technical interviews, and write reliable applications. A strong understanding of these concepts also makes it easier to learn advanced Java technologies and frameworks.
This topic combines essential theory with frequently asked programming questions, practical coding examples, debugging exercises, and interview preparation.
2. Learning Objectives
After completing this revision topic, you will be able to:
- Review Java syntax, variables, data types, and operators.
- Understand conditional statements, loops, arrays, and strings.
- Explain object-oriented programming principles.
- Differentiate classes, objects, constructors, and methods.
- Understand inheritance, polymorphism, abstraction, and encapsulation.
- Work with exceptions, collections, and generics.
- Review functional interfaces, lambda expressions, and streams.
- Solve common Core Java programming questions.
- Identify common programming mistakes and debugging techniques.
- Prepare for Core Java technical interviews.
3. Java Fundamentals: Syntax and Program Structure
Java is a high-level, class-based programming language. Java source code is compiled into bytecode, which can be executed by a compatible Java Virtual Machine (JVM).
Example: First Java Program
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to Core Java");
}
}
Output:
Welcome to Core Java
Explanation of the Program
public is an access modifier.
class Main declares a class named Main.
main() is the standard entry point used to launch a Java application.
String[] args receives command-line arguments.
System.out.println() prints a message and moves to the next line.
Important Java Components
| Component |
Purpose |
| JDK |
Provides development tools, including the Java compiler, and the components needed to develop Java applications. |
| JRE |
Traditionally describes the runtime components needed to run Java applications; modern Java distributions may package these differently. |
| JVM |
Executes Java bytecode and provides runtime services. |
| Java Compiler |
Compiles Java source code into bytecode. |
| Bytecode |
Platform-independent instructions executed by a compatible JVM. |
4. Variables, Data Types, and Operators
Variables store data that a program can use and modify. Java is statically typed, which means a variable's type is known at compile time.
Primitive Data Types
| Data Type |
Typical Use |
Example |
byte |
Small integer values |
byte age = 25; |
short |
Small-range integers |
short count = 1000; |
int |
General integer values |
int salary = 50000; |
long |
Large integer values |
long population = 8000000L; |
float |
Single-precision decimal values |
float price = 12.5f; |
double |
Double-precision decimal values |
double percentage = 85.75; |
char |
Single UTF-16 code unit |
char grade = 'A'; |
boolean |
Logical true or false values |
boolean active = true; |
Reference types include classes, arrays, interfaces, records, and enums. A reference variable can refer to an object or contain null.
Example: Operators
public class Main {
public static void main(String[] args) {
int a = 20;
int b = 6;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
}
}
Output:
26
14
120
3
2
Because both operands in the division are integers, 20 / 6 produces the integer result 3, not a decimal result.
5. Conditional Statements and Loops
Conditional statements allow a program to make decisions, while loops repeat operations until a condition is met or for a specified number of iterations.
Example: Check Whether a Number Is Even or Odd
public class Main {
public static void main(String[] args) {
int number = 17;
if (number % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}
Output:
Odd
Example: Calculate the Sum from 1 to 5
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 15
Loop Types
for: useful when the iteration count or range is known.
while: repeats while a condition remains true.
do-while: executes its body at least once before checking the condition.
- Enhanced
for: iterates over arrays and Iterable collections.
6. Arrays and Strings
Arrays
An array stores a fixed number of elements of the same type. Array indexes start at zero.
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int number : numbers) {
System.out.println(number);
}
}
}
Output:
10
20
30
40
Strings
A String represents a sequence of characters. String objects are immutable, meaning their contents cannot be changed after creation.
public class Main {
public static void main(String[] args) {
String first = "Core";
String second = "Java";
String result = first + " " + second;
System.out.println(result);
System.out.println(result.length());
System.out.println(result.toUpperCase());
}
}
Output:
Core Java
9
CORE JAVA
String vs. StringBuilder
| Feature |
String |
StringBuilder |
| Mutability |
Immutable |
Mutable |
| Modification |
Creates new String objects for changes |
Modifies its internal character sequence |
| Common use |
Fixed text and general string operations |
Repeated string construction |
| Thread safety |
Immutability makes String values safe to share |
Not synchronized for concurrent access |
7. Object-Oriented Programming Fundamentals
Object-oriented programming (OOP) organizes software around classes and objects. Java supports four widely recognized OOP principles: encapsulation, inheritance, polymorphism, and abstraction.
7.1 Classes and Objects
A class defines the data and behavior of objects. An object is an instance of a class.
class Student {
String name;
int age;
void display() {
System.out.println(name + " - " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.name = "Amit";
student.age = 21;
student.display();
}
}
Output:
Amit - 21
7.2 Encapsulation
Encapsulation combines data and behavior in a class and controls access to internal state. Private fields and public methods are common techniques.
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
Keeping the balance private prevents other classes from changing it directly and allows validation within the deposit method.
7.3 Inheritance
Inheritance allows a class to acquire accessible members and behavior from another class. It supports code reuse and specialized class hierarchies.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
7.4 Polymorphism
Polymorphism allows a common interface or parent type to represent different implementations. Method overriding is a major example of runtime polymorphism.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
}
}
Output:
Bark
7.5 Abstraction
Abstraction exposes essential behavior while hiding implementation details. Abstract classes and interfaces are commonly used to achieve abstraction in Java.
8. Constructors, Methods, and the this Keyword
A constructor initializes a new object. A method defines behavior that can be called by other code.
class Employee {
private String name;
private double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
void display() {
System.out.println(name + ": " + salary);
}
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee("Neha", 55000);
employee.display();
}
}
Output:
Neha: 55000.0
The this keyword refers to the current object. It helps distinguish instance variables from constructor or method parameters with the same names.
9. Exception Handling
Exception handling allows a program to respond to errors and unusual conditions without relying entirely on abrupt program termination.
| Keyword |
Purpose |
try |
Encloses code that may throw an exception. |
catch |
Handles a matching exception. |
finally |
Runs during normal or exceptional completion of a try statement, subject to JVM termination and other exceptional circumstances. |
throw |
Explicitly throws an exception or error object. |
throws |
Declares exceptions that a method may propagate. |
Example: Handling Division by Zero
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
Output:
Cannot divide by zero
10. Collections Framework
The Java Collections Framework provides interfaces and implementations for storing and processing groups of objects.
| Collection Type |
Purpose |
Examples |
| List |
Maintains an ordered sequence and permits duplicates. |
ArrayList, LinkedList |
| Set |
Stores unique elements. |
HashSet, TreeSet |
| Queue |
Supports processing elements according to a queue policy. |
PriorityQueue, ArrayDeque |
| Map |
Stores key-value associations. |
HashMap, TreeMap |
Example: Using ArrayList
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("SQL");
for (String language : languages) {
System.out.println(language);
}
}
}
Output:
Java
Python
SQL
11. Common Core Java Programming Questions
Question 1: Reverse a String
Problem: Write a Java program to reverse a string.
public class Main {
public static void main(String[] args) {
String text = "Java";
String reversed = new StringBuilder(text)
.reverse()
.toString();
System.out.println(reversed);
}
}
Output:
avaJ
Explanation: The StringBuilder class provides a reverse() method that reverses the character sequence.
Question 2: Check Whether a Number Is Prime
Problem: Determine whether an integer is a prime number.
public class Main {
public static void main(String[] args) {
int number = 17;
boolean isPrime = number >= 2;
for (int i = 2; i <= number / i; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime ? "Prime" : "Not Prime");
}
}
Output:
Prime
Explanation: Numbers less than 2 are not prime. For other numbers, the program checks potential divisors up to the square root of the number, using division in the loop condition to avoid multiplication overflow.
Question 3: Find the Factorial of a Number
Problem: Calculate the factorial of a non-negative integer.
public class Main {
public static void main(String[] args) {
int number = 5;
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(factorial);
}
}
Output:
120
Explanation: The factorial of 5 is 5 × 4 × 3 × 2 × 1 = 120. A long can hold larger values than an int, but factorial results eventually overflow even a long.
Question 4: Find the Largest Element in an Array
public class Main {
public static void main(String[] args) {
int[] numbers = {12, 45, 7, 89, 34};
int largest = numbers[0];
for (int number : numbers) {
if (number > largest) {
largest = number;
}
}
System.out.println("Largest: " + largest);
}
}
Output:
Largest: 89
Question 5: Check Whether a String Is a Palindrome
A palindrome reads the same forward and backward under the chosen comparison rules.
public class Main {
public static void main(String[] args) {
String text = "madam";
String reversed = new StringBuilder(text)
.reverse()
.toString();
if (text.equals(reversed)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
Output:
Palindrome
Question 6: Swap Two Numbers Using a Temporary Variable
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int temp = a;
a = b;
b = temp;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Output:
a = 20
b = 10
Question 7: Count Vowels in a String
public class Main {
public static void main(String[] args) {
String text = "Core Java";
int count = 0;
for (char ch : text.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) >= 0) {
count++;
}
}
System.out.println("Vowels: " + count);
}
}
Output:
Vowels: 4
Question 8: Remove Duplicate Elements from a List
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueNumbers);
}
}
Output:
[1, 2, 3, 4, 5]
12. Common Core Java Interview Questions
Q1. What is Java?
Java is a class-based, object-oriented programming language designed to run on compatible platforms through the Java Virtual Machine.
Q2. What is the difference between JDK, JRE, and JVM?
The JDK provides development tools and components needed to develop Java applications. The JVM executes Java bytecode. JRE is the traditional term for the runtime environment containing the JVM and supporting libraries; packaging varies across modern Java distributions.
Q3. What is the difference between == and equals()?
For primitive values, == compares values. For references, == checks whether two references point to the same object. The equals() method can compare logical equality when implemented appropriately by a class.
Q4. What is method overloading?
Method overloading occurs when multiple methods in the same class share a name but have different parameter lists. Return type alone cannot distinguish overloaded methods.
Q5. What is method overriding?
Method overriding occurs when a subclass provides an implementation compatible with an inherited instance method, allowing runtime polymorphism.
Q6. What is the difference between an abstract class and an interface?
An abstract class can maintain instance state and define constructors, concrete methods, and abstract methods. An interface defines a contract and can include abstract, default, static, and private methods. A class can extend only one class but can implement multiple interfaces.
Q7. What is the difference between checked and unchecked exceptions?
Checked exceptions are generally checked by the compiler and must be caught or declared where required. Unchecked exceptions are subclasses of RuntimeException and are not subject to that compile-time requirement.
Q8. What is the difference between ArrayList and LinkedList?
ArrayList uses a resizable array and provides efficient indexed access. LinkedList uses linked nodes and can support efficient insertion or removal at known positions, although locating those positions may be costly.
Q9. What is a functional interface?
A functional interface has exactly one distinct abstract method and can serve as the target type for a compatible lambda expression or method reference.
Q10. What is the Stream API?
The Stream API processes data through operations such as filtering, mapping, sorting, and collecting. It supports a declarative style of programming.
Q11. What is the difference between final, finally, and finalize()?
final restricts reassignment, overriding, or inheritance depending on its use. finally is a block used in exception-handling constructs. finalize() is a deprecated object-finalization mechanism and should not be used for resource cleanup.
Q12. What is garbage collection?
Garbage collection reclaims memory occupied by objects that are no longer reachable from live references, according to the JVM's garbage-collection implementation.
13. Debugging and Problem-Solving Techniques
Strong Core Java skills require more than memorizing syntax. Developers should be able to understand program behavior, locate errors, and test different input conditions.
- Read compiler messages: Check the file, line number, and reported error before changing code.
- Verify variable values: Use a debugger or carefully placed output statements.
- Check boundary cases: Test empty arrays, zero, negative values, and minimum or maximum expected inputs.
- Understand exceptions: Identify the cause instead of hiding errors with broad catch blocks.
- Use meaningful names: Clear variable and method names make programs easier to understand.
- Test small components: Verify a method independently before integrating it into a larger application.
- Check collection behavior: Consider duplicate elements, ordering, null values, and mutability.
- Review complexity: Consider time and memory usage for algorithms that process large datasets.
14. Mini Project: Student Result Processing System
Objective: Create a simple Java program that stores student marks, calculates the average, determines the result, and displays the student's information.
Program
public class Main {
public static void main(String[] args) {
String studentName = "Amit";
int[] marks = {80, 75, 90, 85, 70};
int total = 0;
for (int mark : marks) {
total += mark;
}
double average = (double) total / marks.length;
String result = average >= 40 ? "Pass" : "Fail";
System.out.println("Student: " + studentName);
System.out.println("Total Marks: " + total);
System.out.println("Average: " + average);
System.out.println("Result: " + result);
}
}
Output:
Student: Amit
Total Marks: 400
Average: 80.0
Result: Pass
Possible Enhancements
- Store multiple students using an ArrayList.
- Validate marks so that they remain between 0 and 100.
- Calculate grades using conditional statements.
- Sort students by average marks.
- Use a Student class to organize student information.
- Use streams to filter students who pass and collect their names.
- Handle invalid input using exception handling.
15. Revision Checklist
- Understand Java program structure and data types.
- Practice operators, conditional statements, and loops.
- Know how to work with arrays and strings.
- Understand classes, objects, constructors, and methods.
- Revise the four major OOP principles.
- Understand exception handling and common collection types.
- Review functional interfaces, lambda expressions, and streams.
- Practice common number and string programming questions.
- Explain code execution and output clearly.
- Test solutions with boundary cases and invalid inputs.
16. Conclusion
Reviewing Core Java fundamentals is essential for building a strong programming foundation. Concepts such as variables, control statements, arrays, strings, object-oriented programming, exceptions, collections, and streams are frequently used in practical software development.
Solving common programming questions helps strengthen logical thinking, improve debugging skills, and prepare for technical interviews. Regular practice, clear coding habits, and a strong understanding of Java fundamentals will make it easier to develop reliable applications and progress to advanced Java technologies.
Learn Core Java with JustAcademy
Explore the Core Java Training course at JustAcademy to continue developing your Java programming skills.
To learn more about the course, register for a course demo.
Visit the JustAcademy official website for more training programs and learning resources.