1. Compare the features of C++ and Java, highlighting the differences.
Comparison of C++ and Java
Feature C++ Java
Memory Manual (pointers) Automatic (Garbage
Management collection)
Multiple Supports directly Not supported (achieved
Inheritance via interfaces)
Platform Platform-dependent Platform-independent
Dependence (compiled code) (JVM-based)
Compilation Compiles to machine Compiles to bytecode
Model code
Object-Oriented Partial (supports Pure object-oriented
procedural as well)
2. Describe Java tokens in detail, identifying their significance in Java
programming.
Java tokens are the smallest elements of a program recognized by the
compiler. They include:
● Keywords: Reserved words like if, else, class.
● Identifiers: Names of variables, classes, methods.
● Literals: Constants like numbers (123), characters ('A').
● Operators: Symbols like +, -, *.
They form the building blocks of a Java program, enabling the creation
of classes, control structures, and logic.
3. Illustrate the concept of single and double-dimensional arrays in
Java, providing examples to demonstrate their usage.
Feature Single-Dimensional Double-Dimensional Array
Array
Definition A list or sequence of An array of arrays (rows and
elements columns)
Syntax int[] arr = new int[][] arr = new
int[5]; int[3][3];
Storage Linear, stored in a Matrix-like, stored in rows
Structure single row and columns
Element Accessed by a single Accessed by two indices
Access index (arr[0]) (arr[0][1])
Declaration Declared with one Declared with two square
square bracket ([]) brackets ([][])
Usage int[] arr = {1, int[][] matrix = {{1,
Example 2, 3}; 2}, {3, 4}};
Initialization Can be initialized with Requires nested arrays for
one-dimensional initialization
values
Common Used for lists, queues, Used for matrices, tables,
Use Cases stacks grids
Memory Allocates memory for Allocates memory for
Allocation one-dimensional elements in a
elements two-dimensional structure
Complexity Easier to implement Slightly more complex due to
and manage additional indexing
4. Define Java tokens, and classify the four types of tokens with
examples.
Token Type Description Example
Keywords Reserved words with predefined class, int, if,
meanings, used by the Java else
compiler
Identifiers Names assigned to variables, myVar,
classes, methods Employee,
doWork()
Literals Constant values used directly in 123, 'A',
code "Hello", true
Operators Symbols used to perform +, -, *, /, ==, &&
operations on variables and
values
Separators Used to separate tokens or (), {}, [], ;, .
group code sections
Comments Explanatory notes ignored by // This is a
the compiler comment
Whitespace Space, tabs, or line breaks that Space between
improve code readability tokens,
indentation
Punctuation Used for structuring Java syntax ,, ;, ., :
Escape Special characters within string \n (new line), \t
Sequences literals (tab)
Significance Tokens are fundamental building They define the
blocks that structure Java code program's logic
5. Explain type casting in Java, and differentiate between widening
and narrowing type casting using examples.
Feature Default Constructor Parameterized
Constructor
Definition A constructor with no A constructor that takes
parameters parameters
Purpose Used to initialize objects Used to initialize objects
with default values with specific values
Syntax class Dog { Dog() class Dog {
{ } } Dog(String breed) {
this.breed = breed; }
}
Invocation Called automatically Called when specific
when no parameters are arguments are passed
passed
Implicit Provided by Java if no Not provided automatically,
Availability constructor is defined must be defined explicitly
Overloadin Cannot be overloaded Can be overloaded with
g multiple parameter
variations
Use Case Ideal for creating Ideal for objects needing
objects with default specific data upon creation
configurations
Memory Allocates memory for an Allocates memory for an
Allocation object with default object with customized
settings settings
Example Dog dog = new Dog dog = new
Dog(); Dog("Labrador");
Practical Suitable for cases Useful in constructors of
Scenario where default database connections,
initialization suffices configuration
6. Summarize control statements in Java, and demonstrate their use
with examples.
Control statements direct the flow of execution. They include:
● If-else: if (a > b) { ... } else { ... }
● Switch-case: switch (x) { case 1: ... }
● Loops: for, while, do-while
7. Define a statement in Java, and explain the differences between
declaration statements and expression statements with examples.
In Java, a statement is a complete unit of
execution that performs an action, such as
declaring a variable, making a method call, or
controlling the flow of a program. Each statement
ends with a semicolon (;). Statements are the
building blocks of Java code and can be classified
into different types, such as expression
statements, declaration statements, and control
statements.
Examples of statements:
1. Declaration Statement: int x = 5;
2. Expression Statement: x = x + 1;
3. Control Statement: if (x > 5) { x--; }
Statements define the logic flow and behavior of a
program
Declaration Statement: Declares variables.
java
int a;
Expression Statement: Assigns values or performs
operations.
java
a = 5;
8. Illustrate the concept of classes and objects in Java, with an
example.
Java
Aspect Class Object
Definition A blueprint or template to An instance of a class,
define properties and representing a real-world
behavior entity
Purpose Encapsulates data (fields) Holds specific values
and methods (functions) defined by the class
Declaration Declared using class Created using the new
keyword keyword
Memory No memory is allocated Memory is allocated
Allocation until an object is created when an object is
instantiated
Access to Members (fields, methods) Object accesses class
Members are defined within the members via dot notation
class
Example of class Car { } Car myCar = new
Creation Car();
Behavior Defines what actions Objects perform actions
objects of this class can defined by the class
perform
Reusability Can be reused to create Represents a specific
multiple objects instance of a class
Data Holds the structure but no Holds actual data
actual values assigned to fields during
runtime
Example See the example below See the example below
Example: Car Class and Object Creation
java
// Class Definition
class Car {
// Fields
String model;
int year;
// Method
void startEngine() {
System.out.println("Engine started");
}
}
// Object Creation
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car();
// Assigning values to fields
myCar.model = "Tesla Model S";
myCar.year = 2022;
// Accessing methods and fields
System.out.println("Car Model: " +
myCar.model);
System.out.println("Car Year: " +
myCar.year);
myCar.startEngine(); // Output: Engine
started
}
}
Key Points:
● Class: Car defines the blueprint with fields like model and year
and a method startEngine().
● Object: myCar is an object of the Car class.
● Fields: Specific data like "Tesla Model S" and 2022 is assigned
to myCar.
● Methods: The startEngine() method is called using the
myCar object.
9. Differentiate between a default constructor and a parameterized
constructor in Java, and provide examples.
Feature Default Constructor Parameterized
Constructor
Definition A constructor with no A constructor that takes
parameters parameters
Purpose Used to initialize Used to initialize objects
objects with default with specific values
values
Syntax class Dog { Dog() class Dog {
{ } } Dog(String breed) {
this.breed = breed; }
}
Invocation Called automatically Called when specific
when no parameters arguments are passed
are passed
Implicit Provided by Java if no Not provided automatically,
Availability constructor is defined must be defined explicitly
Overloading Cannot be overloaded Can be overloaded with
multiple parameter
variations
Use Case Ideal for creating Ideal for objects needing
objects with default specific data upon creation
configurations
Memory Allocates memory for Allocates memory for an
Allocation an object with default object with customized
settings settings
Example Dog dog = new Dog dog = new
Dog(); Dog("Labrador");
Practical Suitable for cases Useful in constructors of
Scenario where default database connections,
initialization suffices configuration
10. Summarize the concept of inheritance in Java, and classify its
types using examples.
Inheritance enables a class to inherit properties from another class.
java
class Animal { }
class Dog extends Animal { }
● Single: One class inherits from another.
● Multilevel: A chain of inheritance.
11. Classify the types of polymorphism in Java, and demonstrate
examples of compile-time and runtime polymorphism.
Feature Compile-time Runtime Polymorphism
Polymorphism (Method Overriding)
(Method
Overloading)
Definition Multiple methods with Subclass overrides the
the same name but method of the superclass
different signatures
When Resolved during Resolved during runtime
Resolved compilation
Method Methods differ by the Method signatures are the
Signature number or type of same in superclass and
parameters subclass
Inheritance Not required for Requires inheritance
method overloading (subclass and superclass)
Example int add(int a, class Animal { void
int b) / double sound() } class Dog
add(double a, extends Animal { void
double b) sound() }
Static or Static binding Dynamic binding
Dynamic
Performance Faster due to Slower due to runtime
compile-time binding
resolution
Method Use Used when a class Used to provide specific
has methods that implementations of inherited
differ in functionality methods
Common Common in utility Common in
Application methods, constructor subclass-specific behaviors
overloading
Flexibility Offers flexibility by Enables more specialized
allowing multiple object behaviors at runtime
method variations
12. Compare method overloading and method overriding in Java, and
use examples to support your comparison.
Featu Method Method
re Overloading Overriding
Definiti Multiple methods with the Subclass provides a specific
on same name but different implementation of a method in
parameters the superclass
Inheritance No Yes
Required
Binding Static Dynamic (runtime)
(compile-time)
Method Same method name, Same method name and
Signature but different parameter parameter list in superclass
lists and subclass
Return Can have different Must have the same return type
Type return types as the superclass
Access No Cannot reduce the visibility of the
Modifier restriction inherited method
Polymorphism Compile-time Runtime
Type
Example int add(int a, int class Dog extends
b) / double Animal { void sound()
add(double a) }
Use To perform similar tasks with To change behavior of a
Case different input types method in a subclass
Common Utility methods, Inheritance, interface
Application constructors implementation
13. Explain the process of achieving abstraction in Java using abstract
classes and interfaces, supported by examples.
Abstraction in Java is a process of hiding the implementation details
and showing only the essential features of an object. It allows
developers to focus on the what rather than the how of a solution.
Java provides two mechanisms to achieve abstraction: abstract
classes and interfaces.
Abstract Classes
● Definition:
An abstract class in Java is a class that cannot be
instantiated and may contain abstract methods (methods without
a body) as well as non-abstract methods (with an
implementation).
Syntax:
java
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Barks");
}
}
●
● Key Features:
○ Can have both abstract and concrete methods.
○ Can define constructors and maintain state through
instance variables.
○ Can have access modifiers like private, protected,
public.
○ Used when you want to provide partial implementation that
can be shared by subclasses.
Interfaces
● Definition:
An interface in Java is a completely abstract class that
defines a set of methods that implementing classes must
provide. Since Java 8, interfaces can also contain default
methods with a body.
Syntax:
java
interface Animal {
void sound();
default void sleep() {
System.out.println("Sleeping...");
}
}
class Dog implements Animal {
public void sound() {
System.out.println("Barks");
}
}
●
● Key Features:
○ All methods are abstract (prior to Java 8) or can have
default implementations (post Java 8).
○ Interfaces provide full abstraction.
○ No constructors or instance variables allowed.
○ Multiple inheritance through interfaces is possible.
Comparison:
Feature Abstract Class Interface
Methods Can have both abstract All methods are abstract
and non-abstract (except default/static)
methods
Instance Can have instance Cannot have instance
Variables variables variables
Constructors Can have constructors Cannot have
constructors
Multiple Not allowed Supported
Inheritance
Default No Supported since Java 8
Method
Support
Usage Used for sharing partial Used for defining a
implementation contract for multiple
classes
14. Show how encapsulation is implemented in Java, and justify its
importance in object-oriented programming with an example.
Encapsulation is one of the four fundamental concepts of
object-oriented programming (OOP). It refers to the bundling of data
(fields) and methods (functions) that operate on the data into a single
unit, i.e., a class. By making fields private and providing public getter
and setter methods, Java enforces data hiding, thereby protecting the
integrity of the object's state.
Implementation of Encapsulation
Example:
java
public class Employee {
private String name;
private int age;
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age
public void setAge(int age) {
if(age > 0) {
this.age = age;
}
}
}
Key Features of Encapsulation:
1. Data Hiding:
Sensitive data is hidden from unauthorized access by
making fields private.
2. Control Access: You can control how the fields of a class are
accessed and modified using getter and setter methods.
3. Increased Flexibility: By controlling the access to data,
encapsulation allows changes to the internal state of an object
without modifying external code.
4. Security: Encapsulation enhances security by ensuring that only
valid data is assigned to the fields through controlled access.
5. Code Maintainability: Since data is hidden and access is
controlled through methods, modifying code is easier, leading to
better maintainability.
15. Demonstrate the use of this and super keywords in Java, and
assess their functionality through examples.
The this keyword in Java is used to refer to the current instance of
the class. It is primarily used to resolve ambiguity between instance
variables and parameters, call constructors within the same class, and
pass the current object as a parameter.
Example:
java
class Dog {
private String breed;
// Constructor using this to refer to current
object
public Dog(String breed) {
this.breed = breed;
}
public void display() {
System.out.println("Breed: " + this.breed);
}
}
Key Uses of this:
1. To refer to the current class instance variable.
2. To invoke the current class constructor (constructor chaining).
3. To pass the current object as a parameter to a method.
4. To return the current object from a method.
super Keyword
The super keyword is used to refer to the immediate parent class
object. It can be used to access parent class methods, constructors,
and variables.
Example:
java
class Animal {
String color = "white";
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
String color = "brown";
void display() {
System.out.println("Dog color: " + color);
// brown
System.out.println("Animal color: " +
super.color); // white
}
void sound() {
super.sound(); // Calls parent class method
System.out.println("Dog barks");
}
}
Key Uses of super:
1. To refer to the immediate parent class instance variable.
2. To invoke the parent class method.
3. To call the parent class constructor.
4. Used in method overriding to call the parent class method.
16. Categorize the different types of inheritance supported in Java,
and explain how multiple inheritance is achieved through interfaces.
Inheritance is a mechanism where one class acquires the properties
(fields) and behaviors (methods) of another class. Java supports
single inheritance but restricts multiple inheritance of classes to avoid
ambiguity. Multiple inheritance can, however, be achieved using
interfaces.
Types of Inheritance:
1. Single Inheritance:
One class inherits from another.
○ Example: class Dog extends Animal { }
2. Multilevel Inheritance: A class is derived from another derived
class.
○ Example: class Puppy extends Dog { }
3. Hierarchical Inheritance: Multiple classes inherit from one base
class.
○ Example: class Cat extends Animal, class Dog
extends Animal { }
4. Multiple Inheritance (via Interfaces): A class can implement
multiple interfaces.
Example:
java
interface Eater { void eat(); }
interface Sleeper { void sleep(); }
class Animal implements Eater, Sleeper {
public void eat() {
System.out.println("Eating"); }
public void sleep() {
System.out.println("Sleeping"); }
}
Multiple inheritance allows a class to inherit behavior from more than
one parent. While Java doesn’t allow multiple inheritance of classes,
you can implement multiple interfaces to achieve it.
17. Describe the process of memory management in Java, including
memory allocation and garbage collection as handled by the JVM.
Memory management in Java is handled by the JVM (Java Virtual
Machine), which automatically allocates memory to objects and
recycles unused memory through Garbage Collection.
Memory Allocation in Java:
1. Heap Memory:
Used for dynamic memory allocation. Objects and
arrays are allocated in the heap memory.
2. Stack Memory: Stores method call frames, including local
variables and method calls.
3. Method Area: Stores class structures, like metadata, method
data, and constant runtime pool.
4. PC Register and Native Method Stack: Track the execution of
threads and native method calls.
Garbage Collection
Java automatically reclaims memory through the process of Garbage
Collection (GC). The garbage collector removes objects that are no
longer referenced, thus preventing memory leaks.
Key Features of Garbage Collection:
1. Automatic Process: The JVM handles memory deallocation
automatically.
2. No Manual Memory Management: Unlike languages like C++,
developers don’t need to manage memory explicitly.
3. Mark and Sweep: The GC uses algorithms like "Mark and
Sweep" to identify and clear unused objects.
4. Generations: JVM divides heap memory into young, old, and
permanent generations to optimize GC efficiency.
Garbage Collection Example:
java
public class Test {
public static void main(String[] args) {
Test obj = new Test();
obj = null; // Now the object is eligible
for garbage collection
}
}
18. Describe the difference between String and StringBuffer classes in
terms of mutability.
Mutability
Feature String StringBuffer
Mutability Immutable (cannot Mutable (can be modified)
be changed after
creation)
Storage Stored in String Stored in Heap
Pool or Heap
Thread Safety Not thread-safe Thread-safe (synchronized
methods)
Performance Slower for Faster for modifications (no
concatenation (new new object creation)
object created)
Concatenatio Creates new object Modifies the same object
n for each
modification
Memory Inefficient for Efficient for multiple
Efficiency repeated modifications
modifications
Methods for concat() creates append() modifies the
Modification a new String existing StringBuffer
Usage Use when Use when frequent
Scenario immutability is modifications are needed
required
Example String s = StringBuffer sb = new
"Hello"; s = StringBuffer("Hello");
s.concat(" sb.append(" World");
World");
Synchronizati No synchronization Provides synchronization for
on thread safety
19. Develop a small Java program that uses StringTokenizer to split a
sentence into words.
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String sentence = "Java is a powerful
programming language";
// Create a StringTokenizer object to split
the sentence
StringTokenizer tokenizer = new
StringTokenizer(sentence);
// Iterate and print each word
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Key Points:
1. Sentence:The string is "Java is a powerful programming
language."
2. StringTokenizer: Used to split the sentence into words.
3. Delimiters: The default delimiter is space.
4. Token Count: Each word is treated as a token.
5. Loop: hasMoreTokens() checks if there are more words to
process.
6. Word Extraction: nextToken() retrieves the next word from
the sentence.
7. Output: Words are printed one by one.
8. Efficiency: Suitable for simple word splitting without regex.
9. Alternative: split() from String class is another option for
splitting.
10. Thread Safety: StringTokenizer is not thread-safe;
consider alternatives in multi-threaded environments.
20. Define access modifiers in Java and list the four types of access
modifiers available.
Access Modifiers in Java
Access Description Access Scope
Modifier
Public Allows access from any Accessible from any
class other class
Private Restricts access to within Accessible only within
the class the class
Protected Allows access within the Accessible within the
package and subclasses same package and
subclasses
Default If no modifier is specified, Accessible within the
(Package-priv default is same package
ate) package-private
Class Access Public allows class to be Private restricts class
accessed by any class members within the
class
Inheritance Protected used for Private members cannot
Use inheritance be inherited
Encapsulation Private helps Public exposes class
encapsulate class details details
Visibility Public maximizes Protected balances
Control visibility, Private visibility within packages
minimizes it and inheritance
Example public class Dog { protected void
... }, private sound() { ... },
String breed; int age;
Common Use Public for widely Protected for subclass
Case accessible methods, use, Default for internal
Private for internal details package use
21. Explain the difference between built-in packages and user-defined
packages in Java.
Built-in vs. User-defined Packages in Java
Feature Built-in Packages User-defined Packages
Definition Predefined packages Custom packages created by
provided by Java developers
Examples java.util, java.io, com.mycompany.myapp
java.lang
Content Contains standard Java Contains user-defined
classes and interfaces classes, interfaces, and
sub-packages
Accessibili Available by default Must be imported explicitly or
ty created manually
Common Used for common tasks Used for organizing large
Use like input/output, projects into modules
collections, networking
Ease of Easy to use, no need Requires planning and
Use for manual setup design to set up
Maintenan Built-in packages are Developers are responsible
ce maintained by Java for maintaining user-defined
packages
Importing Imported using import Imported using import
java.util.*; com.mycompany.myapp.*
;
Dependenc Managed automatically Managed manually by
ies by the Java runtime developers
environment
Modularity Limited modularity, Enhances project modularity,
used across many specific to the developer's
projects needs
Customizat Cannot be customized Fully customizable based on
ion project requirements
22. Compare the advantages of using public vs. private access
modifiers in object-oriented programming. Which one would you prefer
in designing a library? Justify your choice.
Feature Description
Definition Mechanism to handle runtime errors and ensure
normal program flow
Try-Catch Used to handle exceptions gracefully by catching
Block thrown errors
Finally Block Always executed after try-catch, used for
cleanup tasks
Throw Keyword Used to explicitly throw an exception
Throws Declares exceptions that a method may throw
Keyword
Checked Exceptions that are checked at compile-time
Exceptions
Unchecked Exceptions that are checked at runtime
Exceptions
Custom Developers can create their own exception
Exceptions classes
Hierarchy All exceptions inherit from
java.lang.Exception
Best Practices Use specific exceptions, avoid over-catch, use
finally for cleanup