Java QB Sol (Module-01)
Java QB Sol (Module-01)
1. List and explain the features of Java language. Or List and explain the JAVA Buzzwords.
Ans:
• Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on
the Object model.
• Architecture-neutral: Java compiler generates an architecture-neutral object file format, which
makes the compiled code executable on many processors, with the presence of Java runtime system.
• Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master
• Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
• Portable: Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability
boundary, which is a POSIX subset.
• Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
• Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform
many tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly
• Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental
and light-weight process.
• High Performance: With the use of Just-In-Time compilers, Java enables high performance.
• Distributed: Java is designed for the distributed environment of the internet.
• Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that can
be used to verify and resolve accesses to objects on run-time.
Robustness in Java:
Java's robustness is mainly achieved through its emphasis on strong typing, exception handling, automatic
memory management (garbage collection), and runtime checking. These features help prevent common
programming errors and make it easier to write reliable and bug-free code. Here are some key points that
contribute to Java's robustness:
a. Strong Typing: Java enforces strict data type checking, ensuring that variables and expressions are used
in a consistent manner. This prevents type-related errors at compile time, reducing the likelihood of runtime
crashes.
b. Exception Handling: Java requires developers to handle exceptions explicitly, making it less prone to
unexpected failures. When an exception occurs, it can be caught, processed, and the program can continue
its execution gracefully.
c. Garbage Collection: Java manages memory automatically through a garbage collector. This feature frees
developers from explicitly deallocating memory, avoiding memory leaks and segmentation faults.
d. Array Bound Checking: Java automatically checks array bounds, preventing buffer overflow errors and
enhancing the overall stability of the code.
e. No Pointers: Java does not have pointer arithmetic, which eliminates the risk of directly accessing
arbitrary memory addresses and further enhances security and stability.
System.out.println("Zzz");
➢ Encapsulation
Encapsulation is the principle of bundling data (attributes) and the methods (functions) that operate
on that data within a single unit, i.e., an object. In Java, encapsulation is achieved through access
modifiers and getter and setter methods.
EX:
package com.javatpoint;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("vijay");
System.out.println(s.getName());
➢ Polymorphism
Polymorphism is the ability of a class to take on multiple forms. In Java, polymorphism is achieved
through method overriding and method overloading.
EX; class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
4. Define Byte code. How does it help the Java program achieve portability? Or How “Compile once and
Run anywhere” is implemented in the Java language
Ans:
Java bytecode is the instruction set for the Java Virtual Machine.
Here's how bytecode helps Java achieve portability:
➢ Platform Independence: Bytecode is not specific to any particular hardware or operating system.
It is designed to be executed by the JVM, which acts as an abstraction layer between the bytecode
and the underlying system. Since the JVM is available for various platforms, the same bytecode
can be executed consistently across different environments without modification.
➢ "Write Once, Run Anywhere" (WORA) Principle: The generation of bytecode and its execution
by the JVM adhere to the "Write Once, Run Anywhere" principle. Once you compile your Java
source code into bytecode, you can distribute the bytecode to any machine with a compatible JVM.
As long as the JVM implementation is correct for that platform, the Java program will run as
expected.
➢ No Need for Re-compilation:With bytecode, you don't need to recompile your Java code for each
target platform. This saves development effort and time, making it easier to deploy and distribute
Java applications.
➢ Consistency in Behavior: Because bytecode is interpreted by the JVM, the behavior of a Java
program remains consistent across different platforms. This eliminates platform-specific quirks and
issues, providing a reliable and predictable execution environment.
➢ Security: Bytecode adds an additional layer of security since it cannot directly access the
underlying system resources. The JVM manages the bytecode execution, providing a controlled
environment for Java programs, reducing the risk of system-level vulnerabilities.
5. List down various operators available in Java and Explain any three with suitable examples.
Ans:
there are several types of operators
Arithmetic Operators: These operators perform basic arithmetic operations.
o Addition (+)
o Subtraction (-)
o Multiplication (*)
o Division (/)
o Modulus (%)
• Relational Operators: These operators compare two values and return a boolean result (true or
false).
o Equal to (==)
o Not equal to (!=)
o Greater than (>)
o Less than (<)
o Greater than or equal to (>=)
o Less than or equal to (<=)
• Logical Operators: These operators are used to perform logical operations and combine boolean
expressions.
o Logical AND (&&)
o Logical OR (||)
o Logical NOT (!)
• Bitwise Operators: These operators perform bit-level manipulation of values.
o Bitwise AND (&)
o Bitwise OR (|)
o Bitwise XOR (^)
o Bitwise NOT (~)
o Left Shift (<<)
o Right Shift (>>)
o Unsigned Right Shift (>>>)
• Assignment Operators: These operators are used to assign values to variables.
o Assignment (=)
o Addition and Assignment (+=)
o Subtraction and Assignment (-=)
o Multiplication and Assignment (*=)
o Division and Assignment (/=)
o Modulus and Assignment (%=)
o Bitwise AND and Assignment (&=)
o Bitwise OR and Assignment (|=)
o Bitwise XOR and Assignment (^=)
o Left Shift and Assignment (<<=)
o Right Shift and Assignment (>>=)
o Unsigned Right Shift and Assignment (>>>=)
• These operators work with a single operand.
o Increment (++)
o Decrement (--)
o Unary Plus (+)
o Unary Minus (-)
o Logical NOT (!)
o Bitwise NOT (~)
den != 0: This condition checks whether the value of 'den' is not equal to zero. If 'den' is zero, it means
that the division 'num/den' will result in an error due to division by zero.
num/den > 2: This condition checks whether the result of the division 'num/den' is greater than 2.
If both conditions are true, the code block inside the if statement will be executed. If either
of the conditions is false, the code block will be skipped.
b. int num, den;
if(den!=0 & num/den>2 )
{}
Ans:
In this snippet, the logical expression is written using the single ampersand "&" operator. This
operator is known as the "bitwise AND" operator. Unlike the "logical AND" operator (&&), the bitwise
AND operator does not short-circuit the evaluation. It evaluates both sides of the expression, regardless of
whether the first condition is true or false.
den != 0: This condition checks whether the value of 'den' is not equal to zero, just like in snippet 'a'.
num/den > 2: This condition checks whether the result of the division 'num/den' is greater than 2, just like
in snippet 'a'.
or
Bitwise operators.
Bitwise operators perform operations on individual bits of integer types (byte, short, int, long) and
are used for low-level bit manipulation. These operators treat the operands as binary numbers and operate
on each corresponding bit.
a. Bitwise AND (&):
The bitwise AND operator (&) performs a bitwise AND operation between the individual bits of
two operands. The result has a 1 in each position where both operands have a 1.
EX;
int a = 5;
int b = 3;
int result = a & b;
System.out.println(result);
b. Bitwise OR (|):
The bitwise OR operator (|) performs a bitwise OR operation between the individual bits of two
operands. The result has a 1 in each position where at least one of the operands has a 1.
EX:
int a = 5;
int b = 3;
int result = a | b;
System.out.println(result);
int result = a ^ b;
System.out.println(result);
8. Explain Type casting. Explain with an example. a. Briefly discuss The Java development tool kit
Or The Java environment Or The JVM.
Ans:
Type casting, also known as type conversion, is the process of changing the data type of a
variable from one type to another. In Java, type casting allows you to convert values between primitive
data types and perform conversions between object types in cases of inheritance or interface
implementations. There are two types of type casting:
The Java Virtual Machine (JVM) is a crucial component of the Java Runtime Environment (JRE) or
Java Development Kit (JDK). It is responsible for executing Java bytecode, which is the compiled form
of Java source code. The JVM provides a platform-independent runtime environment, enabling Java's
"write once, run anywhere" capability.
• Bytecode Execution: The JVM interprets the platform-independent bytecode generated by the
Java compiler or can also use Just-In-Time (JIT) compilation to convert bytecode to machine
code at runtime for improved performance.
• Memory Management: The JVM automatically manages memory allocation and garbage
collection. It tracks objects that are no longer in use and frees up memory to avoid memory
leaks.
• Platform Abstraction: The JVM abstracts the underlying operating system and hardware,
providing a consistent runtime environment for Java applications across different platforms.
• Security: The JVM enforces various security measures to protect the system and ensure that
Java programs run within a secure sandbox environment.
• Class Loading: The JVM dynamically loads Java classes and ensures that class dependencies
are resolved at runtime.
The JVM is available for various platforms, such as Windows, macOS, Linux, etc., enabling Java
programs to be executed on different systems without modification, achieving Java's core principle of
platform independence.
javac HelloWorld.java
The JVM will execute the bytecode in the "HelloWorld.class" file, and you should see the output
"Hello, World!" displayed on the console.
10. Define a class and an object. Mention the difference between them.
Ans:
Class Object
The class has to be declared first and only An object is created many times as per
once. requirement.
Class does not contain any values which Each object has its own values, which are
can be associated with the field. associated with it.
Output:
Name: Vishnu
age: 22
12. What is Polymorphism? List the types of polymorphism and mention the feature provided by Java
to support the types.
Ans:
Polymorphism is a fundamental concept in object-oriented programming that allows
objects to take on multiple forms or behave differently based on their data types or context. It
enables a single interface (method or operator) to represent multiple implementations, providing
flexibility and extensibility in code design.
Types of Polymorphism:
• Method Overloading: In method overloading, multiple methods can have the same
name but different parameter lists (number or type of parameters). The compiler
determines which method to call based on the method signature during compile
time.
• Operator Overloading: Operator overloading allows the same operator to have
different implementations depending on the types of operands involved.
Runtime Polymorphism (Dynamic Polymorphism):
13. How static polymorphism can be achieved in Java. Explain with an example. Or Explain Method
Overloading in Java with a suitable example.
Ans:
Static polymorphism, also known as compile-time polymorphism or method overloading, can
be achieved in Java by using method overloading. Method overloading allows a class to have multiple
methods with the same name but different parameter lists (number or type of parameters). The Java
compiler determines which method to call based on the method signature during compile time.
Static polymorphism allows us to use a single method name for different implementations
based on the method signature, providing a convenient way to perform similar operations with different
types of data without having to use different method names.
14. What are constructors? How constructors are different from Methods of a class.
Ans:
Constructors are special methods in a class that are used to initialize the state (data
members) of objects when they are created. They have the same name as the class and do not have
a return type, not even void. Constructors are automatically called when an object of a class is
created using the "new" keyword. They play a vital role in the object's lifecycle by setting up the
initial values of the object's attributes.
16. Explain with an example how objects can be passed as arguments and how objects can be returned.
Ans:
In Java, objects can be passed as arguments to methods and can also be returned from
methods, allowing for more complex interactions between objects and enabling code reuse. When
an object is passed as an argument, the method can access and modify the object's state. Similarly,
when an object is returned from a method, the calling code can receive and use the object for
further operations.
dataType[] arrayName;
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5]; // Declaring and allocating space for an integer array
of size 5
// Initializing the array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
}
Suppose we have a class called Student that represents students with attributes like name, age, and roll
number:
19. Write a note on Creating and Destroying objects in Java. Or Write a short note on a] Garbage
Collection. b] new and constructor c] and finalize() method.
Ans:
Creating Objects:
• In Java, objects are created using the new keyword, which dynamically allocates memory for
the object at runtime.
• When an object is created, memory is allocated on the heap, and the object's state (data
members) is initialized, either through explicit assignments or by invoking constructors.
• Objects can be created for both built-in data types (e.g., int, double) and user-defined classes
(custom objects).
• Once an object is created, it can be accessed and manipulated through its reference.
Example of creating an object in Java:
}
}
Write a short note on a] Garbage Collection. b] new and constructor c] and finalize() method.
Ans:
a] Garbage Collection (GC):
• Garbage Collection is an automatic memory management feature in Java that helps reclaim
memory occupied by objects that are no longer in use or unreachable. The primary goal of
GC is to free up memory and prevent memory leaks, ensuring efficient memory utilization
in Java programs
• When objects are created using the new keyword, memory is allocated on the heap.
However, objects may become unreachable due to references being lost or variables going
out of scope.
• The Garbage Collector periodically runs in the background, identifying and deallocating
memory occupied by unreachable objects.
• The GC process involves several algorithms, such as Mark and Sweep, Copying, and
Generational, to manage different types of objects and memory regions efficiently.
• As a programmer, you don't need to manually deallocate memory or destroy objects. The
JVM handles the Garbage Collection process internally.
• The System.gc() method can be used to request Garbage Collection, but it does not
guarantee immediate execution of the process.
b] new and Constructor:
• In Java, the new keyword is used to dynamically create objects at runtime. It allocates
memory for the object on the heap and initializes its state (data members) based on the
constructor called during object creation.
• The general syntax for creating an object is
ClassName objectName = new ClassName();.
• The new keyword is followed by the constructor call, which initializes the object's state.
Constructors are special methods with the same name as the class and no return type,
not even void.
• If a class does not explicitly define a constructor, Java provides a default constructor
with no parameters, which initializes the object's attributes with default values (e.g., 0
for integers, null for objects).
• Constructors can be overloaded, allowing a class to have multiple constructors with
different parameter lists, providing flexibility in object initialization.
Example of using new and constructor to create objects in Java:
class Car {
String make;
String model;