0% found this document useful (0 votes)
2 views

JAVA (1)

The document provides an overview of Java programming concepts, including platform independence, development tools, data types, control statements, and object-oriented principles like method overloading and overriding. It explains the roles of JVM, JRE, and JDK, as well as constructors and the Runnable interface. Additionally, it covers variable scope, looping statements, and the differences between string creation methods.

Uploaded by

vaishnavi.s1569
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA (1)

The document provides an overview of Java programming concepts, including platform independence, development tools, data types, control statements, and object-oriented principles like method overloading and overriding. It explains the roles of JVM, JRE, and JDK, as well as constructors and the Runnable interface. Additionally, it covers variable scope, looping statements, and the differences between string creation methods.

Uploaded by

vaishnavi.s1569
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1) Java is platform-independent and portable.

Justify

ANS:-Java achieves platform independence through its compilation process. When you compile a Java program, the
source code is translated into bytecode, which is a platform-neutral intermediate representation of the program. This
bytecode is not specific to any particular operating system or hardware architecture.

Furthermore, Java utilizes the concept of the Java Virtual Machine (JVM). The bytecode generated during compilation
is executed by the JVM, which is platform-specific. However, the JVM is available for different platforms, including
Windows, macOS, Linux, and others. This allows the same bytecode to run on any device or operating system that
has a compatible JVM installed, without the need for recompilation or modification of the original source code.

2) List out Java development tools and explain any one from it.

ANS:- Java Development Tools

1. JDK (Java Development Kit)

2. JRE (Java Runtime Environment)

3. Eclipse

4. IntelliJ IDEA

5. NetBeans

6. Maven

7. Gradle

8. Ant

9. JUnit

10. Spring Tool Suite

Explanation of One Tool: JDK (Java Development Kit)

The Java Development Kit (JDK) is a core component for developing Java applications. It includes:

- Compiler (javac): Converts Java source code into bytecode.

- JVM (Java Virtual Machine): Runs the compiled bytecode on any platform.

- Java Runtime Environment (JRE): Provides libraries and other resources to run Java applications.

- Debugger: Helps in debugging the code by identifying and fixing errors.

- Additional Tools: Utilities like `javap` (class file disassembler), `javadoc` (documentation generator), and others for
development and testing.

The JDK is essential for writing, compiling, and running Java programs.

3)What is meaning of automatic type conversion?

ANS:-Automatic type conversion means that the programming language automatically changes one data type into
another. For example, in Java, an int can be automatically converted to a double without needing extra code from
the programmer. This helps in making sure that operations between different types work smoothly.

Example in Java

int myInt = 10;

double myDouble = myInt; // Automatic type conversion from int to double


In this example, the int value myInt is automatically converted to a double when assigned to myDouble. This ensures
that the operation is performed without data loss or errors, as double can accommodate the int value.

4)Define the break and continue statements.

ANS:-The break and continue statements are the jump statements that are used to skip some statements inside the
loop or terminate the loop immediately without checking the test expression. These statements can be used inside
any loops such as for, while, do-while loop.

Break:-The break statement in java is used to terminate from the loop immediately. When a break statement is
encountered inside a loop, the loop iteration stops there, and control returns from the loop immediately to the first
statement after the loop. Basically, break statements are used in situations when we are not sure about the actual
number of iteration for the loop, or we want to terminate the loop based on some condition.

Syntax :

break;

Continue:-The continue statement in Java is used to skip the current iteration of a loop. We can use continue
statement inside any types of loops such as for, while, and do-while loop. Basically continue statements are used in
the situations when we want to continue the loop but do not want the remaining statement after the continue
statement.

Syntax:

continue;

5)List the primitive and non-primitive data types used in Java.

ANS:-Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases. Java has two categories in which data types are segregated

Primitive Data Type: Primitive data are only single values and have no special capabilities. There are 8 primitive data
types.such as boolean, char, int, short, byte, long, float, and double

-byte: 8-bit integer, range from -128 to 127.

-short: 16-bit integer, range from -32,768 to 32,767.

-int: 32-bit integer, commonly used, range from -2^31 to 2^31-1.

-long: 64-bit integer, used for large values, range from -2^63 to 2^63-1.

-float: 32-bit floating-point, for single-precision decimal numbers.

-double: 64-bit floating-point, for double-precision decimal numbers.

-char: 16-bit Unicode character, stores a single character/letter.

-boolean: Represents true or false values.


Non-Primitive Data Type or Object Data type: The Reference Data Types will contain a memory address of variable
values because the reference types won’t store the variable value directly in memory such as String, Array, etc.

-String: Represents a sequence of characters, used for text.

-Arrays: Collection of elements of the same type.

-Classes: Blueprints for creating objects, encapsulate data and methods.

-Interfaces: Abstract types used to specify a behavior that classes must implement.

-Enums: Special classes that represent a group of constants (unchangeable variables).


6) Write a Difference between method overloading and method overriding.

ANS:-

Method Overloading Method Overriding

Method overloading is a compile-time polymorphism. Method overriding is a run-time polymorphism.

Method overloading helps to increase the readability of the Method overriding is used to grant the specific implementation of the
program. method which is already provided by its parent class or superclass.

It occurs within the class. It is performed in two classes with inheritance relationships.

Method overloading may or may not require inheritance. Method overriding always needs inheritance.

In method overloading, methods must have the same name In method overriding, methods must have the same name and same
and different signatures. signature.

In method overloading, the return type can or can not be


In method overriding, the return type must be the same or co-variant.
the same, but we just have to change the parameter.

Static binding is being used for overloaded methods. Dynamic binding is being used for overriding methods.

It gives better performance. The reason behind this is that the binding of
Poor Performance due to compile time polymorphism.
overridden methods is being done at runtime.

Private and final methods can be overloaded. Private and final methods can’t be overridden.

The argument list should be different while doing method


The argument list should be the same in method overriding.
overloading.

7) What is a constructor? Explain it with an example. How does it works?

ANS:-In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type
of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one
constructor is called.

EXAMPLE:-

// Java Program to demonstrate

// Constructor

import java.io.*;

// Driver Class

class Geeks {

// Constructor

Geeks()

{
super();

System.out.println("Constructor Called");

// main function

public static void main(String[] args)

Geeks geek = new Geeks();

How a Constructor Works:-

Object Creation: When an object is created using the new keyword, the constructor is called.

Initialization: The constructor initializes the object's fields with the provided values or default values.

8) How to Implement the java.lang.Runnable Interface in java explain with an example?

ANS:-java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be


executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is
no need of subclassing a Thread when a task can be done by overriding only run() method of Runnable.

Implementing the `java.lang.Runnable` Interface

1. Create a Class that Implements `Runnable`:

- Implement the `run()` method with the code you want to execute in a thread.

2. Create a Thread and Start It:

- Pass an instance of your class to a `Thread` object.

- Call the `start()` method on the `Thread` object to begin execution.

Example

```java

// Step 1: Implement the Runnable Interface

class MyRunnable implements Runnable {

@Override

public void run() {

System.out.println("Thread is running");

public class Main {

public static void main(String[] args) {

// Step 2: Create a Thread with MyRunnable and start it


MyRunnable myRunnable = new MyRunnable();

Thread thread = new Thread(myRunnable);

thread.start(); // Output: Thread is running

```

Explanation

1. MyRunnable Class:

- Implements the `Runnable` interface.

- `run()` method prints "Thread is running".

2. Main Class:

- Creates an instance of `MyRunnable`.

- Creates a `Thread` object, passing the `MyRunnable` instance.

- Starts the thread with `thread.start()`, which calls the `run()` method.

9) What is the difference b/w JVM, JRE and JDK?

ANS:- Difference Between JVM, JRE, and JDK

1. JVM (Java Virtual Machine):

- What It Is: A virtual machine that runs Java bytecode.

- Purpose: Executes Java programs, providing platform independence.

- Contains: Just the Java runtime environment for running Java applications.

2. JRE (Java Runtime Environment):

- What It Is: A package that provides the libraries, JVM, and other components to run Java applications.

- Purpose: Allows you to run Java programs.

- Contains: JVM + standard libraries and other files required to run Java applications.

3. JDK (Java Development Kit):

- What It Is: A full-featured software development kit for Java.

- Purpose: Provides tools to develop, compile, and run Java applications.

- Contains: JRE + development tools like the compiler (`javac`), debugger, and other tools.

10) What is the difference between create a string using double quotes and using new operator?

ANS:-Strings are the type of objects that can store the character of values and in Java, every character is stored in 16
bits i,e using UTF 16-bit encoding. A string acts the same as an array of characters in Java. String is an immutable class
which means a constant and cannot be changed once created and if wish to change , we need to create an new
object and even the functionality it provides like toupper, tolower, etc all these return a new object , its not modify
the original object. It is automatically thread safe.
Ways of Creating a String

There are two ways to create a string in Java:

1)String Literal

2)Using new Keyword

Syntax:

<String_Type> <string_variable> = "<sequence_of_string>";

1. String literal

To make Java more memory efficient (because no new objects are created if it exists already in the string constant
pool).

Example:

String demoString = “GeeksforGeeks”;

2. Using new keyword

String s = new String(“Welcome”);

In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal “Welcome” will
be placed in the string constant pool. The variable s will refer to the object in the heap (non-pool)

Example:

String demoString = new String (“GeeksforGeeks”);

11)) List out the various operators use in Java.

ANS:- 1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations.

Operator Description Example


+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b

++ Increment a++ or ++a


-- Decrement a-- or --a

2. Relational Operators

Relational operators are used to compare two values.

Operator Description Example


== Equal to a == b
!= Not equal to a != b
Operator Description Example
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

3. Logical Operators

Logical operators are used to perform logical operations on boolean values.

Operator Description Example


&& Logical AND a && b
` `
! Logical NOT !a

4. Bitwise Operators

Bitwise operators are used to perform operations on individual bits of integer types.

Operator Description Example


& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise Complement ~a
<< Left Shift a << 2
>> Right Shift a >> 2
>>> Unsigned Right Shift a >>> 2

5. Assignment Operators

Assignment operators are used to assign values to variables.

Operator Description Example


= Assignment a = b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
&= Bitwise AND and assign a &= b
` =` Bitwise OR and assign
^= Bitwise XOR and assign a ^= b
<<= Left shift and assign a <<= 2
>>= Right shift and assign a >>= 2
Operator Description Example
>>>= Unsigned right shift and assign a >>>= 2

6. Conditional (Ternary) Operator

The ternary operator is a shorthand for an if-else statement that assigns a value based on a
condition.

Operator Description Example


? : Ternary condition ? value1 : value2

12)How to define a class in Java?

ANS:-A class in Java is a set of objects which shares common characteristics/ behavior and common properties/
attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.To define a class in Java, you use the class keyword followed by the
class name. Within the class definition, you can include fields (variables), methods, constructors, and inner classes.
Each class typically encapsulates related data and behavior.

Properties of Java Classes

Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.

Class does not occupy memory.

Class is a group of variables of different data types and a group of methods.

A Class in Java can contain:

Data member

Method

Constructor

Nested Class

Interface

SYNTAX:-

public class MyClass {

// class members (fields, methods, constructors)

Within the curly braces {}, you can define fields (variables), methods, constructors, and other inner classes.

13)List out the looping statements available in Java. Explain any one with example.

ANS:-Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions
repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the
ways provide similar basic functionality, they differ in their syntax and condition checking time.

1.while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :

while (boolean condition)

loop statements...

2.for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement
consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to
debug structure of looping.

Syntax:

for (initialization condition; testing condition;increment/decrement)

statement(s)

3.do while: do while loop is similar to while loop with only difference that it checks for condition after executing the
statements, and therefore is an example of Exit Control Loop.

Syntax:

do

statements..

while (condition);

For loop Example

public class ForLoopExample {

public static void main(String[] args)

for (int i = 1; i <= 10; i++) {

System.out.println(i); // Print the current value of i

14)Explain the scope of variable.

ANS:-Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers
are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of
function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be
covered under following categories.

Member Variables (Class Level Scope):-These variables must be declared inside class (outside any function). They
can be directly accessed anywhere in class.

Local Variables (Method Level Scope):-Variables declared inside a method have method level scope and can’t be
accessed outside the method.

Block scope:-Block scope refers to the scope of variables declared within a block of code enclosed within curly braces
{}. In Java, blocks can be found within methods, constructors, loops, if statements, and other control structures.

SOME IMPORTANT SCOPE:-

-Variables declared within a block are accessible only within that block and any nested blocks. Once the block
execution completes, the variables -declared within it go out of scope, and their memory is reclaimed.

-In general, a set of curly brackets { } defines a scope.

-In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are
writing or within any curly brackets inside of the curly brackets where the variable was defined.

-Any variable defined in a class outside of any method can be used by all member methods.

-When a method has the same local variable as a member, “this” keyword can be used to reference the current class
variable.

-For a variable to be read after the termination of a loop, It must be declared before the body of the loop.

15)What is the difference between ArrayList and LinkedList?

ANS:-

ArrayList LinkedList

This class uses a dynamic array to store the elements in This class uses a doubly linked list to store the elements in
it. With the introduction of generics, this class supports it. Similar to the ArrayList, this class also supports the
1. the storage of all types of objects. storage of all types of objects.

Manipulating ArrayList takes more time due to the Manipulating LinkedList takes less time compared to
internal implementation. Whenever we remove an ArrayList because, in a doubly-linked list, there is no
element, internally, the array is traversed and the concept of shifting the memory bits. The list is traversed
2. memory bits are shifted. and the reference link is changed.

3. Inefficient memory utilization. Good memory utilization.

4. It can be one, two or multi-dimensional. It can either be single, double or circular LinkedList.

5. Insertion operation is slow. Insertion operation is fast.

This class implements both the List interface and


This class implements a List interface. Therefore, this
the Deque interface. Therefore, it can act as a list and a
acts as a list.
6. deque.

This class works better when the application demands This class works better when the application demands
7. storing the data and accessing it. manipulation of the stored data.
ArrayList LinkedList

Data access and storage is very efficient as it stores the


Data access and storage is slow in LinkedList.
8. elements according to the indexes.

9. Deletion operation is not very efficient. Deletion operation is very efficient.

10. It is used to store only similar types of data. It is used to store any types of data.

11. Less memory is used. More memory is used.

12. This is known as static memory allocation. This is known as dynamic memory allocation.

16)Why java does not support multiple inheritance?

ANS:-Multiple Inheritance is a feature provided by OOPS, it helps us to create a class that can inherit the properties
from more than one parent. Some of the programming languages like C++ can support multiple inheritance but Java
can’t support multiple inheritance.The major reason behind Java’s lack of support for multiple inheritance lies in its
design philosophy of simplicity and clarity over complexity. By disallowing Multiple Inheritance, Java aims to prevent
the ambiguity and complexities that can arise from having multiple parent classes.

Java class can be inherited from only one superclass using the extends keyword. The single inheritance model
ensures a clear hierarchical structure where each class has a single direct superclass and it can facilitate easier code
maintenance and reduce the potential for conflicts.

17)Explain with an example serialization in java.

ANS:-Serialization is a mechanism of converting the state of an object into a byte stream.Serialization in Java is the
process of converting an object into a format that can be easily stored, transmitted, or reconstructed later. This is
done by converting the object into a sequence of bytes. It's commonly used for saving object states to files, sending
objects over networks, or storing them in databases. Java provides built-in support for serialization through the
java.io.Serializable interface, making it easy to serialize and deserialize objects using streams.

EXAMPLE:-

import java.io.*;

class Person implements Serializable {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

public String toString() {

return "Person{" +
"name='" + name + '\'' +

", age=" + age +

'}';

public class SerializationExample {

public static void main(String[] args) {

// Creating a Person object

Person person = new Person("John", 30);

// Serialization

try {

FileOutputStream fileOut = new FileOutputStream("person.ser");

ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(person);

out.close();

fileOut.close();

System.out.println("Person object serialized and saved as person.ser");

} catch (IOException e) {

e.printStackTrace();

18)Write a Program in java to check whether the given number is Armstrong number

ANS:-

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();


scanner.close();

if (isArmstrong(number)) {

System.out.println(number + " is an Armstrong number.");

} else {

System.out.println(number + " is not an Armstrong number.");

// Function to check if a number is an Armstrong number

public static boolean isArmstrong(int number) {

int originalNumber = number;

int sum = 0;

int numberOfDigits = String.valueOf(number).length();

while (number != 0) {

int digit = number % 10;

sum += Math.pow(digit, numberOfDigits);

number /= 10;

return sum == originalNumber;

19)What is inhertance and write various types of inheritance.

ANS:-Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by


which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means
creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields
of that class. In addition, you can add new fields and methods to your current class as well.

Java Inheritance Types

Below are the different types of inheritance which are supported by Java.

1. Single Inheritance

In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base
class for the derived class B.

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as
the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.

3. Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below
image, class A serves as a base class for the derived classes B, C, and D.

4. Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes.
Please note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and B.

5. Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances with
classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid
inheritance.

20) Define method overloading. Define method overriding.

ANS:-Method overloading is a feature in Java that allows a class to have multiple methods with the same name but
with different parameters or argument lists within the same class. The methods must have different parameter types,
different numbers of parameters, or both.

When a method is overloaded, Java determines which version of the method to execute based on the arguments
provided during the method call. This is known as compile-time polymorphism or static polymorphism because the
decision on which method to call is made at compile time.

Method overloading enables developers to define several methods with the same name that perform similar tasks
but operate on different types of data or accept different numbers of parameters, making the code more readable
and flexible.

METHOD OVERRIDING:-

Method overriding in Java refers to the process of providing a new implementation for a method in a subclass that is
already defined in its superclass. When a subclass overrides a method of its superclass, it provides a specific
implementation of that method tailored to the subclass's context.In Java, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already provided by one of its super-
classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and
the same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override
the method in the super-class.

21) What is the meaning of the static keyword?

ANS:-The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share
the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks,
and nested classes. The static keyword belongs to the class than an instance of the class.

22)Differentiate between Classes and Interface.

ANS:-
Class Interface

The keyword used to create a class is “class” The keyword used to create an interface is “interface”

A class can be instantiated i.e., objects of a class can


An Interface cannot be instantiated i.e. objects cannot be created.
be created.

Classes do not support multiple inheritance. The interface supports multiple inheritance.

It can be inherited from another class. It cannot inherit a class.

It can be inherited by a class by using the keyword ‘implements’


It can be inherited by another class using the keyword
and it can be inherited by an interface using the keyword
‘extends’.
‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be declared


using any access specifier(public, private, default, All variables and methods in an interface are declared as public.
protected).

Variables in a class can be static, final, or neither. All variables are static and final.

23) What are the conditions for using super () method.

ANS:-The super() method in Java is used to call the constructor of the superclass from the subclass. It is typically used
in the constructor of the subclass to invoke the constructor of the superclass. Here are the conditions for using the
super() method:

1.Call to superclass constructor: The super() method must be the first statement in the constructor of the subclass.
2.Implicit super constructor call: If the constructor of the subclass does not explicitly call super(), the compiler
inserts a call to the no-argument constructor of the superclass.

3.Explicit super constructor call: If the superclass does not have a no-argument constructor (default constructor), the
subclass constructor must explicitly call one of the superclass constructors using super().

4.Arguments matching: When calling super(), the arguments passed (if any) must match one of the constructors in
the superclass.

5.Superclass constructor chaining: If the superclass constructor calls another constructor within the same class using
this(), the subclass constructor can still use super() to call one of the superclass constructors.

24)Explain Difference between C++ and JAVA.

ANS:-
Java C++

oracle.com/java isocpp.org

C++ was Influenced by Influenced by Ada, ALGOL


Java was Influenced by Ada 83, Pascal, C++, C#, etc. languages.
68, C, ML, Simula, Smalltalk, etc. languages.

Java was influenced to develop BeanShell, C#, Clojure, Groovy, C++ was influenced to develop C99, Java, JS++, Lua,
Hack, J#, Kotlin, PHP, Python, Scala, etc. languages. Perl, PHP, Python, Rust, Seed7, etc. languages.

Platform-independent, Java bytecode works on any operating Platform dependent should be compiled for different
system. platforms.

It can run on any OS hence it is portable. C++ is platform-dependent. Hence it is not portable.

Java is both a Compiled and Interpreted Language. C++ is a Compiled Language.

Memory Management is System Controlled. Memory Management in C++ is Manual.

It doesn’t have Virtual keywords. It has Virtual keywords.

It supports only single inheritance. Multiple inheritances are


It supports both single and multiple Inheritance.
achieved partially using interfaces.

It supports only method overloading and doesn’t allow operator


It supports both method and operator overloading.
overloading.

It has limited support for pointers. It strongly supports pointers.

It doesn’t support direct native library calls but only Java Native It supports direct system library calls, making it
Interfaces. suitable for system-level programming.

Libraries have a wide range of classes for various high-level C++ libraries have comparatively low-level
services. functionalities.

It doesn’t support documentation comments for source


It supports documentation comments (e.g., /.. */) for source code.
code.

C++ doesn’t have built-in support for threads, depends


Java provides built-in support for multithreading.
on third-party threading libraries.

C++ is both a procedural and an object-oriented


Java is only an object-oriented programming language.
programming language.

Java uses the (System class): System.in for input


C++ uses cin for input and cout for output operation.
and System.out for output.

Java doesn’t support the goto Keyword C++ supports the goto keyword.
Java C++

Java doesn’t support Structures and Unions. C++ supports Structures and Unions.

C++ supports both Pass by Value and pass-by-


Java supports only the Pass by Value technique.
reference.

It supports no global scope. It supports both global scope and namespace scope.

It supports manual object management using new and


Automatic object management with garbage collection.
deletes.

Java supports only calls by value. C++ both supports call by value and call by reference.

Java is not so interactive with hardware. C++ is nearer to hardware.

25) Explain with an example why we used super keyword in java?

ANS:-In Java, the super keyword is used to refer to the superclass (parent class) of the current object. It can be used
to access superclass methods, constructors, and fields from within the subclass (child class). One common use case
for the super keyword is to invoke the superclass constructor from the subclass constructor, especially when the
superclass has parameterized constructors.

Here's an example to illustrate why we use the super keyword in Java:

In this example:

•We have a superclass Animal with a parameterized constructor that initializes the color field.

•The subclass Dog extends the Animal class and adds a new field breed.

•In the constructor of Dog, we use super(color) to explicitly call the superclass constructor with the color parameter.

•Inside the display() method of Dog, we use super.display() to call the superclass display() method to print the color
of the dog.

•Then, we print the breed of the dog.

Without the use of the super keyword, the superclass constructor would not be invoked automatically, and the
superclass fields would remain uninitialized. Similarly, without super.display(), only the subclass method would be
called, and the superclass method would be overridden.

Using the super keyword ensures that both superclass and subclass constructors and methods are properly invoked,
allowing for correct initialization and behavior in class hierarchies.

26)List out few important classes and interfaces in collection framework. What is vector class?

ANS:-The Java Collections Framework provides a set of classes and interfaces to represent and manipulate collections
of objects. Some important classes and interfaces in the Java Collections Framework are:

Classes:
1.ArrayList: Implements the List interface using a dynamic array. It allows fast random access and dynamic resizing of
the underlying array.
2.LinkedList: Implements the List interface using a doubly linked list. It provides efficient insertion and deletion
operations at both ends of the list.

3.HashSet: Implements the Set interface using a hash table. It does not allow duplicate elements and provides
constant-time performance for basic operations like add, remove, and contains.

4.TreeSet: Implements the Set interface using a red-black tree. It stores elements in sorted order and provides
efficient operations for range queries.

5.HashMap: Implements the Map interface using a hash table. It stores key-value pairs and provides constant-time
performance for basic operations like put, get, and remove.
6.TreeMap: Implements the Map interface using a red-black tree. It stores key-value pairs in sorted order and
provides efficient operations for range queries.

Interfaces:

1.List: Represents an ordered collection of elements that allows duplicate elements. It defines operations for
accessing, adding, removing, and modifying elements in the list.
2.Set: Represents a collection of unique elements. It does not allow duplicate elements and provides operations for
adding, removing, and testing for the presence of elements.
3.Map: Represents a collection of key-value pairs. It maps keys to values and does not allow duplicate keys. It
provides operations for adding, removing, and retrieving values based on keys.

4.Queue: Represents a collection that supports insertion and removal of elements according to a specific order. It
typically follows the FIFO (First-In-First-Out) or LIFO (Last-In-First-Out) order.

5.Deque: Represents a double-ended queue that supports insertion and removal of elements at both ends. It
extends the Queue interface and provides additional operations for stack-like behavior.

VECTOR:-The Vector class implements a growable array of objects. Vector implements a dynamic array which means
it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.

They are very similar to ArrayList, but Vector is synchronized and has some legacy methods that the collection
framework does not contain.

It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread environment as it is
synchronized, and due to this, it gives a poor performance in adding, searching, deleting, and updating its elements.

The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and throws the
ConcurrentModificationException.

Syntax:

public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable

27)What is wrapper class? Explain Auto boxing and unboxing with example.

ANS:-WRAPPER CLASS:-A Wrapper class in Java is a class whose object wraps or contains primitive data types. When
we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other
words, we can wrap a primitive value into a wrapper class object.They convert primitive data types into objects.
Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by
value).The classes in java.util package handles only objects and hence wrapper classes help in this case also.

Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and
not primitive types.

An object is needed to support synchronization in multithreading.


Advantages of Wrapper Classes:-

-Collections allowed only object data.

-On object data we can call multiple methods compareTo(), equals(), toString()

-Cloning process only objects

-Object data allowed null values.

-Serialization can allow only object data.

1. Autoboxing

The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as
autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.

2. Unboxing

It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding
primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.

28)What is the difference between string and string buffer class?

ANS:-

String StringBuffer

The String class is immutable. The StringBuffer class is mutable.

String is slow and consumes more memory when we concatenate too StringBuffer is fast and consumes less
many strings because every time it creates new instance. memory when we concatenate t strings.

String class overrides the equals() method of Object class. So you can StringBuffer class doesn't override the
compare the contents of two strings by equals() method. equals() method of Object class.

String class is slower while performing concatenation operation. StringBuffer class is faster while performing
concatenation operation.

String class uses String constant pool. StringBuffer uses Heap memory

29)) List out the different types of exception.

ANS:-

30)What is a constructor? What are its special properties?

ANS:-In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.It is a special type of
method which is used to initialize the object.Every time an object is created using the new() keyword, at least one
constructor is called.

1.Same Name as Class: Constructors have the same name as the class in which they are defined. This allows the
compiler to recognize them as constructors and automatically invoke them when objects of the class are created.

2.No Return Type: Constructors do not have a return type, not even void. This is because they are not intended to
return any value; their purpose is to initialize objects.
3.Cannot be Inherited or Overridden: Constructors are not inherited by subclasses and cannot be overridden like
regular methods. Each class in the inheritance hierarchy must define its own constructors.

4.Can Overload: Like other methods, constructors can be overloaded, meaning a class can have multiple constructors
with different parameter lists. This allows for object initialization with different sets of parameters.

5.Implicit Superclass Constructor Call: If a constructor does not explicitly call a superclass constructor using super(),
the compiler inserts a call to the no-argument constructor of the superclass as the first statement in the constructor.

6.Implicit Superclass Constructor Invocation: If a constructor does not explicitly call super() or this(), the compiler
inserts a call to the no-argument constructor of the superclass as the first statement in the constructor.
7.Initialization Block: Constructors can contain initialization blocks (initializer blocks) that are executed before the
constructor body. These blocks are useful for performing common initialization tasks across multiple constructors.

8.Can Access Modifiers: Constructors can have access modifiers like public, private, protected, or default (package-
private), controlling their visibility and accessibility.

9.Initialization of Final Variables: Constructors can initialize final variables. Once initialized, the value of a final
variable cannot be changed.

31) Explain multilevel inheritance program in Java.


ANS:-Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by
which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means
creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields
of that class.

Multilevel Inheritance in Java

Multilevel inheritance in Java refers to a type of inheritance where a class is derived from another class, which is also
derived from another class, creating a chain of inheritance. In other words, it involves more than two levels of
inheritance. This allows the properties and methods of a class to be passed on to multiple levels of subclasses.

Example:-

// Base class

class Animal {

void eat() {

System.out.println("Eating...");

// Derived class from Animal

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

// Derived class from Dog

class Puppy extends Dog {


void weep() {

System.out.println("Weeping...");

public class MultilevelInheritanceExample {

public static void main(String[] args) {

Puppy puppy = new Puppy();

// Calling methods from all three levels of inheritance

puppy.eat(); // Method from Animal class

puppy.bark(); // Method from Dog class

puppy.weep(); // Method from Puppy class

32) Explain the features of JAVA

ANS:- 1.Object oriented:Java is an Object Oriented Programming Language, which supports the construction of
programs that consist of collections of collaborating objects. These objects have a unique identity and have oop
features such as encapsulation, abstraction, Class, inheritance and polymorphism.
2. Simple:Java was designed with a small number of language constructs so that programmers could learn it quickly
which make it simple. It eliminates several language features that were in C/C++ that was associated with poor
programming practices or rarely used such as multiple inheritance, goto statements, header files, structures,
operator overloading, and pointers, security reason was also there for removing or not adding pointer in java.

3. Secure:Java is designed to be more secure in a networked environment. A byte code verification processis used by
the Java run-time environment to ensure that code loaded over the network does not violate Java security
constraints. Absence of pointer also adds on values for java security features.

4. Platform Independent: As we have seen on Introduction page Byte code and JVM which plays the major role for
making the java platform independent and which make it a distinct.

5. Robust:Java is designed to eliminate certain types of programming errors. Java is strongly typed, which allows
extensive compile-time error checking. Its automatic memory management (garbage collection) eliminates memory
leaks and other problems associated with dynamic memory allocation and deallocation. Java does not support
memory pointers, which eliminates the possibility of overwriting memory and corrupting data.

6. Portable:Has usually meant some work when moving an application program to another machine. Recently, the
Java programming language and runtime environment has made it possible to have programs that run on any
operating system and machine that supports the Java standard (from Sun Microsystems) without any porting work.

7. Architecture Neutral:Any system that implements the Java Virtual Machine interprete the Java applications that
are compiled to bytecodes. The Java Virtual Machine is supported by most ofoperating systems, this means that Java
applications are able to run on most platforms.

8. Dynamic:Java supports dynamic loading of classes class loader is responsible for loading the class dynamically in to
JVM.

9. Interpreted:Java source code is compiled to bytecodes, which are interpreted by a Java run-time environment.
10. High Performance:Java is an interpreted language, it was designed to support “just-in-time” compilers, which
dynamically compile bytecodes to machine code.

11. Multithreaded:Java supports multiple threads of execution including a set of synchronization primitives. This
makes programming with threads much easier.

12. Distributed:Java supports various levels of network connectivity. Java applications are network conscious: TCP/IP
support is built into Java class libraries. They have ability to open and access remote objects on the Internet.

33) Briefly explain custom exception.

ANS:-Custom Exception in Java

Custom exceptions in Java are user-defined exceptions that extend the Exception class (for checked exceptions) or
the RuntimeException class (for unchecked exceptions). They allow you to create specific error conditions that are
relevant to your application, making your code more readable and maintainable by providing meaningful error
messages.

Inheritance:Custom exceptions should extend Exception for checked exceptions or RuntimeException for unchecked
exceptions.

Constructors:Define constructors in your custom exception class to pass error messages and other relevant data to
the superclass.

Meaningful Names:Use meaningful class names for custom exceptions to clearly indicate the type of error.

Exception Handling:Handle custom exceptions using try-catch blocks or by declaring them with the throws keyword
in method signatures.

34) Explain about various access specifiers used in Java.

ANS:-in Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It
provides security, accessibility, etc to the user depending upon the access modifier used with the element.Access
specifiers (also known as access modifiers) in Java determine the visibility and accessibility of classes, methods, and
variables. They help in implementing encapsulation by controlling how different parts of the code can access a
particular member or class. Java provides four main access specifiers:

1.Public (public)

Visibility: Accessible from anywhere.

Usage: For methods and variables that need to be accessed from any other class.

2.Private (private)

Visibility: Accessible only within the same class.

Usage: For methods and variables that should not be accessed outside the class.

3.Protected (protected)

Visibility: Accessible within the same package and subclasses (even if they are in different packages).

Usage: For methods and variables that should be accessible in subclasses.

4.Default (no modifier)

Visibility: Accessible only within the same package.

Usage: For methods and variables that should not be accessed outside the package.
35) What is inheritance? Explain different types of inheritance supported by java with an example.

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or
derived class) to inherit properties and behaviors (fields and methods) from an existing class (superclass or base
class). This promotes code reuse and establishes a natural hierarchical relationship between classes.

Types of Inheritance in Java

Java supports the following types of inheritance:

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance

1. Single Inheritance

A subclass inherits from one superclass.

class Animal {

void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat(); // Inherited method

dog.bark(); // Own method

2. Multilevel Inheritance

A class inherits from a superclass, and another class inherits from that subclass, forming a chain.

class Animal {
void eat() {

System.out.println("This animal eats food.");

class Mammal extends Animal {

void walk() {

System.out.println("This mammal walks.");

class Dog extends Mammal {

void bark() {

System.out.println("The dog barks.");

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat(); // Inherited from Animal

dog.walk(); // Inherited from Mammal

dog.bark(); // Own method

3. Hierarchical Inheritance

Multiple subclasses inherit from a single superclass.

class Animal {

void eat() {

System.out.println("This animal eats food.");

}
class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

class Cat extends Animal {

void meow() {

System.out.println("The cat meows.");

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat(); // Inherited from Animal

dog.bark(); // Own method

Cat cat = new Cat();

cat.eat(); // Inherited from Animal

cat.meow(); // Own method

46) Explain the states of a thread.

ANS:-A thread is a process or task in execution. The Java Virtual Machine allows an application to execute multiple
threads concurrently. Such as paint, calculator, Microsoft word or any process running on computer is a thread. Every
thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each
thread which is currently executing may or may not be marked as a daemon. When a new Thread object is created,
the priority of new thread is initially set equal to the priority of the creating thread.A newly created thread is a
daemon thread if and only if the creating thread is a daemon.

-NEW:

Definition: A thread that has been created but not yet started.

Transition: The start() method must be called to move the thread to the RUNNABLE state.

-RUNNABLE:

Definition: A thread that is ready to run or is currently running.


Includes: Threads that are actively executing code or waiting for CPU time.

-BLOCKED:

Definition: A thread that is waiting for a monitor lock to enter a synchronized block/method.

Cause: Occurs when one thread tries to access a synchronized block/method held by another thread.

-WAITING:

Definition: A thread that is waiting indefinitely for another thread to perform a specific action.

Cause: Occurs when calling methods like Object.wait(), Thread.join(), or LockSupport.park() without a timeout.

-TIMED_WAITING:

Definition: A thread that is waiting for another thread to perform a specific action for a specified period.

Cause: Occurs when calling methods like Thread.sleep(), Object.wait(long timeout), or Thread.join(long millis).

-TERMINATED:

Definition: A thread that has finished executing or has been terminated.

Cause: Occurs when the run() method completes normally or the thread is explicitly stopped.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy