UNIT 1: 1Q. Discuss briefly about the Java's lineage and history of Java.
9Q. Explain about the creation and evolution of Java.
Ans: Java’s Lineage : Java is related to C++, which is a direct descendant of C.
Much of the character of Java is inherited from these two languages. From C, Java
derives its syntax. Many of Java’s object-oriented features were influenced by
C++. In fact, several of Java’s defining characteristics come from—or are
responses to—its predecessors. Moreover, the creation of Java was deeply rooted
in the process of refinement and adaptation that has been occurring in computer
programming languages for the past several decades. For these reasons, this section
reviews the sequence of events and forces that led to Java. As you will see, each
innovation in language design was driven by the need to solve a fundamental
problem that the preceding languages could not solve. Java is no exception.
history of Java : the history of java dates back to the early 1990s when a team of
engineers at Sun Microsystems, led by James Gosling, Mike Sheridan, and Patrick
Naughton, began working on a project called "Green." The goal was to create a
programming language for digital devices such as set-top boxes and interactive
television. The team wanted a language that was platform-independent, secure, and
could run on a variety of devices.
1991: The Green project begins at Sun Microsystems.
1994: The team releases the first version of Java, initially known as "Oak." However,
due to trademark issues, the language was later renamed Java, inspired by the coffee
that the team consumed in large quantities.
1995: Java 1.0 is officially released to the public. This version included many
features that are still fundamental to Java, such as the Java Virtual Machine (JVM)
and the concept of "Write Once, Run Anywhere" (WORA).
1996: Sun Microsystems releases Java 1.1, which introduced new features like inner
classes and JavaBeans.
1997: Java 1.2, also known as Java 2, is released. This version included the Swing
GUI toolkit, the Collections Framework, and the Java Naming and Directory
Interface (JNDI).
1998: Sun releases Java 1.3, which added the HotSpot JVM, performance
improvements, and the Java Naming and Directory Interface (JNDI).
2000: Java 2 Platform, Standard Edition (J2SE) 1.3 is released, followed by J2SE
1.4 in 2002, which introduced the assert keyword, regular expressions, and the NIO
(New I/O) package.
2004: Java 5, also known as J2SE 5.0 or Java 1.5, is released. This version
introduced significant language enhancements, including generics, metadata
annotations, and the enhanced for loop.
2006: Java 6 (J2SE 6) is released, featuring improvements such as scripting support
with the inclusion of the Java Compiler API and improvements to the Java Virtual
Machine.
2011: Oracle Corporation acquires Sun Microsystems, becoming the steward of the
Java platform.
2014: Java 8 is released, introducing lambdas, the Stream API, the java.time
package, and other features.
2017: Java 9 is released, featuring the modular system known as Project Jigsaw, the
module system that enables better modularization of Java applications.
2018: Java 10 and Java 11 are released, with Java 11 being a Long-Term Support
(LTS) release.
2019: Oracle announces a new release cadence for Java, with feature releases every
six months. Java 12, 13, and 14 are released.
2021: Java 16 is released, continuing the regular cadence of feature releases.
2Q. List out all the keywords defined in Java and their usage.
Ans: abstract: Used to declare abstract classes and methods. Abstract classes
cannot be instantiated, and abstract methods must be implemented by concrete (non-
abstract) subclasses.
boolean: Represents a boolean data type, which can have values true or false.
break: Used to terminate a loop prematurely. It is also used with switch statements
to exit the switch block.
byte: Represents a byte data type, which is an 8-bit signed two's complement integer.
case: Used within switch statements to define different cases.
catch: Used to catch and handle exceptions in exception handling (try-catch)
blocks.
char: Represents a char data type, which is a 16-bit Unicode character.
class: Declares a class in Java.
continue: Usage: Skips the rest of the loop and continues with the next iteration.
default: Used within switch statements as the default case when none of the other
cases match.
do: Introduces a do-while loop, which executes a block of code at least once and
then repeats based on a boolean expression.
double: Represents a double-precision 64-bit floating-point data type.
else: Used in conditional statements to execute a block of code when the if condition
is false.
enum: Declares an enumerated type, which is a special data type that represents a
set of constants.
3Q. List and describe the Java Buzzwords.
10Q. Mention about Java features.
ANS: Simple: Java aims to be straightforward and easy to understand. It eliminates complex
features and unnecessary complications, making it accessible to a broad range of developers.
Object-Oriented: Java is based on an object-oriented programming paradigm, emphasizing the
use of classes and objects. It promotes code organization, modularity, and reusability.
Distributed: Java provides features that support the development of distributed applications. It
has built-in support for creating networked and distributed computing applications, making it
suitable for building enterprise-level systems.
Multithreaded: Java has built-in support for multithreading, allowing developers to write
programs that can perform multiple tasks concurrently. This is crucial for developing responsive
and efficient applications, particularly in scenarios like user interfaces and server applications.
Dynamic: Java is designed to be adaptable and dynamic, supporting features like
dynamic memory allocation (garbage collection) and dynamic class loading. This
flexibility contributes to better runtime performance and adaptability.
Portable: Java's "Write Once, Run Anywhere" (WORA) philosophy emphasizes
portability. Once a Java program is compiled into bytecode, it can run on any device
with a compatible JVM, regardless of the underlying hardware or operating system.
High Performance: While being platform-independent, Java aims to provide high
performance. Features like Just-In-Time (JIT) compilation contribute to efficient
execution of Java programs.
Robust: Java incorporates strong memory management, exception handling, and
type checking, reducing the likelihood of errors and crashes. This robustness
enhances the reliability of Java applications.
Secure: Java has a strong emphasis on security. It includes features like the
sandboxing of applets, which allows untrusted code to run securely within a
controlled environment. Additionally, Java's runtime environment provides security
measures to protect against unauthorized access and malicious activities.
Integrated: Java supports seamless integration of code and components. It can be
easily integrated with other technologies and applications, making it suitable for
developing complex and interconnected systems.
High-Performance Interpreted: Java is both compiled and interpreted. The source
code is initially compiled into bytecode, which is then interpreted by the JVM. This
combination allows for a balance between performance and platform independence.
4Q. Describe the Flow control constructs in Java with suitable examples.
Ans:
1. Conditional Statements:
a. if Statement: The if statement is used to conditionally execute a block of code.
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
b. if-else Statement: The if-else statement allows for the execution of one block of
code if a condition is true and another block if the condition is false.
int number = -5;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is non-positive.");
}
c. if-else if-else Statement: The if-else if-else statement allows for multiple
conditions to be checked.
int number = 0;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
2. Looping Statements:
a. for Loop: The for loop is used for iterating over a range of values.
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
b. while Loop: The while loop repeatedly executes a block of code as long as a
given condition is true.
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
c. do-while Loop: The do-while loop is similar to the while loop but guarantees that
the block of code is executed at least once, as the condition is checked after the loop
body.
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 3);
5Q. Explain the three OOP Principles
Ans: 1. Encapsulation: Encapsulation is the bundling of data (attributes) and
methods (functions) that operate on the data into a single unit known as a class. It
hides the internal details of how an object operates and exposes only what is
necessary for the outside world to interact with it.
Data Hiding: The internal details of an object are hidden from the outside world.
The internal state of an object is kept private, and access to it is controlled through
methods (getters and setters).
Access Control: Access modifiers (such as private, protected, and public) restrict or
allow access to certain members of a class. This helps in controlling the visibility
and modification of data.
2. Inheritance: Inheritance is a mechanism that allows a new class (subclass or
derived class) to inherit properties and behaviors of an existing class (superclass or
base class). It promotes code reuse and the creation of a hierarchy of classes.
Reusability: Subclasses can reuse the attributes and methods of their superclass,
reducing redundancy in code.
Extensibility: Subclasses can add or override methods of the superclass, allowing
for the extension of functionality.
Polymorphism: Inheritance is closely related to polymorphism, where objects of a
subclass can be treated as objects of the superclass.
3. Polymorphism: Polymorphism allows objects of different classes to be treated as
objects of a common base class. There are two types of polymorphism in OOP:
compile-time (method overloading) and runtime (method overriding).
Compile-time Polymorphism (Method Overloading): Multiple methods with the
same name but different parameter lists can coexist in a class. The appropriate
method is chosen at compile time based on the method signature.
Runtime Polymorphism (Method Overriding): Subclasses can provide a specific
implementation of a method that is already defined in their superclass. The method
in the subclass overrides the method in the superclass.
6Q. What is JDK and how to install JDK?
Ans: For Windows:
( i )Download the JDK:
• Visit the official Oracle website or an OpenJDK distribution to download the
JDK installer for your Windows platform.
• For Oracle JDK: Oracle JDK Downloads
• For OpenJDK: AdoptOpenJDK
( ii )Run the Installer:
• Execute the downloaded installer by double-clicking on it.
• Follow the installation wizard instructions.
• Choose the installation directory and ensure that the "JDK" option is selected
during installation.
( iii )Set Environment Variables (Optional but Recommended):
• After installation, you may need to set the ‘JAVA_HOME’ environment
variable and add the ‘bin’ directory of the JDK to the system's PATH variable.
• To set ‘JAVA_HOME’ :
• Right-click on "This PC" or "Computer" on your desktop or in File Explorer.
• Select "Properties."
• Click on "Advanced system settings" on the left.
• Click the "Environment Variables" button.
• Add a new system variable with the name ‘JAVA_HOME’ and the path to
your JDK installation directory as the value.
• To update the ‘PATH’ variable:
• Append the path to the ‘bin’ directory of the JDK to the end of the existing
‘PATH’ variable.
( iv )Verify Installation:
• Open a command prompt and type ‘java -version' to verify that Java is
installed.
• Similarly, type ‘javac -version’ to verify that the Java compiler is installed.
7Q. How to define, declare and initialize variables and explain typecasting in
Java.
Ans: 1. Defining Variables:
a. Primitive Data Types: Java has several primitive data types for representing
simple values:
int: Integer data type (e.g., 1, 42, -7).
double: Double-precision floating-point data type (e.g., 3.14, -0.5).
char: Character data type (e.g., 'A', 'b', '$').
boolean: Boolean data type (either true or false).
b. Reference Data Types:Java also has reference data types that represent objects:
String: Represents a sequence of characters.
User-defined classes: You can define your own custom classes.
2. Declaring and Initializing Variables:
a. Primitive Types: int age; // Declaration
age = 25; // Initialization
double pi = 3.14; // Declaration and Initialization
char grade = 'A'; // Declaration and Initialization
boolean isJavaFun = true; // Declaration and Initialization
b. Reference Types: String greeting; // Declaration
greeting = "Hello, Java!"; // Initialization
// Custom class (assuming you have a class named MyClass)
MyClass myObject; // Declaration
myObject = new MyClass(); // Initialization
3. Typecasting in Java: Typecasting refers to converting a variable from one data
type to another.
a. Implicit Typecasting:
int intValue = 42;
double doubleValue = intValue; // Implicit casting from int to double
In this example, the int value is implicitly cast to a double because a double can
represent a wider range of values than an int.
b. Explicit Typecasting:
double doubleValue = 3.14;
int intValue = (int) doubleValue; // Explicit casting from double to int
In this example, the double value is explicitly cast to an int. Keep in mind that
explicit casting may result in loss of data if the target type cannot represent the full
range of values of the source type.
8Q. Explain about Arithmetic, relational and logical operators in java.
Ans: 1. Arithmetic Operators: Arithmetic operators are used to perform
mathematical operations on numeric values.
Addition (+): Adds two operands.
int sum = 5 + 3; // Result: 8
Subtraction (-): Subtracts the right operand from the left operand.
int difference = 7 - 4; // Result: 3
Multiplication (*): Multiplies two operands.
int product = 2 * 6; // Result: 12
Division (/): Divides the left operand by the right operand.
double quotient = 10.0 / 3.0; // Result: 3.3333...
2. Relational Operators: Relational operators are used to compare two values
and return a boolean result.
Equal to (==): Checks if the left and right operands are equal.
• int a = 5, b = 7;
• boolean isEqual = (a == b); // Result: false
Not equal to (!=): Checks if the left and right operands are not equal.
• int x = 10, y = 10;
• boolean notEqual = (x != y); // Result: false
Greater than (>): Checks if the left operand is greater than the right operand.
• int m = 8, n = 5;
• boolean greaterThan = (m > n); // Result: true
Less than (<): Checks if the left operand is less than the right operand.
• int p = 3, q = 6;
• boolean lessThan = (p < q); // Result: true
3. Logical Operators: Logical operators are used to perform logical operations on
boolean values.
Logical AND (&&): Returns true if both the left and right operands are true.
• boolean condition1 = true, condition2 = false;
• boolean result = (condition1 && condition2); // Result: false
Logical OR (||): Returns true if at least one of the left or right operands is true.
• boolean condition3 = true, condition4 = false;
• boolean resultOr = (condition3 || condition4); // Result: true
Logical NOT (!): Returns the opposite boolean value of the operand.
• boolean isTrue = true;
• boolean isFalse = !isTrue; // Result: false
11Q. Explain the process of compilation and execution of java program
with an example
Ans: 1. Writing the Java Source Code: Create a text file with a ‘.java’
extension containing the Java source code. For example, let's create a simple
Java program named ‘HelloWorld.java’:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
2. Compiling the Java Source Code: Open a command prompt or terminal
window and navigate to the directory where the Java file is saved.
Use the javac command (Java Compiler) to compile the source code.
javac HelloWorld.java
If there are no syntax errors, the compiler generates a bytecode file with a ‘.class’
extension. In this case, it will create a file named ‘HelloWorld.class’
3. Execution with Java Virtual Machine (JVM): Once the source code is
compiled, you can use the java command to execute the program.
java HelloWorld
• The JVM loads and executes bytecode, producing the o/p: Hello, World!
NOTE: The main method is the entry point for the program, and it is where the
execution begins.
Java source files must have the same name as the public class they contain. In this
example, the source file is named HelloWorld.java, and the public class is
HelloWorld.
The javac command compiles the Java source code into bytecode, and the java
command executes the bytecode using the JVM.
If there are compilation errors, the javac command will display error messages
indicating the issues in the source code.
12Q. Explain about switch statement in java with example.
Ans: The ‘switch’ statement in Java is a control flow statement that allows you to
select a specific branch of code to execute based on the value of an expression. It is
often used as an alternative to a series of ‘if-else if’ statements when you need to
compare a variable against multiple possible values.
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
// additional cases...
default:
// code to be executed if expression doesn't match any case
}
---The expression is evaluated once, and its value is compared with each case value.
---If a match is found, the code associated with that case is executed.
---The break statement is used to exit the switch block. Without a break, execution
would "fall through" to subsequent cases.
---It's important to note that ‘switch’ statements only work with certain types,
including ‘int’, ‘char’, ‘byte’, ‘short’, and ‘String’ (since Java 7). Additionally, each
case label must be a constant expression (literal or final variable).
13Q. Explain in-detail about Abstraction and Encapsulation
Ans: Abstraction: Abstraction is a fundamental concept in object-oriented
programming that involves simplifying complex systems by modeling classes based on the
essential properties and behaviors they share. It allows you to focus on the relevant aspects
of an object while ignoring unnecessary details. Abstraction involves creating abstract
classes and interfaces to define a common structure for a group of related classes.
Abstract Class: An abstract class is a class that cannot be instantiated on its own
and may contain abstract methods (methods without a body) that must be
implemented by its subclasses.
abstract class Shape {
abstract void draw(); // Abstract method
}
Interface: An interface is a collection of abstract methods. Classes can implement
interfaces, providing a contract for the methods they must implement.
interface Drawable {
void draw();
}
Encapsulation: Encapsulation is the bundling of data (attributes) and methods
(functions) that operate on the data into a single unit, known as a class. It restricts
direct access to some of an object's components and prevents the accidental
modification of its internal state. Encapsulation helps in achieving data hiding and
promotes modularity and maintainability.
1.Access Modifiers: Access modifiers (e.g., private, protected, public) control the
visibility of class members (attributes and methods).
2.Data Hiding:
Encapsulation hides the internal details of an object and allows access only through
well-defined interfaces (public methods). Users of the class don't need to know how
the internal attributes are implemented.
3. Setter and Getter Methods:
Encapsulation often involves the use of setter and getter methods to control access
to attributes.
14Q. What are primitive data types in java? Explain.
ANS: In Java, primitive data types are the basic building blocks for representing
simple values such as integers, floating-point numbers, characters, and boolean
values. These data types are not objects and are stored directly in memory, providing
efficiency in terms of both memory usage and performance. Java has eight primitive
data types, categorized into four groups:
1. Integral Data Types:
byte: 8-bit signed integer.
short: 16-bit signed integer.
int: 32-bit signed integer.
long: 64-bit signed integer.
byte myByte = 127;
short myShort = 32000;
int myInt = 2147483647;
long myLong = 9223372036854775807L; // Note the 'L' suffix for long literals
2. Floating-Point Data Types:
float: 32-bit IEEE 754 floating-point.
double: 64-bit IEEE 754 double-precision floating-point.
float myFloat = 3.14f; // Note the 'f' suffix for float literals
double myDouble = 2.71828;
3. Character Data Type: char: 16-bit Unicode character.
char myChar = 'A';
4. Boolean Data Type: boolean: Represents true or false values.
boolean isJavaFun = true;
The range of values for each data type depends on its size and whether it is signed
or unsigned.
15Q. What is an Array.List and explain various types of arrays with examples.
Ans: An array in Java is a data structure that allows you to store multiple values of
the same data type under a single variable name. Arrays provide a way to efficiently
manage and access a collection of elements. Each element in an array is identified
by an index, starting from 0.
Types of Arrays in Java:
Single-Dimensional Array: An array that stores elements in a single line or row.
// Declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements
int firstElement = numbers[0]; // Retrieves the element at index 0 (value: 1)
Multidimensional Array: An array of arrays. Commonly used for representing
matrices.
// Declaration and initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
int value = matrix[1][2]; // Retrieves the element at row 1, column 2 (value: 6)
Jagged Array: An array where the length of each row can be different.
int[][] jaggedArray = { // Declaration and initialization
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
// Accessing elements
int value = jaggedArray[2][1]; // Retrieves the element at row 2, column 1 (value: 7)
Object Array: An array that stores objects of a class or a mix of different object
types.
// Declaration and initialization
Person[] people = new Person[3];
people[0] = new Person("Alice");
people[1] = new Person("Bob");
people[2] = new Person("Charlie");
// Accessing elements
String personName = people[1].getName(); // Retrieves the name of the person at index 1 ("Bob")
Array of Strings: An array that stores strings.
// Declaration and initialization
String[] fruits = {"Apple", "Orange", "Banana"};
// Accessing elements
String fruitName = fruits[2]; // Retrieves the element at index 2 ("Banana")
16Q. Explain about bit-wise operators in java and the order of precedence for
Java operators.
Ans: Bitwise Operators in Java:
Bitwise operators in Java are used to perform operations at the bit level. They
manipulate individual bits of integers, typically int and long types. Here are the
bitwise operators in Java:
Bitwise AND (&): Sets each bit to 1 if both corresponding bits are 1.
int result = 5 & 3; // Binary: 0101 & 0011 = 0001 (Decimal: 1)
Bitwise OR (|): Sets each bit to 1 if at least one corresponding bit is 1.
int result = 5 | 3; // Binary: 0101 | 0011 = 0111 (Decimal: 7)
Bitwise XOR (^): Sets each bit to 1 if only one of the corresponding bits is 1.
int result = 5 ^ 3; // Binary: 0101 ^ 0011 = 0110 (Decimal: 6)
Bitwise NOT (~): Flips each bit. 0 becomes 1, and 1 becomes 0.
int result = ~5; // Binary: ~0101 = 1010 (Decimal: -6 due to two's complement
representation)
Left Shift (<<): Shifts the bits of a number to the left by a specified number of positions,
filling the vacant positions with zeros.
int result = 5 << 2; // Binary: 0101 << 2 = 010100 (Decimal: 20)
Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions.
The vacant positions are filled based on the sign bit (sign-preserving).
int result = 20 >> 2; // Binary: 010100 >> 2 = 0001 (Decimal: 5)
Order of Precedence for Java Operators:
The order of precedence determines the sequence in which operators are evaluated in an
expression. Operators with higher precedence are evaluated before those with lower
precedence. Here's a simplified overview, from highest to lowest precedence:
Postfix Operators: expr++, expr--
Unary Operators: ++expr, --expr, +expr, -expr, ~expr, !expr
Multiplicative Operators: *, /, %
Additive Operators: +, -
Shift Operators: <<, >>, >>>
Relational Operators: <, <=, >, >=, instanceof
Equality Operators: ==, !=
Bitwise AND Operator (&) Bitwise OR Operator (|): Bitwise XOR Operator (^):
Evaluates both sides of the expression.
Logical AND Operator (&&):Evaluates the left operand. If true, evaluates the right
operand.
Logical OR Operator (||):Evaluates the left operand. If false, evaluates the right operand.
Conditional Operator (? :): Evaluates the boolean expression. If true, returns the value
of the left operand; otherwise, returns the value of the right operand.
Assignment Operators: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=
Comma Operator (comma): Evaluates both expressions and returns the value of the
second expression.