V20PCA101 - Programming Using Java

You might also like

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

Program MCA

Semester 1

Course Programming Using Java

Part A
Q.1 Consider the following code segment.
int sum = 0;
int k = 1;
while (sum < 12 || k < 4)
sum += k;
System.out.println(sum);

What is printed as a result of executing the code segment?


(A) 6
(B) 10
(C) 12
(D) Nothing is printed due to an infinite loop

Answer- D

Q.2 Consider the following code segment.


int num = 2574;
int result = 0;
while (num > 0) {
result = result * 10 + num % 10;
num /= 10;
}
System.out.println(result);
What is printed as a result of executing the code segment?
(A) 2
(B) 4
(C) 18
(D) 4752

Answer-D

Q.3 Consider the following code segment.


int count = 0;
for (int x = 0; x < 4; x++) {
for (int y = x; y < 4; y++) {
count++;
}
}
System.out.println(count);
What is printed as a result of executing the code segment?
(A) 4
(B) 8
(C) 10
(D) 16
Answer- C

Q.4 Consider the following code segment.


int[] arr = {7, 2, 5, 3, 0, 10};
for (int k = 0; k < arr.length - 1; k++) {
if (arr[k] > arr[k + 1])
System.out.print(k + " " + arr[k] + " ");
}
What will be printed as a result of executing the code segment?
(A) 0 2 2 3 3 0
(B) 0 7 2 5 3 3
(C) 0 7 2 5 5 10
(D) 1 7 3 5 4 3

Answer- B

Q.5 Consider the following method that is intended to return the sum of the
elements in the array key.
public static int sumArray(int[] key) {
int sum = 0;
for (int i = 1; i <= key.length; i++) {
/* missing code */
}
return sum;
}
Which of the following statements should be used to replace /* missing code
*/ so that sumArray will work as intended?
(A) sum = key[i];
(B) sum += key[i - 1];
(C) sum += key[i];
(D) sum += sum + key[i - 1];

Answer- B

Q.6- Consider the following method.


public int compute(int n, int k) {
int answer = 1;
for (int i = 1; i <= k; i++)
answer *= n;
return answer;
}
Which of the following represents the value returned as a result of the call
compute(n, k)?
(A) n*k
(B) !n
(C) nk
(D) 2k

Answer-C

Q.7 Consider the following code segment.


int x = 1;
while ( /* missing code */ ) {
System.out.print(x + " ");

x = x + 2;
}
Consider the following possible replacements for /* missing code */. I.
x<6
II. x != 6
III. x<7
Which of the proposed replacements for /* missing code */ will cause the code
segment to print only the values 1 3 5 ?
(A) I only
(B) II only
(C) I and II only
(D) I and III only

Answer- D

Q.8 Consider the following method.


/** Precondition: values has at least one row */
public static int calculate(int[][] values) {
int found = values[0][0];
int result = 0;
for (int[] row : values) {
for (int y = 0; y < row.length; y++) {
if (row[y] > found) {
found = row[y];
result = y; }
}
}
return result;
}
Which of the following best describes what is returned by the calculate method?
(A) The largest value in the two-dimensional array
(B) The smallest value in the two-dimensional array
(C) The row index of an element with the largest value in the two-dimensional
array
(D) The column index of an element with the largest value in the two-
dimensional array

Answer- D

Q.9 Consider the following code segment.

int x = 15;

if (x < 15)
{
x = 3 * x;
}

if (x % 2 == 1)
{
x = x / 2;
}

System.out.print(2*x + 1);
What is printed as a result of executing the code segment?

A. 45
B. 11
C. 15
D. 5

Answer- C

Q.10 What is printed as a result of executing the following code segment?

int x = 10;
int y = 5;

if (x % 2 == 0 && y % 2 == 0 || x > y)
{
System.out.print("One ");

if (y * 2 == x || y > 5 && x <= 10)


{
System.out.print("Two ");
}
else
{
System.out.print("Three ");
}
}
A. Nothing is printed out.
B. One
C. TwoThree
D. OneTwo

Answer-D

Q.11 Consider the following class declaration.


public class Student {
private String myName;
private int myAge;
public Student() {
/* implementation not shown */
}
public Student(String name, int age) {
/* implementation not shown */
}
// No other constructors}
Which of the following declarations will compile without error?
I. Student a = new Student();
II. Student b = new Student("Juan", 15);
III. Student c = new Student("Juan", "15");
(A) I only
(B) II only
(C) I and II only
(D) I and III only

Answer- C

Q.12 Consider the following methods:

public void inchesToCentimeters(double i)


{
double c = i * 2.54;
printInCentimeters(i, c);
}
public void printInCentimeters(double inches, double centimeters)
{
System.out.print(inches + "-->" + centimeters);
}
Assume that the method call inchesToCentimeters(10) appears in a method in
the same class. What is printed as a result of the method call?

A. inches –> centimeters


B. 10 –> 25
C. 25.4 –> 10
D. 10.0 –> 25.4

Answer-D

Q.13 Consider the following method.


public static boolean mystery(String str) {
String temp = "";
for (int k = str.length(); k > 0; k--) {
temp = temp + str.substring(k - 1, k);
}
return temp.equals(str);
}
Which of the following calls to mystery will return true?
(A) mystery("no")
(B) mystery("on")
(C) mystery("nnoo")
(D) mystery("noon")
Answer-E

Q.14 How many objects will be created on following code segment execution?

String s1= new String (“Hello”);


String s2= new String (“Hello”);
String s3= “Hello”;
String s4= “Hello”;

A. 1
B. 2
C. 3
D. 4
Answer-C

Q.15 What will be the output of the following program?


public class Test{
public static void main(String args[]){
String s1 = "mca";
String s2 = "mca";
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
}
}

(A) true false


(B) false true
(C) false false
(D) true true

Answer-D

Q.16 What will be the output of the following program?

public class Test {


public static void main() {
System.out.println("Welcome ");
}
public static void main(String msg) {
System.out.println("To ");
}
public static void main(String[] args) {
System.out.println("Java");
}
}
(A) Welcome
(B) Welcome To
(C) Java
(D) Welcome To Java

Answer-C

Q.17 What will be the output of the following program?

public class Test {


static int s=50;
public static void main(String[] args) {
int s=10;
System.out.println(s);
}
}
A) 50
(B) 10
(C) Compile-time error
(D) 50 10

Answer-B

Q.18 What will be the output of the following program?

public class Test {


public static void main(String[] args) {
String s="Good ";
s.concat("Morning");
System.out.println(s);
}
}
A) Good
(B) Good Morning
(C) Compile-time error
(D) Morning

Answer-A

Q.19 What will be the output of the following program?

public class Test {


int var=10;
void m()
{
int var =30;
System.out.println(var+" "+this.var);

}
public static void main(String[] args) {
Test t=new Test();
t.m();
}
}
A) 10 10
(B) 10 30
(C) 30 10
(D) 30 30

Answer-C

Q.20 What will be the output of the following program?

public class Test {


Test()
{
System.out.print("Hello! ");
}
Test(String msg)
{
this();
System.out.println(msg);
}
public static void main(String[] args) {
Test t=new Test("How are you?");

}
}
A) Hello How are you?
(B) How are you?
(C) Compile-time error
(D) Hello

Answer-A

Q.21 public interface Student {


/* implementation not shown */
}
public class Athlete {
/* implementation not shown */
}
public class TennisPlayer extends Athlete implements Student {
/* implementation not shown */
}
Assume that each class has a zero-parameter constructor. Which of the
following is NOT a valid declaration?
(A) Student a = new TennisPlayer();
(B)TennisPlayer b = new TennisPlayer();
(C)Athlete c = new TennisPlayer();
(D)Student d = new Athlete();

Answer-D
Q.22 Whickeyword is h of the following is not a method of Object class?
A) equals()
B) wait()
C) notify()
D) join()
Answer-D
Q.23 Which of the following inheritance is supported only through interfaces?

A) Multiple
B) Single
C) Hierarchical
D) Multilevel
Answer-A

Q.24 Which of the following is a checked exception?

A) ArithmeticException
B) NullPointerException
C) IOException
D) NumberFormatException
Answer-C

Q.25 Object creation is not allowed for-

A) Abstract class
B) Interface
C) Both abstract class and interface
D) None of these
Answer-C

Q.26 Which of the following is not a use of super keyword?

A. super can be used to refer immediate parent class instance variable.


B. super can be used to invoke the immediate parent class method.
C. super can be used to refer to the immediate parent class local variable.
D. super() can be used to invoke the immediate parent class constructor.

Answer- C

Q.27 What is the output of the following code?


interface Testable
{
void show();
}
class Test implements Testable
{
public void show()
{
System.out.println("Hello !");
}
}
public class Main {
public static void main(String[] args) {
Test obj = new Test ();
obj.show();
}
}
A. Exception
B. Hello !
C. Compilation error
D. Run time error

Answer-B

Q.28 Which is the immediate super class of Exception and Error?

A) Throwable

B) BaseException
C) RuntimeException

D) Object
Answer-A

Q.29 What is the output of the following code?


interface Testable
{
int data;
}
class Test implements Testable
{
void show()
{
System.out.println(data);
}
}
public class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.show();
}
}
A. 0

B. Garbage value

C. Runtime error

D. Compilation error

Answer-D

Q.30 An interface is not allowed to have-


A) Constants
B) Constructors
C) Abstract Methods
D) Concrete Methods

Answer- B

Q.31 Which of the following is not a method of Scanner class?

A) nextInt()
B) nextChar()
C) nextFloat()
D) nextByte()

Answer- B

Q.32 Which of the following is not a state of life cycle of a thread?

A) Runnable
B) Terminated
C) Running
D) Joining

Answer- D

Q.33 Which interface can be used for creating threads?

A) Threadable
B) MultiThead
C) Runnable
D) Multiple

Answer- C

Q34. Which of the following class is not defined in java.util package?

A) String
B) Scanner
C) ArrayList
D) Vector

Answer- A

Q.35 What will be the output of the following code snippet?


public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());
}
A) 1
B) 5
C) 10
D) 100

Answer- B

Q.36 What will be the output of the following code snippet?

public static void main(String[] args)


{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();

// pushing elements into stack


stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
stk.push(50);

System.out.println(stk.search(20));
}
}
A) 1
B) 2
C) 4
D) -1

Answer- C

Q.37 Which of the following class extends Vector class?


A) List
B) ArrayList
C) Queue
D) Stack

Answer-D

Q.38 What will be the output of the following code snippet?

public static void main(String[] args)


{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();

// pushing elements into stack


stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
stk.push(50);

stk.peek();
System.out.println("Elements in Stack: " + stk);
}
}
A) [10, 20, 30, 40, 50]
B) [10, 20, 30, 40]
C) [20, 30, 40, 50]
D) [50, 40, 30, 20, 10]

Answer- A

Q.39 Which of the following is not a legacy class?


A. ArrayList
B. Dictionary
C. Properties
D. Vector

Answer-A

Q.40 Which of the following is an abstract class?


A. Random
B. Calender
C. Date
D. GregorianCalendar

Answer-B

Q.41 Which of the following is a character stream class?

A) FileInputStream
B) BufferedInputStream
C) DataInputStream
D) FileReader

Answer-D

Q.42 Which stream classes are designed for raw binary data?

A) Byte stream
B) Character stream
C) File stream
D) Input stream

Answer-A

Q.43 write() from FileWriter class throws-

A) FileNotFoundException
B) ArithmeticException
C) IOException
D) WriteException

Answer-C
Q.44 Which of the following is not a container?

A) Frame
B) Panel
C) Window
D) Button

Answer-D

Q.45 How many methods are given in ActionListener interface?

A) 2
B) 5
C) 1
D) 0
Answer-C

Q.46 Which of the following is the default layout?

A) BorderLayout
B) FlowLayout
C) GridLayout
D) None of these

Answer-B

Q.47 What is the return type of read() of the FileReader class?

A) String
B) char
C) int
D) double
Answer-C

Q.48 Which exception is thrown when you try to read a closed file?

A) FileNotFoundException
B) IOException
C) FileCloseException
D) FileException

Answer- B

Q.49 Which is used to arrange the components in five regions: north, south,
east, west, and center?

A) FlowLayout
B) CardLayout
C) BorderLayout
D) BoxLayout

Answer- D

Q.50 Which of the following controls allows multiple lines of text?

A) List
B) TextArea
C) TextField
D) Label

Answer-C

Part B
Q.1 What is the difference between a break and continue statement?
Answer-The break statement causes the program execution to exit the loop
or switch statement immediately, and control is transferred to the statement
immediately following the loop or switch.
The continue statement causes the program execution to jump to the next
iteration of the loop, skipping the remaining code within the loop body for
the current iteration.

Q.2 Is Java a pure object-oriented programming language? Justify your answer.


Answer- Java is not a pure object-oriented programming language, as it supports
primitive data types and Wrapper classes. Java is fully object-oriented but not
pure object oriented.

Q.3 Write a method to find smallest element from array .


Answer-
public static int findSmallestElement(int[] array) {

// Initialize the smallest element as the first element of the array


int smallest = array[0];

// Iterate through the array to find the smallest element


for (int i = 1; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}

return smallest;
}
Q.4 Differentiate between a while loop and a do-while loop in Java.
Answer- While Loop:
Syntax: while (condition) {
// Code block
}
Execution: In a while loop, the condition is evaluated before the execution of
the code block. If the condition is true, the code block is executed. If the
condition is false initially, the code block is never executed.
Example:
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
Note: It's possible that the code block within a while loop may never execute if
the condition is false from the start.
Do-While Loop:
Syntax: do {
// Code block
} while (condition);
Execution: In a do-while loop, the code block is executed at least once,
regardless of the condition. After the first execution, the loop condition is
evaluated. If the condition is true, the code block is executed again, and the
process continues. If the condition is false after the first execution, the loop
terminates.
Example:
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);
Note: The code block within a do-while loop always executes at least once
because the loop condition is evaluated after the first execution.

Q.5 Explain logical operators in java.


Answer-
1. AND Operator (&&): The AND operator returns true if both of its
operands are true, otherwise, it returns false.
Syntax: operand1 && operand2
Example: boolean result = (true && false); // Evaluates to false
2. OR Operator (||): The OR operator returns true if at least one of its
operands is true, otherwise, it returns false.
Syntax: operand1 || operand2
Example: boolean result = (true || false); // Evaluates to true
3. NOT Operator (!): The NOT operator is a unary operator that negates the
boolean value of its operand. It returns true if the operand is false, and
false if the operand is true.
Syntax: !operand
Example: boolean result = !true; // Evaluates to false

Q.6 How constructors are different from regular methods?


Answer- 1. Constructors are special methods used for initializing objects. They
are called automatically when an object of a class is created.
Regular methods are used to perform specific tasks or operations within a class.
They are called explicitly by the programmer as needed.
2. Constructors do not have a return type, not even void.
Regular methods can have a return type, which can be any valid data type in
Java, including void.
3. Constructors have the same name as the class in which they are declared.
Regular methods have unique names that are chosen by the programmer to
describe the operation they perform.

Q.7 What is the purpose of “this” keyword and list any 2 uses of this keyword in
Java.
Answer- In Java, this is a reference variable that refers to the current object.
1. this can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
Q.8 Explain static method in Java.
Answer- In Java, a static method is a method that belongs to the class rather
than to any instance of the class. This means that the method can be called
directly using the class name, without the need to create an object of the class.
Static methods cannot directly access instance variables (non-static fields) of the
class. However, static methods can access other static members, including static
variables and other static methods.
Q.9 What are the different access modifiers in Java?
Answer- 1. public: Classes, variables, methods, and constructors marked as
public are accessible from any other class in the same package or from any other
package. There are no restrictions on access.
2. protected: Variables, methods, and constructors marked as protected are
accessible within the same package or by subclasses (even if they are in
different packages). Outside the package, protected members are only
accessible through inheritance.
3. package private (no modifier):If no access modifier is specified, the
default access level is applied.Classes, variables, methods, and
constructors with default access are accessible only within the same
package.
4. private: Variables, methods, and constructors marked as private are
accessible only within the same class. They are not visible to any other
class, including subclasses.
Q.10 Explain the “final” keyword and its uses.
Answer- The final keyword in Java is used to restrict the user. The java final
keyword can be used in many contexts. Final can be:
1. variable - If you make any variable as final, you cannot change the value
of final variable (It will be constant).
2. Method- If you make any method as final, you cannot override it.
3. Class - If you make any class as final, you cannot extend it.

Q.11 Explain Hierarchical Inheritance in java.


Answer- Hierarchical inheritance in Java is a type of inheritance where a
single superclass (parent class) serves as the base class for multiple
subclasses (child classes). In other words, it forms a hierarchy of classes,
where each subclass inherits properties and behaviors from a common
superclass. However, each subclass can also have its own unique properties
and behaviors, in addition to those inherited from the superclass.

Q.12 What is the advantage of exception handling?


Answer- In Java, an exception is an event that disrupts the normal flow of the
program. The Exception Handling in Java is one of the powerful mechanisms
to handle the runtime events so that the normal flow of the application can
be maintained.
Q.13 What is an abstract class in Java?
Answer- An abstract class is a class that cannot be instantiated on its own
and is typically used as a base class for other classes. It serves as a blueprint
for its subclasses, providing common methods and fields that can be shared
among multiple related classes. An abstract class may contain abstract
methods, concrete methods, constructors, and instance variables.

Q.14 How catch block is different from finally block?


Answer- Catch Block: The catch block is used to handle exceptions that are
thrown within the corresponding try block.
When an exception occurs within the try block, the execution of the try block
is interrupted, and the control flow is transferred to the appropriate catch
block that matches the type of the thrown exception.
Finally Block:The finally block is used to define code that should be executed
regardless of whether an exception occurs or not.
Common use cases for the finally block include releasing resources, closing
files or connections, or performing cleanup tasks that should always be
executed, regardless of whether an exception occurs.
Q.15 How we can write concrete methods in an interface in java?
Answer- From Java 8, it became possible to define concrete methods in
interfaces by using default methods and static methods.
A default method is a method defined within an interface with a default
implementation which may or may not be overridden by implementation
class.
A static method in an interface is a method that can be called directly using
the interface name, without needing an instance of a class that implements
the interface. It cannot be overridden.
Q.16 Explain the life cycle of a thread.
Answer- 1. New: When a thread object is created using the new keyword or by
instantiating a class that extends Thread or implements Runnable interface, it is
in the "New" state.
2. Runnable: In this state, the thread is eligible to be scheduled by the Java
Virtual Machine (JVM) for execution.
3. Running: When the thread scheduler selects a thread from the "Runnable"
pool and allocates processor time to it, the thread enters the "Running" state.
4. Blocked/Waiting: A running thread can transition to the "Blocked" or
"Waiting" state due to certain conditions, such as waiting for I/O operations,
synchronization locks, or explicit calls to wait(), sleep(), or join() methods
5. .Terminated: A thread enters the "Terminated" state when its run() method
completes, or if an uncaught exception occurs within the thread.

Q.17 What is the difference between pop() and peek()?


Answer- pop():The pop() method removes and returns the top element of the
stack.After calling pop(), the size of the stack decreases by one, as the top
element is removed.
peek():The peek() method returns the top element of the stack without
removing it.The size of the stack remains unchanged after calling peek().
Q.18 Explain join() method of Thread class.
Answer-the join() method of the Thread class is used to wait for a thread to
finish its execution before proceeding with the execution of the current thread.
It allows one thread to wait until another thread completes its execution. The
syntax of the join() method is:
public final void join() throws InterruptedException
Q.19 Write a short note on StringTokenizer class in java.
Answer-StringTokenizer class in Java is a legacy class used to break a string into
tokens or words based on a specified delimiter. It is part of the java.util package
and is particularly useful for parsing text or splitting strings into smaller
components. This is an example of the StringTokenizer class that tokenizes a
string "Welcome to Java" on the basis of whitespace-
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("Welcome to Java "," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
Output-
Welcome
To
Java

Q.20 Write an example to demonstrate how Scanner can be used to read a file.
Answer- import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileScannerExample {


public static void main(String[] args) {
// Specify the path to the file
String filePath = "example.txt";

try {
// Create a File object representing the file to be read
File file = new File(filePath);

// Create a Scanner object to read from the file


Scanner scanner = new Scanner(file);

// Read and print each line from the file


while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}

// Close the scanner to release resources


scanner.close();
} catch (FileNotFoundException e) {
// Handle file not found exception
System.err.println("File not found: " + filePath);
e.printStackTrace();
}
}
}

Q.21 What is the difference between ByteStream and CharacterStream in java?


Answer- ByteStream handles raw binary data in the form of bytes. It is used for
input and output operations on binary data such as images, audio files, or any
other non-text files. Examples of ByteStream classes include InputStream and
OutputStream and their various subclasses such as FileInputStream,
FileOutputStream, ByteArrayInputStream, and ByteArrayOutputStream.
CharacterStream handles character data, typically in the form of Unicode
characters. It is used for input and output operations on text files or data that
can be represented as characters. Examples of CharacterStream classes include
Reader and Writer and their various subclasses such as FileReader, FileWriter,
BufferedReader, and BufferedWriter.

Q.22 Explain GridLayout in AWT.


Answer- The Java GridLayout class is used to arrange the components in a
rectangular grid. One component is displayed in each rectangle.

Constructors of GridLayout class-

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns along with given horizontal and vertical
gaps.

Q.23 What is the difference between TeatField and TextArea?


Answer- TextField is a single-line input field that allows users to enter text.
It is typically used for short text input, such as usernames, passwords, or search
queries.
TextArea is a multi-line input field that allows users to enter multiple lines of
text.It is suitable for longer text input, such as messages, descriptions, or
comments.
Q.24 What is an event handling in AWT?
Answer- Event handling in AWT (Abstract Window Toolkit) refers to the
mechanism by which Java programs respond to user actions or system-
generated events, such as mouse clicks, key presses, window movements, etc.
AWT provides a framework for handling events in graphical user interfaces
(GUIs) by using event listeners and event objects.

Q.25 What is the purpose of setBounds() method in AWT?


Answer- In AWT (Abstract Window Toolkit), the setBounds() method is used to
set the size and position of a component within its container. It is a method
defined in the Component class, which is the superclass of all AWT components
such as buttons, labels, text fields, etc.
Syntax-
setBounds(int x-coordinate, int y-coordinate, int width, int height)
The setBounds() method takes four parameters:

1. x: The x-coordinate of the component's top-left corner, relative to the


container's top-left corner.
2. y: The y-coordinate of the component's top-left corner, relative to the
container's top-left corner.
3. width: The width of the component, in pixels.
4. height: The height of the component, in pixels.

Part C

Q.1 What is the difference between instance variable and local variable in java.
Answer- Instance Variables:
● Instance variables are declared within a class but outside of any method,
constructor, or block.
● They are also known as member variables or fields.
● Each instance of the class (object) has its own copy of instance variables.
● Instance variables are initialized when an object of the class is created and
can have default values if not explicitly initialized.
● They exist for the entire lifetime of the object.
Example:
public class MyClass {
// Instance variable
int instanceVar = 10;
}
Local Variables:
● Local variables are declared within a method, constructor, or block.
● They are created when the method, constructor, or block is entered and
destroyed when it exits.
● Local variables must be initialized before they are used; otherwise, a
compile-time error occurs.
● They are visible only within the scope in which they are declared.
● Local variables do not have default values and must be explicitly initialized
before being accessed.
Example:
public class MyClass {
public void myMethod() {
// Local variable
int localVar = 20;
System.out.println(localVar);
}
}
In summary, the main differences between instance variables and local variables
lie in their scope, lifetime, and where they are declared. Instance variables
belong to the class and are accessible throughout the class, while local variables
are confined to the method, constructor, or block in which they are declared
and exist only for the duration of that scope.

Q.2 What are different primitive data types available in java?


Answer- In Java, primitive data types are the most basic data types provided by
the language. They represent single values and are not objects. Here are the
different primitive data types available in Java:
1. Integer Types:
● byte: 8-bit signed integer. Range: -128 to 127.
● short: 16-bit signed integer. Range: -32,768 to 32,767.
● int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
● long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.
2. Floating-Point Types:
● float: 32-bit floating-point. Range: approximately
±3.40282347E+38F (6-7 significant decimal digits).
● double: 64-bit floating-point. Range: approximately
±1.79769313486231570E+308 (15 significant decimal digits).
3. Character Type:
● char: 16-bit Unicode character. Range: '\u0000' (0) to '\uffff'
(65,535).
4. Boolean Type:
● boolean: Represents true or false values.
In summary, Java has eight primitive data types: byte, short, int, long, float,
double, char, and boolean. These data types are used to represent different
kinds of numeric values, characters, and boolean values in Java programs.

Q.3 What is the difference between pass by value and pass by reference in java.
Answer- Pass by Value:
When you pass a primitive data type (e.g., int, double, char) to a method in Java,
it's passed by value.
Pass by value means that a copy of the actual value is passed to the method. Any
changes made to the parameter within the method do not affect the original
value outside the method.
Example:
public class PassByValueExample {
public static void main(String[] args) {
int x = 10;
modifyValue(x);
System.out.println(x); // Output: 10
}

public static void modifyValue(int num) {


num = 20;
}
}
Pass by Reference:
In Java, objects are passed by reference. However, it's important to understand
that what's passed by reference is the reference to the object, not the actual
object itself.
This means that changes made to the object's state within the method will affect
the object outside the method because they both refer to the same object in
memory.
Example:
public class PassByReferenceExample {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("Hello");
modifyStringBuilder(str);
System.out.println(str); // Output: Hello World
}

public static void modifyStringBuilder(StringBuilder s) {


s.append(" World");
}
}
In summary, Java always passes arguments by value. However, for non-primitive
types (objects), what gets passed by value is the reference to the object, not the
object itself.

Q.4 What are the different ways of performing String comparison?


Answer-
1. Using equals() method:
This method compares the content of two strings and returns true if they are
equal, false otherwise.
Example:
String str1 = "Hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("Strings are equal");
}
2. Using equalsIgnoreCase() method:
This method compares the content of two strings ignoring their case
(uppercase/lowercase).
Example:
String str1 = "hello";
String str2 = "HELLO";
if (str1.equalsIgnoreCase(str2)) {
System.out.println("Strings are equal ignoring case");
}
3. Using compareTo() method:
● This method compares two strings lexicographically (dictionary order) and
returns an integer.
● Returns a negative integer if the first string comes before the second
string.
● Returns zero if the strings are equal.
● Returns a positive integer if the first string comes after the second string.
Example:
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
if (result < 0) {
System.out.println("str1 comes before str2");
} else if (result > 0) {
System.out.println("str1 comes after str2");
} else {
System.out.println("str1 and str2 are equal");
}
4. Using compareToIgnoreCase() method:
This method compares two strings lexicographically ignoring their case.
Example:
String str1 = "Apple";
String str2 = "banana";
int result = str1.compareToIgnoreCase(str2);
if (result < 0) {
System.out.println("str1 comes before str2");
} else if (result > 0) {
System.out.println("str1 comes after str2");
} else {
System.out.println("str1 and str2 are equal");
}
5. Using == operator:
This operator checks if two string references point to the same object in
memory.
It does not compare the content of the strings.
Example:
String str1 = "Hello";
String str2 = "Hello";
if (str1 == str2) {
System.out.println("Strings are equal");
}

Q.5 How multiple inheritance can be be implemented in java using interfaces?


Answer- In Java, multiple inheritance can be achieved using interfaces. There are
2 ways to achieve this-
1. Unlike classes, where a class can only extend one other class (single
inheritance), a class can implement multiple interfaces. This allows a Java
class to inherit behaviors from multiple sources, effectively achieving
multiple inheritance.

Here's an example demonstrating how multiple inheritance can be implemented


using interfaces in Java:

// Interface 1
interface Animal {
void eat();
void sleep();
}

// Interface 2
interface Mammal {
void run();
}
// Concrete class implementing multiple interfaces
class Dog implements Animal, Mammal {
@Override
public void eat() {
System.out.println("Dog is eating");
}
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
@Override
public void run() {
System.out.println("Dog is running");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Output: Dog is eating
myDog.sleep(); // Output: Dog is sleeping
myDog.run(); // Output: Dog is running
}
}
2. In Java, an interface can extend multiple interfaces, allowing for a form of
multiple inheritance at the interface level. This feature enables the
creation of interfaces that inherit methods from more than one parent
interface. Let's illustrate this with an example:

// Interface 1
interface Flyable {
void fly();
}
// Interface 2
interface Swimmable {
void swim();
}
// Interface extending multiple interfaces
interface Bird extends Flyable, Swimmable {
void chirp();
}
// Concrete class implementing the Bird interface
class Sparrow implements Bird {
@Override
public void fly() {
System.out.println("Sparrow is flying");
}

@Override
public void swim() {
System.out.println("Sparrow is swimming");
}
@Override
public void chirp() {
System.out.println("Sparrow is chirping");
}
}

public class Main {


public static void main(String[] args) {
Sparrow sparrow = new Sparrow();
sparrow.fly(); // Output: Sparrow is flying
sparrow.swim(); // Output: Sparrow is swimming
sparrow.chirp(); // Output: Sparrow is chirping
}
}

Q.6 How to create custom exception in java?


Answer- In Java, you can create custom exceptions by extending either the
Exception class or one of its subclasses, such as RuntimeException. Here's a step-
by-step guide to creating a custom exception:

1. Create a new Java class for your custom exception:


● You should define your custom exception as a subclass of Exception or
any of its subclasses.
● It's a convention to end the name of your custom exception with
"Exception" to make it clear that it's an exception class.
2. Define constructors:
● Provide constructors that allow you to initialize the exception with a
message and optionally with a cause (another exception that caused
this exception to be thrown).
Here's an example demonstrating the creation of a custom exception named
InvalidAgeException:
// Custom exception class
class InvalidAgeException extends Exception {
// Constructor with a message
public InvalidAgeException(String message) {
super(message);
}

// Constructor with a message and a cause


public InvalidAgeException(String message, Throwable cause) {
super(message, cause);
}
}

// Example usage
class MyClass {
// Method that throws the custom exception
public void validateAge(int age) throws InvalidAgeException {
if (age < 0 || age > 120) {
throw new InvalidAgeException("Age must be between 0 and 120");
}
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
try {
obj.validateAge(150);
} catch (InvalidAgeException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
}
}
In the above example:
● We create a custom exception class InvalidAgeException that extends
Exception.
● We provide two constructors: one that accepts a message and one that
accepts both a message and a cause.
● Inside the validateAge method of MyClass, we throw an
InvalidAgeException if the age is not within the valid range.
● In the main method, we catch and handle the InvalidAgeException if it
occurs during the execution of validateAge.
● By following this approach, you can create custom exceptions tailored
to your specific application requirements.

Q.7 Explain synchronization in multithreading.


Answer- In Java, synchronization is a mechanism provided by the language to
control access to shared resources by multiple threads, ensuring that only one
thread can access the resource at a time. This prevents race conditions and
maintains data consistency.

There are several ways to achieve synchronization in Java:


1. Synchronized Methods:
You can declare a method as synchronized to ensure that only one thread
can execute it at a time.
When a thread enters a synchronized method, it acquires the intrinsic lock
(also known as monitor lock) associated with the object the method belongs
to. Other threads attempting to execute synchronized methods on the same
object will be blocked until the lock is released.
Example:
class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}
}
2. Synchronized Blocks:
You can use synchronized blocks to restrict access to specific sections of code
rather than entire methods.
Synchronized blocks require an object reference or class literal to
synchronize on.
Example:
class Example {
private final Object lock = new Object();

public void someMethod() {


synchronized (lock) {
// Critical section
}
}
}

Q.8 Explain Vector class.


Answer- In Java, the Vector class is a part of the Java Collections Framework and
is present in the java.util package. It represents a dynamic array that can
dynamically grow and shrink as elements are added or removed. Vector is
similar to an ArrayList, but it's synchronized, meaning it's thread-safe.

Here are some key features of the Vector class:

● Dynamic Size: Like an ArrayList, a Vector automatically grows and shrinks


in size as elements are added or removed. You don't need to specify its
size explicitly.
● Synchronization: Unlike ArrayList, which is not synchronized by default,
Vector is synchronized. This means that multiple threads can safely
manipulate a Vector instance without explicit synchronization from the
programmer. However, this synchronization comes with some
performance overhead.
● Enumeration: Vector provides an enumeration interface (Enumeration) to
iterate over its elements. This interface is similar to an iterator but is less
flexible.
● Legacy: Vector was one of the original collection classes in Java and has
been available since the early versions of Java. It predates the Collections
Framework introduced in Java 2 (JDK 1.2).
● Commonly used methods-
1. Adding Elements:
▪ add(E e): Appends the specified element to the end of the
vector.
▪ add(int index, E element): Inserts the specified element at
the specified position in the vector.
2. Accessing Elements:
▪ get(int index): Returns the element at the specified index in
the vector.
▪ elementAt(int index): Returns the element at the specified
index in the vector (similar to get method).
▪ firstElement(): Returns the first element of the vector.
▪ lastElement(): Returns the last element of the vector.
3. Removing Elements:
▪ remove(int index): Removes the element at the specified
index from the vector.
▪ remove(Object o): Removes the first occurrence of the
specified element from the vector.
4. Checking Size and Capacity:
▪ size(): Returns the number of elements in the vector.
▪ capacity(): Returns the current capacity of the vector.
5. Checking Vector State:
▪ isEmpty(): Returns true if the vector is empty; otherwise,
returns false.
6. Searching Elements:
▪ contains(Object o): Returns true if the vector contains the
specified element; otherwise, returns false.

Q.9 Write methods to write data to a file and read data from file using FileWriter
and FileReader class.
Answer-
static void writeData() {
FileWriter out=null;
try {
out=new FileWriter("abc.txt");
out.write("Welcome to java");
System.out.println("File created");

} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

static void readData() {


FileReader in=null;
try {
in=new FileReader("abc.txt");
int i;
in.close();
while((i=in.read())!=-1)
{
System.out.print((char)i);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Q.10 Differentiate between containers and components in AWT java.


Answer- In Java's Abstract Window Toolkit (AWT), both containers and
components play vital roles in creating graphical user interfaces (GUIs). Here's
how they differ:

1. **Containers:**
- **Definition:** Containers are components that can contain and organize
other components within them. They provide a layout structure for arranging
and managing the placement of components.
- **Functionality:** Containers manage the layout and positioning of
components according to a specified layout manager. They handle the visual
representation of the GUI, including the size, position, and visibility of contained
components.
- **Types:** AWT provides several types of containers, such as Frame,
Window, Panel, Dialog, and Applet. Each type serves a specific purpose and may
have its own unique properties and behavior.
- **Example:** In AWT, a Frame is a top-level container that represents a
window in a GUI application. It can contain various components like buttons,
labels, text fields, etc., arranged within its layout.

2. **Components:**
- **Definition:** Components are the building blocks of GUIs. They represent
the visual elements that users interact with, such as buttons, labels, text fields,
checkboxes, etc.
- **Functionality:** Components provide specific functionality or display
information to the user. They can respond to user input events like mouse clicks,
key presses, or focus changes.
- **Types:** AWT offers a wide range of components for creating GUIs,
including Button, Label, TextField, TextArea, Checkbox, Choice, and many more.
Each component has its own set of properties and methods for customization
and interaction.
- **Example:** A Button component in AWT represents a clickable button that
users can interact with by clicking on it. It can have text or an icon and can trigger
actions or events when clicked.

In summary, containers provide structure and organization for arranging


components within a GUI, while components represent the actual visual
elements that users interact with. Together, containers and components form
the foundation of AWT GUI programming in Java.

You might also like