Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Que Bank Solve

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Java Que Bank Solve

Que And Ans:-

Unit-1

1) Explain Below Term.


Ans:
i) Byte Code:
Bytecode is computer object code that an interpreter
converts into binary machine code so it can be read by a
computer's hardware processor. The interpreter is typically
implemented as a virtual machine (VM) that translates the
bytecode for the target platform.

ii) JVM:
What is JVM A specification where working of Java Virtual
Machine is specified. But implementation provider is independent
to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
An implementation Its implementation is known as JRE (Java
Runtime Environment). Runtime Instance Whenever you write
java command on the command prompt to run the java class, an
instance of JVM is created.

2) Explain features of Java.


Ans:

In any Java program, the main() method is the starting point from where
compiler starts program execution. So, the compiler needs to call the main()
method.
If the main() is allowed to be non-static, then while calling the main()
method JVM has to instantiate its class.

While instantiating it has to call the constructor of that class, There will be
ambiguity if the constructor of that class takes an argument.

Static method of a class can be called by using the class name only without
creating an object of a class.

The main() method in Java must be declared public, static and void. If any
of these are missing, the Java program will compile but a runtime error will
be thrown.

3) What is java? Explain Object Oriented Programming Concepts in


java.
Ans:
Java is Easy to write
catching.
and more readable and eye

• Java has a concise, cohesive set of features that


makes it easy to learn and use.

• Most of the concepts are drew from C++ thus making


Java learning simpler.

4) Explain Operators in java.


Ans:
What is OOPs in java? OOps in java is to improve code readability and
reusability by defining a Java program efficiently. The main principles of
object-oriented programming are abstraction, encapsulation, inheritance,
and polymorphism. These concepts aim to implement real-world entities in
programs.
5) Explain briefly any 3 data types used in java.
Ans:
Java is a statically-typed programming language, which means that
every variable or expression in Java has a specific data type that is
known at compile-time. Here are three common data types used in
Java:

1. Integer: The Integer data type represents a whole number value


without any decimal points. It is commonly used to store and
manipulate numerical values such as counters, loop indices, and
other mathematical calculations. In Java, integers are represented
using the "int" keyword and can store values ranging from -
2,147,483,648 to 2,147,483,647.
2. Double: The Double data type is used to represent decimal values.
It is commonly used for storing and manipulating floating-point
values such as measurements or other precise calculations that
require decimal points. In Java, doubles are represented using the
"double" keyword and can store values ranging from
approximately 4.9 x 10^-324 to 1.8 x 10^308.
3. Boolean: The Boolean data type represents a logical value that can
be either true or false. It is commonly used in programming to
control the flow of code execution using conditional statements
such as if-else statements, while loops, and for loops. In Java,
Booleans are represented using the "boolean" keyword.

Unit-2

1) Define term:- Constant, Literals and Variable in java.


Ans:
1. Constant: A constant is a variable whose value cannot be changed once
it is defined. In Java, constants are declared using the "final" keyword. They are
often used to define values that should not be changed during program
execution, such as mathematical constants or configuration values.
final double PI = 3.14159;

2. Literal: A literal is a value that is directly used in the program, without being
stored in a variable. In Java, literals can take various forms depending on the
data type they represent, such as integer literals, floating-point literals,
boolean literals, and string literals.
int age = 25; // Integer literal
double price = 29.99; // Floating-point literal
boolean isRaining = true; // Boolean literal
String name = "John"; // String literal

3. Variable: A variable is a named storage location in memory that holds a value


of a specific data type. In Java, variables must be declared with a data type
and a name before they can be used in a program. The value stored in a
variable can be changed during program execution.
int count; // Variable declaration
count = 10; // Variable assignment

2) Define String Class With its all methods.


Ans:
In Java, the String class represents a sequence of characters. Strings
are one of the most commonly used data types in Java, and the String
class provides a rich set of methods for working with strings. Here are
some of the most commonly used methods of the String class:
1. length(): Returns the length of the string.
2. charAt(int index): Returns the character at the specified index.
3. substring(int beginIndex): Returns a substring of the string starting
from the specified index.
4. substring(int beginIndex, int endIndex): Returns a substring of the
string starting from the specified begin index and ending at the
specified end index (exclusive).
5. concat(String str): Concatenates the specified string to the end of
the current string.
6. indexOf(String str): Returns the index of the first occurrence of the
specified string in the current string.
7. equalsIgnoreCase(String str): Returns true if the current string is equal
to the specified string, ignoring case.
8. toUpperCase(): Returns a new string with all characters in upper case.
9. toLowerCase(): Returns a new string with all characters in lower case.
10. trim(): Returns a new string with leading and trailing white
space removed.

3) What is Array? Explain different Type of array With example.


Ans:
Array:- An array is a data structure that contains a group of elements.
Typically these elements are all of the same data type, such as an integer or
string. Arrays are commonly used in computer programs to organize data so
that a related set of values can be easily sorted or searched.

Arrays can of following types:

1. One dimensional (1-D) arrays or Linear arrays


2. Multi dimensional arrays
(a) Two dimensional (2-D) arrays or Matrix arrays
(b) Three dimensional arrays

4) What is Conditional statement? Explain any two With example.


Ans:
In programming, a conditional statement is a construct that allows
you to execute different code blocks based on whether a certain
condition is true or false. In Java, there are two types of conditional
statements: if statements and switch statements.
1. if statement: The if statement is used to execute a block of code if
a certain condition is true. Here's an example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}
2. if-else statement: The if-else statement is used to execute one
block of code if a certain condition is true, and a different block of
code if the condition is false. Here's an example:
int x = 3;
if (x % 2 == 0) {
System.out.println("x is even");
} else {
System.out.println("x is odd");
}

5) What is loop Statement? Explain any two with example.


Ans:
A loop statement is a programming construct that allows you to execute a
block of code multiple times based on a certain condition.

There are different types of loop statements,

• such as for loop,


• while loop,
• and do-while loop

• A for loop is a loop that runs for a preset number of times.It has three
parts: an initialization, a condition, and an update. For example:

// This for loop prints the numbers from 1 to 10


for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}

• A while loop is a loop that repeats as long as an expression is true. It


has only one part: a condition. For example:

// This while loop prints "Hello" until the user enters 'q'
char input;
while (input != 'q') {
printf("Hello\n");
scanf("%c", &input);
}

6) Explain Array.Sort(), Array.Fill(), Array.BinarySearch() with


example.
Ans:
Array.Sort():
The Array.Sort() method is used to sort the elements in an array in ascending
order. It takes an array as input and sorts the elements in place, meaning that
the original array is modified. Here is an example of using Array.Sort() to
sort an array of integers:

Ex:
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
Array.Sort(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
// Output: 1 1 2 3 4 5 5 6 9
In the above example, the Array.Sort() method is called on the numbers
array, which sorts the elements in ascending order. The sorted array is then
output to the console using a foreach loop.

Array.Fill():
The Array.Fill() method is used to fill all the elements in an array with a
specified value. It takes an array as input, as well as the value to fill the
array with, and the index to start filling from (optional). Here is an example
of using Array.Fill() to fill an array of strings with the value "Hello World":

Ex:
string[] greetings = new string[5];
Array.Fill(greetings, "Hello World");
foreach (string greeting in greetings)
{
Console.Write(greeting + " ");
}
// Output: Hello World Hello World Hello World Hello World Hello World
In the above example, the Array.Fill() method is called on the greetings
array, which fills all the elements in the array with the string "Hello World".
The filled array is then output to the console using a foreach loop.

Array.BinarySearch():
The Array.BinarySearch() method is used to search for a specified value in a
sorted array. It takes an array as input, as well as the value to search for,
and returns the index of the value in the array (if found), or a negative
number if the value is not found. Here is an example of using
Array.BinarySearch() to search for the value 5 in a sorted array of integers:

Ex:
int[] numbers = { 1, 1, 2, 3, 4, 5, 5, 6, 9 };
int index = Array.BinarySearch(numbers, 5);
Console.WriteLine(index);
// Output: 5
In the above example, the Array.BinarySearch() method is called on the
numbers array to search for the value 5. Since the array is sorted, the
method returns the index of the first occurrence of 5 in the array, which is
5. The index is then output to the console using a Console.WriteLine()
statement.

7) Explain pass by value and pass by reference concept with example.


Ans:
In Java, when you pass a variable as an argument to a method,
there are two ways that the variable can be passed: pass by value and
pass by reference.

Pass by value means that a copy of the variable's value is passed to


the method. Any changes made to the variable inside the method are
not reflected outside the method. Primitive data types in Java, such as
int, float, double, and boolean, are passed by value. Here's an example:
public static void changeValue(int x) {
x = 10;
}

public static void main(String[] args) {


int y = 5;
changeValue(y);
System.out.println(y); // prints 5
}
Pass by reference means that a reference to the variable is passed to
the method. Any changes made to the variable inside the method are
reflected outside the method. Objects in Java are passed by reference.
Here's an example:
public static void changeValue(StringBuilder sb) {
sb.append(" world!");
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
changeValue(sb);
System.out.println(sb.toString()); // prints "Hello world!"
}

Unit -3

1) Discuss Accessibility of Access Modifiers in different condition.


Ans:

There are two types of modifiers in Java: access modifiers and non-access
modifiers.

The access modifiers in Java specifies the accessibility or scope of a field,


method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
2) Discuss Final and static method with example.
Ans:
In Java, final and static are two keywords that can be used to modify
methods.
A final method is a method that cannot be overridden in a subclass. This means
that if a subclass defines a method with the same name and signature as a final
method in its superclass, it will not be able to override it. This is often used to
prevent subclasses from changing the behavior of a particular method that is
critical to the class's functionality.

Here's an example of a final method in Java:

public class Vehicle {


public final void startEngine() {
System.out.println("Engine started.");
}
}

public class Car extends Vehicle {


// This will not compile - a final method cannot be overridden.
public void startEngine() {
System.out.println("This will not print.");
}
}

3) Difference between Abstract Class and interface.


Ans:
4) What is multithreading? Why it is required? Explain Thread Life Cycle.
Ans:

Multithreading is a technique in computer programming where


multiple threads of execution run concurrently within a single process.
In other words, it's a way of creating multiple threads within a single
program, allowing for parallel processing of tasks.

Multithreading is required for several reasons, including:


1. Improving performance: By dividing a program into multiple threads, we can
improve the program's overall performance by utilizing multiple cores or
processors in a computer.
2. Responsiveness: Multithreading can help improve the responsiveness of an
application by allowing it to perform several tasks simultaneously, such as
accepting user input while performing a long-running task in the background.
3. Resource utilization: Multithreading can help utilize resources more efficiently
by allowing a program to perform several tasks simultaneously, rather than
waiting for one task to complete before starting another.

Thread life cycle in Java refers to the various states that a thread can
be in at any given time. These states include:
1. New: A thread is in the "new" state when it has been created but has not yet
started running.
2. Runnable: A thread is in the "runnable" state when it has been started and is
ready to run, but the scheduler has not yet chosen it to run.
3. Running: A thread is in the "running" state when the JVM has selected it to run
on a CPU.
4. Blocked: A thread is in the "blocked" state when it is waiting for a resource to
become available, such as a lock on an object.

5) What is difference between method overloading and method


overriding.
Ans:
Overriding occurs when the method signature is the same in the
superclass and the child class. Overloading occurs when two or more
methods in the same class have the same name but different parameters.

6) Explain Inheritance with example.


Ans:
Inheritance in Java
Inheritance
Types of Inheritance
Why multiple inheritance is not possible in Java in case of class?
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

7) What is Constructor? Explain types of constructor with example.


Ans:
In Java, a constructor is a special method that is used to create and initialize
objects of a class. It is called when an object of a class is created using the new
keyword.

Types of constructors:

1. Default Constructor: A default constructor is a constructor that


takes no arguments. It is automatically created by the compiler if
no constructor is defined in the class. The default constructor
initializes all instance variables to their default values.
public class Person {
String name;
int age;

// default constructor
public Person() {
name = "";
age = 0;
}
}

2. Parameterized Constructor: A parameterized constructor is a


constructor that takes one or more arguments. It is used to
initialize instance variables with the provided values.
public class Person {
String name;
int age;

// parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

3. Copy Constructor: A copy constructor is a constructor that takes an


object of the same class as an argument and creates a new object
with the same values. It is used to create a new object with the
same state as an existing object.
public class Person {
String name;
int age;

// copy constructor
public Person(Person p) {
this.name = p.name;
this.age = p.age;
}
}

4. Private Constructor: A private constructor is a constructor that is


declared private and can only be called from within the same class.
It is used to prevent the instantiation of the class by other classes.
public class Singleton {
private static Singleton instance;

// private constructor
private Singleton() {
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

8) What is Package? Explain creating and importing package in brief.


Ans:

In Java, a package is a way of organizing related classes and


interfaces into a single unit. It helps to prevent naming conflicts and
provides better modularization of code.

create a package in Java, you need to follow these steps:

1. Define a new directory for your package.


2. Place all the related classes and interfaces in that directory.
3. Add a package statement at the top of each source file in the
directory.

To import a package in Java, you can use the import statement. This
statement tells the Java compiler which package to search for the
classes and interfaces that you want to use in your code.
Here's an example of how to import a package:

import com.example.util.*;

public class MyClass {

// code here

}
9) What is Variable? Explain different types of variable.
Ans:

In programming, a variable is a named location in memory that can


hold a value. Variables are used to store data that can be manipulated
or used in computations.

In Java, there are three types of variables:

• Local Variables: A local variable is a variable that is declared within a block


of code, such as a method or a loop. Local variables have a limited scope,
meaning that they can only be accessed within the block of code where they
are declared.
• Instance Variables: An instance variable is a variable that is declared within a
class, but outside of any method. Instance variables are associated with
objects of the class, meaning that each object has its own copy of the
variable. Instance variables can be accessed and modified by any method
within the class.
• lass Variables (also called static variables): A class variable is a variable that
is declared with the static keyword and is associated with the class itself,
rather than with any object of the class. Class variables are shared by all
objects of the class and can be accessed and modified by any method within
the class.
10) Write a java program to implement multiple inheritance. Also
explain the concept implemented.

Ans:
When the child class extends from more than one superclass, it is known
as multiple inheritance. However, Java does not support multiple inheritance.
To achieve multiple inheritance in Java, we must use the interface.
"interface Backend {
// abstract class
public void connectServer();
}
class Frontend {

public void responsive(String str) {


System.out.println(str + " can also be used as frontend.");
}
}
// Language extends Frontend class
// Language implements Backend interface
class Language extends Frontend implements Backend {
String language = "Java";
// implement method of interface
public void connectServer() {
System.out.println(language + " can be used as backend language.");
}
public static void main(String[] args) {
// create object of Language class
Language java = new Language();
java.connectServer();
// call the inherited method of Frontend class
java.responsive(java.language);
}
}

Unit-4
1) Differentiate Checked and unchecked Exception.
Ans:

2) What is Exception Handling? Explain Try, catch and Finally block


with Example.
Ans:
Exception handling is a mechanism in programming that allows a
program to gracefully handle unexpected errors or exceptional conditions
that occur during program execution. In Java, exception handling is done
using try, catch, and finally blocks.

The try block is used to enclose the code that might generate an exception.
If an exception occurs in the try block, the control is transferred to the catch
block. The catch block is used to handle the exception that occurred in the
try block.

Here's an example of try-catch block:


public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int num1 = 10;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}

3) What is Exception? Explain throw and throws block with example.


Ans:
In Java, an exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions. Exceptions can occur
for a variety of reasons, such as incorrect input data, resource exhaustion, or
programming errors.

The throw keyword is used to explicitly throw an exception from a method


or a block of code. This is useful when you want to terminate the normal
flow of execution and raise an exception when a particular condition is
encountered. Here's an example of using the throw keyword:
public void myMethod(int x) {
if (x < 0) {
throw new IllegalArgumentException("x cannot be negative");
}
// rest of the code
}

The throws keyword is used to declare that a method may throw


one or more exceptions. This is useful when you want to indicate
to the caller of the method that they need to handle the
potential exceptions that might be thrown. Here's an example of
using the throws keyword:
public void myMethod() throws IOException {
// code that may throw an IOException
}

4) Explain types of Errors. Give difference between Error and


exception.
Ans:
Error is an illegal operation performed by the user which results in
the abnormal working of the program. Programming errors often
remain undetected until the program is compiled or executed. Some
of the errors inhibit the program from getting compiled or executed.
Thus errors should be removed before compiling and executing.
1. Run Time Error
2. Compile Time Error
In Java, errors and exceptions are both types of problems that can occur
during the execution of a program. However, there are some key
differences between errors and exceptions:

1. Errors are usually caused by the environment or the JVM itself,


while exceptions are caused by problems in the application
code. Errors are typically severe problems that prevent the JVM
from continuing to execute the program, such as out-of-memory
errors or system errors. Exceptions, on the other hand, are
problems that can be handled by the application code, such as
invalid user input or a file that cannot be found.
2. Errors are usually unrecoverable, while exceptions can be
caught and handled. When an error occurs, the JVM may
terminate the program. There is usually no way to recover from an
error and continue executing the program. Exceptions, on the
other hand, can be caught by the application code and handled in
a variety of ways, such as displaying an error message to the user
or retrying an operation.

5) Explain user defined Exception with example.


Ans:

In Java, you can create your own custom exception classes by


extending the Exception class. These custom exception classes
can be used to handle specific errors or exceptional conditions
that might occur in your program. Here's an example of a user-
defined exception class:

public class MyException extends Exception {


public MyException(String message) {
super(message);
}
}

6) Give Advantages of Exception Handling.


Ans:
1. Robustness: Exception handling makes programs more
robust and reliable by allowing them to handle errors and
exceptional conditions gracefully, instead of crashing or producing
incorrect results.
2. Separation of Concerns: Exception handling separates the error-
handling logic from the normal flow of the program, making the
code easier to read and understand. This improves the
maintainability and modularity of the code.
3. Debugging: Exception handling provides a powerful debugging
tool, as it allows developers to trace the source of errors and
exceptions more easily. The stack trace produced by an exception
can be very helpful in pinpointing the location of a bug.
4. User Experience: Exception handling can improve the user
experience of an application by providing meaningful error
messages and allowing the program to recover from errors and
continue running.

7) Write a program to handle Divide by Zero Exception using try-


catch and finally.
Ans:
import java.util.Scanner;

public class DivideByZeroException {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num, denom, result;

try {
System.out.print("Enter numerator: ");
num = sc.nextInt();
System.out.print("Enter denominator: ");
denom = sc.nextInt();

// Divide numerator by denominator


result = num / denom;
System.out.println("Result: " + result);

} catch (ArithmeticException e) {
// Catch divide-by-zero exception
System.out.println("Error: Cannot divide by zero!");

} finally {
// Close scanner object
sc.close();
}
}
}

_______________
Abhishek.

You might also like