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

Untitled Document

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

1)Explain different operators in JAVA in detail.

Ans:Java Operators Overview


Arithmetic Operators:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus/remainder)
Relational Operators:
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
Logical Operators:
&& (logical AND)
|| (logical OR)
! (logical NOT)
Bitwise Operators:
& (bitwise AND)
| (bitwise OR)
^ (bitwise XOR)
~ (bitwise complement)
<< (left shift)
>> (right shift)
>>> (unsigned right shift)
Assignment Operators:
= (assignment)
+=, -=, *=, /=, etc. (compound assignment)
Unary Operators:
++ (increment)
-- (decrement)
+ (unary plus)
- (unary minus)
! (logical complement)
~ (bitwise complement)
Conditional (Ternary) Operator:
? : (ternary operator, shorthand for if-else)
Instanceof Operator:
instanceof (used to check if an object is an instance of a particular class/interface)
2)Explain different control statements in JAVA in detail.
Ans.
Conditional Statements:
if statement: Executes a block of code only if a specified condition is true.
if-else statement: Executes one block of code if the condition is true and another if false.
else-if ladder: Chains multiple conditions, executing the block associated with the first true
condition.
Looping Statements:
for loop: Repeats a block of code a specified number of times.
while loop: Repeats a block of code while a specified condition is true.
do-while loop: Similar to a while loop but guarantees the code block executes at least once
before checking the condition.
Switch Statement:

Used to select one of many code blocks to be executed based on a variable's value. It's an
alternative to using multiple if-else statements.
Jump Statements:
break statement: Terminates the loop or switch statement it's in and transfers control to the
statement immediately following the loop or switch.
continue statement: Skips the current iteration of a loop and continues with the next iteration.
3)How do you achieve multiple inheritance in Java , explain in detail.
Ans.In Java, multiple inheritance, i.e., inheriting from more than one class, is not directly
supported due to concerns about ambiguity and complexity in resolving conflicts that may arise
when methods or attributes with the same name exist in multiple parent classes.

Instead, Java allows for multiple inheritance through interfaces. An interface defines a contract
that implementing classes must follow but doesn't provide any method implementations. A class
can implement multiple interfaces, effectively inheriting multiple sets of method signatures
without the conflicts of multiple inheritance.
-Sample code.
interface A {
void methodA();
}

interface B {
void methodB();
}

class MyClass implements A, B {


public void methodA() {
// Implement methodA
}

public void methodB() {


// Implement methodB
}
}
4)What is the difference between error and an exception?
Nature:
Errors: These are typically caused by the environment and are beyond the control of the
application. Errors are often related to severe failures that may not be recoverable, such as
system failures, out-of-memory errors, or hardware issues.
Exceptions: Exceptions are issues that occur within the application code due to logical errors,
invalid user input, or other exceptional conditions that can be anticipated and handled.
Hierarchy:
Errors: Errors are subclasses of the Error class and are generally unchecked, meaning they
don't need to be caught or declared in a method's throws clause.
Exceptions: Exceptions in Java are subclasses of the Exception class. They can be further
categorized into checked exceptions (which must be caught or declared) and unchecked
exceptions (which don't require explicit handling).
Handling:
Errors: Generally, errors should not be caught and recovered from as they often indicate critical
issues that the application might not be able to resolve.
Exceptions: Exceptions can be caught and handled using try-catch blocks or propagated up
the call stack by declaring them in method signatures using throws.
Recoverability:
Errors: Typically, errors might not be recoverable within the scope of the application as they
signify serious problems that may require system-level interventions.
Exceptions: Exceptions, especially checked exceptions, are designed to be caught and
handled by the application to gracefully handle exceptional conditions and continue execution.
Examples:
Errors: Examples of errors include OutOfMemoryError, StackOverflowError, and
VirtualMachineError.
Exceptions: Examples of exceptions are NullPointerException,
ArrayIndexOutOfBoundsException, and FileNotFoundException."
5)Explain different types of exceptions.
Ans:Exceptions can be categorized in two ways:
1.Built-in Exceptions
• Checked Exception
• Unchecked Exception
2.User-Defined Exceptions.
1. Built-in Exceptions:
Here types of exceptions in Java are predefined within Java libraries. These types of exceptions
in Java occur most frequently. You can consider an Arithmetic Exception in this category. This
predefined exception is found in the Java.lang.package.
–Checked Exceptions:
These types of exceptions in Java are called compile-time exceptions. These exceptions are
checked by
the compiler while the compilation process is ongoing. These types of exceptions in Java can
confirm whether a programmer is handling a specific exception.
List of Common Checked Exceptions in Java:
SQLException: It occurs due to the failure of a database operation.
IOException: It occurs due to the failure of an input/output operation.
–Unchecked Exceptions
These types of exceptions in Java occur during program execution. Therefore, these types of
exceptions are also called runtime exceptions. The unchecked exceptions are not given any
attention during the compilation process.
List of Common Unchecked Exceptions in Java
RuntimeException: It is the superclass of different unchecked exceptions.
Arithmetic Exception: It occurs due to the failure of an arithmetic operation.
2)User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases,
users can also create exceptions, which are called ‘user-defined Exceptions’.
6)What is meant by byte code?
Ans: Java solves both the security and the portability problem is that the output of a Java
compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of
instructions designed to be executed by the Java run-time system, which is called the Java
Virtual Machine (JVM).
In essence, the original JVM was designed as an interpreter for bytecode. Translating a
Java program into bytecode makes it much easier to run a program in a wide variety of
environments because only the JVM needs to be implemented for each platform.
7)How to use break and continue statements in java?
Ans:Break statement as a goto statement:
If we mention a label after the break keyword, the control shifts to the end of the particular label
scope. Java prohibits the use of goto statements because it encourages branched behaviour of
programming. However break labels function like goto statements.
Java program to illustrate the use of break keyword:
import java.util.* :
public class IfStatement
{
public static void main(String[] args) {
for (int i = 0; i < 10 ;i++) {
System.out.println(i);
if ( i ==7)
break;
}}}
b. Continue Statement in Java:
The continue statement is useful for early iteration of a particular loop. Sometimes rather than
breaking out of a loop and halting it for good we want to skip some iterations based on our
requirements of a program. This results in the usage of continue statements.
Java program to illustrate the use of the continue statement:
import java.util.*;
public class ContinueStatement{
public static void main(String[] args) {
for (int i = 0 i < 10 i ++) {
if ( i ==7) continue;
System.out.println(i);
}}}
9)Explain in detail about type conversion and type casting with examples.
Ans:
In Java, casting refers to converting a value of one data type into another. There are two types
of casting: implicit casting (widening) and explicit casting (narrowing).
–Implicit Casting (Widening):
Implicit casting occurs when you're converting a smaller data type into a larger one, where
there's no loss of data. Java automatically performs this type of casting.
Example:
int smallNumber = 10;
double largeNumber = smallNumber; // Implicit casting from int to double.
–Explicit Casting (Narrowing)
Explicit casting, on the other hand, occurs when you're converting a larger data type into a
smaller one, which might result in a potential loss of data. You need to explicitly specify this
conversion in code.
Example:
double largeNumber = 100.5;
int smallNumber = (int) largeNumber; // Explicit casting from double to int
Implicit casting is done automatically by the Java compiler for widening conversions.Explicit
casting is needed for narrowing conversions, and it should be used with caution as it may result
in data loss or unexpected behavior.Casting between incompatible types might cause runtime
errors or unexpected behavior, so it's essential to be careful while performing explicit casts.
10)Differentiate between class and object.
Ans:
Definition:
Class: It's a blueprint or template that defines the structure and behavior of objects. It
encapsulates data and methods that describe the properties and actions of the objects.
Object: It's an instance of a class. It's a runtime entity and represents a real-world entity,
possessing state (attributes/fields) and behavior (methods) as defined by its class.
Usage:
Class: Acts as a blueprint or a template that can be used to create multiple instances or objects.
Object: Represents a specific instance created from a class. Multiple objects can be created
from the same class, each with its own set of properties and behaviors.
Memory Allocation:
Class: Doesn't occupy memory space until an object is created from it. It's a static entity in
memory.
Object: Occupies memory space when instantiated from a class. Each object has its own
memory allocation and holds its specific data.
Accessing Elements:
Class: Cannot access instance variables or methods directly. To access them, an object needs
to be created from the class.
Object: Can access both instance variables (data members) and methods defined in the class it
was instantiated from.
Relationship:
Class: Defines the structure and behavior that objects of that class will exhibit.
Object: Represents a single occurrence or instance of that defined structure and behavior.
In essence, a class serves as a template or blueprint for creating objects, while an object is
an instance of a class, possessing its own state and behavior defined by that class.
11)Types of inheritance?
Ans:
12)What are the types of inheritances in java?
Ans:
Inheritances:Inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such a way, you can reuse, extend or modify the
attributes and behaviors which are defined in other classes.
In Java, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Types of Inheritance :
1. Single inheritance : When one class inherits another class, it is known as single level
inheritance
class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1/2)*b*h);
}
}

2. Hierarchical inheritance : Hierarchical inheritance is defined as the process of deriving more


than one class from a base class.
Sample code
class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1/2)*b*h);
}
}
class Circle extends Shape {
public void area(int r) {
System.out.println((3.14)*r*r);
}
}

3. Multilevel inheritance : Multilevel inheritance is a process of deriving a class from another


derived class.
class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1/2)*b*h);
}
}
class EquilateralTriangle extends Triangle {
int side;
}
4. Hybrid inheritance : Hybrid inheritance is a combination of simple, multiple inheritance and
hierarchical inheritance.
Sample code:
class SolarSystem {
}
Class Earth extends SolarSystem {
}
Class Mars extends SolarSystem {
}
Public class Moon extends Earth {
Public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();
System.out.println(s instanceof SolarSystem);
System.out.println(e instanceof Earth);
System.out.println(m instanceof SolarSystem);
}
}
Polymorphism:It allows different classes to be treated as instances of the same class through
inheritance, enabling methods to be overridden in subclasses to exhibit unique behavior while
sharing a common interface.
Method Overloading:
Method Overloading is a Compile time polymorphism. In method overloading, more than one
method shares the same method name with a different signature in the class. In method
overloading, the return type can or can not be the same, but we have to change the parameter
because, in java, we can not achieve method overloading by changing only the return type of
the method.
Different ways to overload the method.There are two ways to overload the method in java.
1)By changing number of arguments.2)By changing the data type.
1)By changing number of arguments.
class Cse1{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Cse1.add(11,11));
System.out.println(Cse1.add(11,11,11));
}}
2)By changing the data type.
class Cse1{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Cse1.add(11,11));
System.out.println(Cse1.add(12.3,12.6));
}}
Achive the polymorphism or method overriding
Method Overriding:
Polymorphism is primarily achieved through method overriding, where a subclass provides a
specific implementation of a method that is already defined in its superclass.
The method in the subclass must have the same signature (name, parameters, and return type)
as the method in the superclass.
Sample code:
class Super Class {
public static void sample() ;
{
System.out.println("Method of the super class");
}
}
public class SubClass extends SuperClass {
public static void sample() {
System.out.println("Method of the sub class");
}
public static void main(String args[]) {
SuperClass obj1 = new SubClass();
SubClass obj2 = new SubClass();
obj1.sample();
obj2.sample();
}
}
15)What are benefits of exception handling?
Ans:Importance of Exception Handling
•Ensures the Continuity of the Program. ...
•Enhances the Robustness of the Program. ...
• Improves the Readability & Maintainability of the Code. ...
•Allows for more Accurate Error Reporting. ...
•Facilitates Debugging and Troubleshooting. ...
• Improves the Security of the Program. ...
•Provides a Better user Experience.
Examples on exception handling
class Main {
public static void main (String args[]) {
try
{
System.out.println ("::Try Block::");
int data = 125 / 5;
System.out.println ("Result:" + data);
}
catch (NullPointerException e) {
System.out.println ("::Catch Block::");
System.out.println (e);
}
finally {
System.out.println (":: Finally Block::");
System.out.println ("No Exception::finally block executed");
System.out.println ("rest of the code...");
}
}
16)List and explain Java buzzwords. Which factors are making Java famous language.
Ans:
1. Simple:
It is free from pointer due to this execution time of application is improve, It have rich set of APIs
(application programming interface).
It have Garbage Collector which is always used to collect un-referenced (unused) memory
locations for improving performance of a Java program.
IV. It contains user friendly syntax for developing any applications.
2. Object Oriented: Java supports OOP features and everything is an Object in Java. The
object model in Java is simple and easy to extend.
3. Robust: Java is robust or strong programming language because of its capability to
handle run-time errors, automatic garbage collection, lack of pointer concept,
exception handling. These entire things make Java is a robust Language.
4. Multi Threading: Java was designed to meet the real-world requirement of creating
interactive, networked programs. To accomplish this, Java supports multithreaded programming,
which allows you to write programs that do many things simultaneously. The Java run-time
system comes with an elegant yet sophisticated solution for multiprocess synchronization that
enables you to construct smoothly running interactive systems.
5. Architecture-Neutral: Architecture represents processor. A language or technology is said to
be architectural neutral which can run on any processors in the real world without considering
type of architecture and vendor (providers).
6. Interpreted: Java programs are compiled to generate the byte code. This byte code can be
downloaded and interpreted by the interpreter in JVM. If we consider any other language, only
an interpreter or a compiler to execute the programs. But in Java, we use both interpreter and
compiler for the execution.
7. High Performance: The problem with interpreter inside JVM is that it is slow. Because of
this, Java programs used to run slow. To overcome this, along with interpreter, Java people
have introduced JIT (Just-in-Time) compiler, which enhances the speed of execution. So now in
JVM, both interpreter and JIT compiler works together to run the program.
8. Distributed: Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols. Java also supports Remote Method Invocation (RMI). This
feature enables a program to invoke methods across a network.
9. Dynamic: Java support dynamic memory allocation. Due to this memory wastage is
reduced. The process of allocating the memory space to the program at a run-time is known as
dynamic memory allocation, To allocate memory space dynamically we use an operator called
'new'. 'new' operator is known as dynamic memory allocationoperator.
10. Secure: It is more secured language compare to other languages; In this, program is
covered into byte code after compilation which is not readable by human and also Java does
not support global variable concept.
11. Portable: If any language supports platform independent and architectural neutral features,
then that language is portable.
Portable=Platformindependent+Architecture-neutral.
17) What is the significance of the CLASSPATH environment variable in using a package?
Ans:The CLASSPATH environment variable in Java is crucial as it specifies the location where
the Java compiler and runtime should look for classes and packages. It helps the system locate
the necessary Java classes and libraries when executing a Java program. When working with
packages, setting the CLASSPATH correctly ensures that the compiler and runtime can find the
required classes within packages to successfully compile and execute the program.
18)Explain in detail about types of method binding.
Method binding refers to the association between a method call and the method body in
programming languages. There are mainly three types of method binding:
Static Binding (or Early Binding):
Occurs during compile-time.
The association between method call and method definition is resolved at compile-time based
on the declared types of variables or objects.
In languages like Java, static binding happens for methods that are private, final, or static as
they cannot be overridden and their binding is resolved at compile-time.
Dynamic Binding (or Late Binding):
Occurs during runtime.The association between method call and method definition is resolved
at runtime based on the actual object type (runtime type) rather than the reference type.
Inheritance and method overriding in object-oriented languages like Java, C++, and Python
utilize dynamic binding. When a subclass overrides a method from its superclass, the method
invoked is determined by the actual type of the object at runtime.
Virtual Method Binding:
Specific to object-oriented programming languages like Java.
Refers to the process of determining the implementation of a method to execute in response to
a method call at runtime.
Achieved through method overriding, where a subclass provides a specific implementation of a
method that is already defined in its superclass. The decision on which method to execute is
made at runtime based on the actual object type.
18)Explain in detail about types of method binding.
Ans:
Static binding:
Binding of static, final and private methods is always a static binding because a static binding
gives better performance and they cannot be overridden and hence will always be accessed by
the object of some local class.
Dynamic binding:
Overriding in Java can be considered as the best example of dynamic binding as both parent
and child class have the same method, that is it doesn’t decide the method to be called.
19)Write a sample java program to find the GCD of two numbers.
Ans:
import java.util.Scanner;
public class GCDCalculator {
public static int calculateGCD(int num1, int num2) {
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input first number


System.out.print("Enter first number: ");
int number1 = scanner.nextInt();

// Input second number


System.out.print("Enter second number: ");
int number2 = scanner.nextInt();

// Calculate GCD
int gcd = calculateGCD(number1, number2);

// Display the GCD


System.out.println("GCD of " + number1 + " and " + number2 + " is: " + gcd);

scanner.close();
}
}
20)Write a sample java program to find the factorial of a number.
Ans:
import java.util.Scanner;

public class FactorialCalculator {


// Method to calculate factorial
public static int calculateFactorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
int factorial = 1;
for (int i = 2; i <= num; i++) {
factorial *= i;
}
return factorial;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input number
System.out.print("Enter a number to calculate its factorial: ");
int number = scanner.nextInt();

// Calculate factorial
int factorial = calculateFactorial(number);

// Display the factorial


System.out.println("Factorial of " + number + " is: " + factorial);

scanner.close();
}
}
21)Write a sample java program to find the prime numbers.
Ans:
import java.util.Scanner;

public class PrimeNumberFinder {


// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input limit
System.out.print("Enter the limit to find prime numbers up to that limit: ");
int limit = scanner.nextInt();

System.out.println("Prime numbers up to " + limit + " are:");


// Finding and displaying prime numbers
for (int i = 2; i <= limit; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}

scanner.close();
}
}
22)Write a sample java program to find the armstrong numbers.
Ans:
import java.util.Scanner;
public class ArmstrongNumberFinder {
// Method to check if a number is an Armstrong number
public static boolean isArmstrong(int num) {
int originalNum, remainder, result = 0, n = 0;
originalNum = num;

// Count number of digits


while (originalNum != 0) {
originalNum /= 10;
++n;
}

originalNum = num;

// Calculate result
while (originalNum != 0) {
remainder = originalNum % 10;
result += Math.pow(remainder, n);
originalNum /= 10;
}

// Check if the number is Armstrong


return result == num;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// Input range
System.out.print("Enter the range to find Armstrong numbers (from): ");
int from = scanner.nextInt();
System.out.print("Enter the range to find Armstrong numbers (to): ");
int to = scanner.nextInt();

System.out.println("Armstrong numbers between " + from + " and " + to + " are:");

// Finding and displaying Armstrong numbers


for (int i = from; i <= to; i++) {
if (isArmstrong(i)) {
System.out.print(i + " ");
}
}

scanner.close();
}
}
23)Write a sample java program to find the even or odd numbers
Ans:
import java.util.Scanner;

public class EvenOddChecker {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input number
System.out.print("Enter a number to check if it's even or odd: ");
int number = scanner.nextInt();

// Check if the number is even or odd


if (number % 2 == 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}

scanner.close();
}
}
26)Explain about Concepts of exception handling?
Ans:
-Exception: An exception is an event that occurs during the execution of a program, disrupting
the normal flow. It can be caused by various factors like incorrect input, hardware failures, or
programming errors.
-Try-Catch block: This block is used to handle exceptions. The code that might throw an
exception is placed within the try block. If an exception occurs, it's caught by the catch block,
allowing the program to respond to the exceptional condition.
-Throwing exceptions: Exceptions can be manually thrown using the throw keyword. This is
useful when a specific condition is met and the programmer wants to explicitly signal an
exceptional condition.
- Finally block: This block follows a try-catch block and contains code that needs to be
executed regardless of whether an exception occurred or not. It's commonly used to release
resources or perform cleanup operations.
27)Explain why Java is Machine Independent.
Ans:
1.Java Virtual Machine (JVM): Java code is compiled into bytecode, which isn't tied to any
specific hardware or operating bytecode is executed by the JVM, which is platform-specific.
JVMs are available for various platforms, and they interpret bytecode into machine code on the
fly, allowing Java programs to run on different systems without modification.
2.Write Once, Run Anywhere (WORA): Java follows the principle of WORA. Developers can
write Java code on one platform and expect it to run on any other platform with a compatible
JVM, without needing to recompile the code.
3.Abstraction of Hardware: Java abstracts many hardware-specific functionalities through its
libraries and APIs. For instance, file handling, networking, and graphical user interfaces are
managed by Java libraries, shielding the developer from underlying hardware intricacies.
4.No Native Code: Unlike some other programming languages, Java doesn't generate native
code specific to a particular platform during compilation. Instead, it generates bytecode, which is
platform-independent.
5.Bytecode Verification: Before executing bytecode, the JVM verifies it to ensure security and
stability. This verification process adds another layer of independence from the underlying
hardware or OS.

28)Difference between literal and keywords and identifier.


Ans:
1.Literals: These are fixed values that are directly used in code. They represent constants or
values that cannot be changed. Examples include numeric literals (like 5, 3.14), string literals
(like "Hello"), boolean literals (true or false), or even special literals like null. Literals are used to
represent specific values in code.
2.Keywords: Keywords are reserved words in a programming language that have predefined
meanings and purposes. They cannot be used as identifiers (variables, function names, etc.) in
the code. Keywords often denote control structures, data types, or specific functionalities within
the language. For example, in Java, keywords include if, else, class, public, static, etc.
3.Identifiers: These are names given by programmers to variables, functions, classes, or other
entities within a program. Identifiers are user-defined and serve as labels for different elements
in the code. They follow certain rules set by the programming language, such as starting with a
letter or underscore, consisting of letters, digits, and underscores, and not being a keyword.
Examples of identifiers could be variable names like count, totalAmount, function names like
calculateTotal(), or class names like UserInput.
30)Write about recursion in java
Ans:
Recursion in Java:Recursion in java is a process in which a method calls itself continuously. A
method in java that calls itself is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Sample Program:

31)Elaborate different methods available in string object.


Ans:
charAt(int index): Retrieves the character at a specified index.
length(): Returns the length of the string.
substring(int beginIndex, int endIndex): Extracts a portion of the string between the specified
indices.
concat(String str): Concatenates the specified string at the end of the current string.
indexOf(String str): Returns the index within the string of the first occurrence of the specified
substring.
toUpperCase(): Converts the string to uppercase.
toLowerCase(): Converts the string to lowercase.
trim(): Removes leading and trailing whitespaces.
replace(char oldChar, char newChar): Replaces all occurrences of a specified character with
another character.
32)Explain passing parameters in java?
Passing parameters in Java involves sending data to a method when it's called. There are two
ways to pass parameters:

Pass-by-value: Primitive data types (like int, float, etc.) are passed by value, which means a
copy of the actual value is passed to the method. Changes made to the parameter inside the
method do not affect the original variable outside the method.
Pass- by reference(aliasing): Changes made to formal parameter do get transmitted back to
the caller through parameter passing. Any changes to the formal parameter are reflected in the
actual parameter in the calling environment as formal parameter receives a reference (pointer)
to the actual data. This method is also called as call by reference. This method is efficient in
both time and space.

33)What is scope? Explain lifetime of a variable with an example.


Ans:
34)Explain about subclass and subtype in JAVA.
Ans:
35)How are the abstract methods called or excueted?
Abstract methods in Java are meant to be overridden by subclasses. They don't have an
implementation in the abstract class where they are declared. When a class extends an abstract
class containing abstract methods, it must provide concrete implementations for those abstract
methods.

Abstract methods are invoked or executed through polymorphism. When an object of the
subclass is created, and one of its methods (which overrides the abstract method) is called, the
overridden method in the subclass gets executed. This allows the abstraction defined in the
abstract class to be realized in the concrete subclass implementation.
36) Discuss the uses of final keyword?
Ans:
Constants: When applied to a variable, final makes it a constant, meaning its value cannot be
changed after initialization.
Method: When applied to a method, final prevents the method from being overridden in any
subclass, providing a fixed implementation.
Class: Declaring a class as final prevents other classes from extending it, making it impossible
to create subclasses.
Performance optimization: In some cases, the final keyword can assist the compiler in
optimization, allowing for potentially faster execution of code by enabling certain optimizations.
37) Elaborate who polymorphism is achieved in java.
Polymorphism is one of the main aspects of Object-Oriented Programming(OOP). The word
polymorphism can be broken down into Poly and morphs, as “Poly” means many and “Morphs”
means forms. In simple words, we can say that ability of a message to be represented in many
forms.Polymorphism in Java can be achieved in two ways i.e., method overloading and method
overriding.
Polymorphism in Java is mainly divided into two types.

Compile-time polymorphism

Runtime polymorphism

Compile-time polymorphism can be achieved by method overloading, and Runtime


polymorphism can be achieved by method overriding. In the further article, we will be discussing
all the topics related to polymorphism in Java in more detail.
38Q
41)Garbage collector?
Ans:
Sample code:
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
42)Give a brief introduction to variables in an interface.
Ans:
In java, an interface is a completely abstract class. An interface is a container of abstract
methods and static final variables. The interface contains the static final variables. The variables
defined in an interface can not be modified by the class that implements the interface, but it may
use as it defined in the interface.

● The variable in an interface is public, static, and final by default.


● If any variable in an interface is defined without public, static, and final keywords then,
the compiler automatically adds the same.
● No access modifier is allowed except the public for interface variables.
● Every variable of an interface must be initialized in the interface itself.
● The class that implements an interface can not modify the interface variable, but it may
use as it defined in the interface.
Sample code:
int UPPER_LIMIT = 100; LOWER_LIMIT;
public class InterfaceVariablesExample implements SampleInterface{
public static void main(String[] args) { System.out.println
("UPPER LIMIT="UPPER_LIMIT);
}}
43)Explain method overloading and overriding
Ans:
*Method Overriding:* Method overriding occurs when a subclass provides a specific
implementation for a method that is already defined in its superclass. The method signature
(name, return type, and parameters) must be the same in both the superclass and the subclass.
This allows the subclass to provide its own implementation of the method.
Sample program:
class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1.0 / 2) * b * h);
}}
class Circle extends Shape {
public void area(int r) {
System.out.println((3.14) * r * r);
}}
public class Main
{
public static void main(String[] args)
{
Triangle triangle = new Triangle();
Circle circle = new Circle();
triangle.area(5, 4);
circle.area(3);
}}
*Method Overloading:* Method overloading happens when multiple methods in the same
class have the same name but different parameters (either different types or different numbers
of parameters). Java allows method overloading to create multiple methods with the same name
but different behaviors based on the parameters they accept.
Sample program:

class Student {
String name;
int age;

public void displayInfo(String name) {


System.out.println(name);
}

public void displayInfo(int age) {


System.out.println(age);
}

public void displayInfo(String name, int age) {


System.out.println(name);
System.out.println(age);
}

public static void main(String[] args) {


Student student = new Student();

student.name = "John Doe";


student.age = 20;

student.displayInfo(student.name);
student.displayInfo(student.age);
student.displayInfo(student.name, student.age);
}
}
45,46,47Q)

48)Explain the use of super keyword with an example.


Ans:The super keyword is used to refer to the superclass of a class. It's often used to access
methods, variables, or constructors from the parent class. For instance:
Sample code:
class Parent {
int num = 10;
void display() {
System.out.println("This is from the parent class");
}}
class Child extends Parent {
int num = 20;
void display() {
super.display();
System.out.println("This is from the child class");
System.out.println("Value of num in child class: " + num);
System.out.println("Value of num in parent class: " + super.num); // Accesses num from the
Parent class
}}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
}}

40Q
34Q)

You might also like