Core Java Questions
Core Java Questions
1. What is Java?
Java is a high-level, object-oriented, platform-independent programming language
developed by James Gosling and his team at Sun Microsystems (later acquired by
Oracle Corporation). It was released in 1995 and is widely used for building various
types of applications, including web, mobile, enterprise, and desktop applications.
1997: Java 1.1 is released, introducing inner classes and JIT (Just-In-Time)
compiler support.
2004: Java 5 (Java 1.5) is released, introducing major updates like Generics,
Annotations, and Enumerations.
3. What are the features of Java that make it a popular programming language?
Java offers several features that make it a popular programming language:
Security: Java provides a secure runtime environment with features like class
loaders and a security manager.
Pointers: Java does not have pointers, whereas C++ supports them.
Virtual Functions: In Java, all functions are virtual by default, whereas in C++,
virtual functions need to be explicitly defined.
5. Write a simple "Hello Java" program that prints "Hello, World!" to the console.
A simple "Hello Java" program in Java:
javaCopy code
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Set the JAVA_HOME environment variable to point to the JDK installation directory.
Append the bin directory of the JDK to the system's PATH environment
variable.
JDK (Java Development Kit): It is a software development kit that includes all
the tools necessary for developing, debugging, and monitoring Java
applications.
JVM (Java Virtual Machine): It is a virtual machine that executes Java byte
code. It abstracts the hardware and operating system details, providing platform
independence for Java programs.
9. Describe the role and purpose of the Java Virtual Machine (JVM).
Answer: The JVM is a critical component of the Java platform. Its primary role is to
execute Java byte code, which is generated after compiling Java source code. The
JVM abstracts the underlying hardware and operating system, providing a
consistent runtime environment for Java applications across different platforms. It
also handles memory management, garbage collection, and ensures security by
running Java programs in a controlled sandbox environment.
10. What are variables in Java? How are they declared and used?
Answer: Variables in Java are containers used to store data. They are declared with
a data type and can be assigned values that match their data type. Variables can be
of primitive data types (e.g., int, double, char) or reference data types (e.g., objects).
// Using variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
System.out.println("Salary: $" + salary);
}
}
11. Discuss the various data types available in Java with examples.
Answer: Java supports two categories of data types:
Primitive Data Types: byte, short, int, long, float, double, char, boolean.
javaCopy code
public class DataTypesExample {
public static void main(String[] args) {
// Primitive data types
int age = 30;
double salary = 45000.75;
char gender = 'M';
boolean isEmployed = true;
13. Explain different types of operators in Java (arithmetic, logical, bitwise) with
examples.
Java supports different types of operators:
Bitwise Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise
NOT).
Comparison Operators: == (equals), != (not equals), > (greater than), < (less
than), >= (greater than or equal to), <= (less than or equal to).
javaCopy code
public class OperatorsExample {
public static void main(String[] args) {
int a = 10, b = 5;
// Arithmetic Operators
int sum = a + b;
int difference = a - b;
int product = a * b;
int division = a / b;
int modulus = a % b;
// Logical Operators
boolean result1 = (a > b) && (a < 20);
boolean result2 = (a == 10) || (b == 5);
boolean result3 = !(a > 5);
// Bitwise Operators
// Comparison Operators
boolean isEqual = a == b;
boolean isNotEqual = a != b;
boolean isGreater = a > b;
boolean isLess = a < b;
boolean isGreaterOrEqual = a >= b;
boolean isLessOrEqual = a <= b;
// Assignment Operators
int num = 10;
num += 5; // num = num + 5;
num -= 3; // num = num - 3;
num *= 2; // num = num * 2;
num /= 4; // num = num / 4;
num %= 3; // num = num % 3;
}
}
, private ,
public protected : Access modifiers to control access to classes, fields,
and methods.
Java If-else
15. What is the purpose of the if-else statement in Java? Provide an example of
its usage.
The if-else statement allows you to execute different code blocks based on a condition.
It is used for decision-making in Java programs.
javaCopy code
public class IfElseExample {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is non-positive.");
}
}
}
16. Explain the purpose of the switch statement in Java and provide an example.
The switch statement allows you to select one of many code blocks to be executed
based on the value of an expression.
javaCopy code
public class SwitchExample {
public static void main(String[] args) {
int dayOfWeek = 2;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Sunday";
17. What is the purpose of the for loop in Java? Provide an example.
The for loop is used to execute a block of code repeatedly based on a specified
condition.
javaCopy code
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}
18. Explain the purpose of the while loop in Java and provide an example.
he while loop is used to repeatedly execute a block of code as long as a given condition
is true.
javaCopy code
public class WhileLoopExample {
19. Describe the purpose of the do-while loop in Java. Provide an example.
The do-while loop is used to execute a block of code at least once, and then repeatedly
as long as the specified condition is true.
javaCopy code
public class DoWhileLoopExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count <= 5);
}
}
20. What is the purpose of the break statement in Java? Provide an example of its
usage.
The break statement is used to exit from a loop or switch statement prematurely.
javaCopy code
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
javaCopy code
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Iteration " + i);
}
}
}
Java Comments
22. Describe the different types of comments in Java and their purposes.
Java supports three types of comments:
Single-line comments: Used to comment a single line of code. They start with
//.
Multi-line comments: Used to comment multiple lines of code. They start with
/* and end with */.
Java doc comments: Used to generate documentation. They start with /** and
end with */.
/*
* This is a multi-line comment.
* It spans multiple lines.
*/
/**
* This is a Javadoc comment.
* It provides documentation for the code.
*/
}
}
Java Programs
23. Write a Java program to find the sum of all even numbers from 1 to 100.
javaCopy code
public class SumOfEvenNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println("Sum of even numbers from 1 to 100: " + sum);
}
}
JAVA OOPS
Example:
javaCopy code
class Car {
String make;
String model;
void start() {
System.out.println("Starting the car.");
}
}
Example:
javaCopy code
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Corolla";
Example:
javaCopy code
class Student {
String name;
int age;
}
Example:
javaCopy code
class Circle {
double radius;
double calculateArea() {
return Math.PI * radius * radius;
}
}
javaCopy code
class BankAccount {
private double balance;
Example:
javaCopy code
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
Example:
Animal(String type) {
this.type = type;
}
}
Example:
javaCopy code
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
Example:
javaCopy code
class Calculator {
int add(int a, int b) {
return a + b;
}
Example:
javaCopy code
class Car {
String make;
String model;
Example:
Car(String make) {
this.make = make;
}
}
Example:
javaCopy code
class MyClass {
// Default constructor
}
Example:
javaCopy code
class Person {
String name;
Person(String name) {
this.name = name; // 'this' is used to refer to the instance variable
}
}
Example:
javaCopy code
class Animal { }
class Dog extends Animal { }
Example:
javaCopy code
abstract class Shape {
abstract void draw();
}
Example:
javaCopy code
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
void sound() {
System.out.println("Dog barks.");
}
}
Example:
javaCopy code
interface Shape {
void draw();
}
Example:
javaCopy code
interface Constants {
int MAX_COUNT = 100;
}
Example:
javaCopy code
interface Printer {
default void print() {
System.out.println("Printing...");
}
}
Example:
Example:
javaCopy code
interface MathOperation {
static int add(int a, int b) {
return a + b;
}
}
Example:
javaCopy code
class Outer {
int x;
class Inner {
int y;
}
}
javaCopy code
class Outer {
static class Nested {
int x;
}
}
Example:
javaCopy code
class Outer {
void display() {
class Inner {
void show() {
System.out.println("Inside the local inner class.");
}
}
javaCopy code
interface Greeting {
void greet();
}
greeting.greet();
}
}
Example:
javaCopy code
final class MyClass {
// Class implementation
}
Example:
javaCopy code
class Parent {
final void display() {
System.out.println("This method cannot be overridden.");
}
}
Example:
javaCopy code
class Circle {
Example:
javaCopy code
class Counter {
static int count = 0;
Counter() {
count++;
}
}
Example:
javaCopy code
class Person {
String name;
int age;
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
Example:
javaCopy code
class Person {
String name;
int age;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
Example:
javaCopy code
class Person {
String name;
int age;
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
Example:
javaCopy code
class MyClass implements Cloneable {
// Class implementation
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Example:
{
x = 10; // Instance initializer block
}
}
Example:
javaCopy code
class MyClass {
static int x;
static {
x = 5; // Static initializer block
}
}
Example:
javaCopy code
class Parent {
static void display() {
System.out.println("Parent's static method.");
}
}
Example:
javaCopy code
class Outer {
private int x;
class Inner {
void setX(int value) {
x = value; // Accessing the private member of the outer class
}
}
}
Better encapsulation, as the inner class can access private members of the outer
class.
Better readability and maintainability in some cases, as it reduces the scope of the
inner class and avoids naming conflicts.
Ability to implement more elegant designs using design patterns like the Iterator
pattern.