KEMBAR78
JAVA Important Questions and Answers | PDF | Class (Computer Programming) | Programming
0% found this document useful (0 votes)
19 views24 pages

JAVA Important Questions and Answers

Very good source

Uploaded by

sourabh sarkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

JAVA Important Questions and Answers

Very good source

Uploaded by

sourabh sarkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

JAVA important questions

1. What is the difference between Object Oriented Programming language and object based
programming language.
2. What are Access Specifiers available in Java?
3. What is the difference between abstraction and encapsulation?
4. How do you prevent a method from being overridden?
5. What is garbage collection?
6. Why java does not support pointers?
7. Explain the usage of Java packages. Why do we need to use package in Java? How to create a
package in Java?
8. Differentiate between method overloading and method overriding. Write a program to implement
the Fibonacci series using for loop control structure.
9. What is an Interface? How can you achieve multiple inheritances in java? Explain with a
suitable example.
10. What is the difference between static and non-static variables? What is this keyword?
Explain with example.
11. Can I import same package/class twice? Justify. Will the JVM load the package twice at runtime?
12. Differentiate between Interface and abstract class.
13. Explain Casting in Java and its types.
14. Illustrate the use cases of final keyword.
15. When you declare a method as abstract, can other nonabstract methods access it? Justify.
16. Can we have a method with the same name as class and how it is different from constructor?
17. Differentiate between checked and unchecked exceptions in Java.
18. Explain CRUD operations in Java.
19. Define Autoboxing and Unboxing.
20. Define the output of the following Java code
21. class multithreaded_programing
{
public static void main(String args[])
{
}
Thread t= Thread.currentThread ();
System.out.println (t);
}
22. Distinguish between == and equals () method.
23. State object cloning and its need.
24. Explain the thread synchronization in Java. Why is it necessary, and how is it achieved?
25. Write the difference between static variable and final variable in Java.
26. Explain indexOf() and lastIndexOf() with a suitable example.
27. Briefly discuss various features of Object-Oriented Programming. Write a Java program to find
factorial of a Number.
28. Derive the advantages of ArrayList over Arrays. Design an ArrayList called CGU_Subjects: [Java,
Machine Learning, Database], add the elements DAA, DL to the ArrayList and display the final
ArrayList as CGU_Subjects: [Java, Machine Learning, DAA, DL, Database].
29. Define Super Keyword and its need. Illustrate the implementation of multilevel Inheritance using
Super keyword with a suitable example.
30. Explain the different stages of the thread life cycle in Java. Explain the concept of thread priorities
in Java.
31. Write short notes on-
i. Callable Statement in JDBC
ii. Clone ()
iii. Thin Driver
32. Write a program to demonstrate the knowledge of students in advanced concepts of Java string
handling. Eg., (Bioinformatics: finding genes) Biologists use a sequence of letters A, C, T, and G to
model a genome. A gene is a substring of a genome that starts after a triplet ATG and ends before
a triplet TAG, TAA, or TGA. Furthermore, the length of a gene string is a multiple of 3 and the gene
does not contain any of the triplets ATG, TAG, TAA, and TGA. Prompt the user to enter a genome
and displays all genes in the genome. If no gene is found in the input sequence, displays no gene.
Here are the sample runs: Enter a genome string: TTATGTTTTAAGGATGGGGCGTTAGTT
O/P: TTT GGGCGT.

33. Differentiate between constructor and method. Explain constructor overloading with a
suitable example.
34. Write a Java program to solve the given problem statement of CGU_Banking_System.

35. The CGU_Banking_System contains a Bank class with two methods, transfer() and
credit(). The transfer() method transfers money from one account to another, and the
credit() method adds money to an account. Both methods use synchronized blocks to
ensure thread safety. Now, suppose we have two threads, Thread A and Thread B, each
trying to transfer money between two accounts in the bank. Thread A calls the transfer ()
method with account A and account B as arguments, and Thread B calls the transfer ()
method with account B and account A as arguments. If Thread A acquires the lock on
account A and Thread B acquires the lock on account B, both threads will be blocked,
waiting for the lock on the other account to be released.

36. Suppose we have two classes named "Engine" and "Wheels". The Engine class contains
methods to start, stop and maintain the engine, while the Wheels class contains methods to
rotate the wheels, change the tire pressure, and control the brakes. Now, let's assume that
we have a class named "Car" that we want to create by inheriting properties and methods
from both the Engine and Wheels classes.

37. Suppose we have a class named "CGU_Match" which contains the following methods:
getMatch Details(): This method will return the match details such as the team names,
venue, date, and time of the match.
getMatch Details(team1: String, team2: String): This method will return the match details
for a specific match between two teams.
getMatch Details (team: String, venue: String): This method will return the match details
for a specific match played at a particular venue.
getMatch Details(team: String, date: String): This method will return the match details for
a specific match played on a particular date.
getMatch Details (team: String, time: String): This method will return the match details for
a specific match played at a particular time.
For instance, if we call the method getMatch Details() without any arguments, it will return
the details of the most recent match played. However, if we pass the team names as
arguments to the method, it will return the details of the match between those two teams.
Similarly, if we pass the venue, date, or time as an argument, the method will return the
details of the match played at that particular venue, on that particular date or at that
particular time.

38. Describe character stream in Java. Assume in Drive D: two text files are
there(D:\javaprg.txt, D:\javaout.txt). The "javaprg.txt" contains pre-existing test as 4 java
program is best among all". WAP in Java to copy the content of "javaprg.txt" to
"javaout.txt" using FileInputStream and FileOutputStream.

39. Explain the concept of JDBC in Java. Differentiate between Statement and
PreparedStatement interfaces. How can you connect to a database using JDBC?

40. Write a program to create a user defined Package named Engineering which has one class
Student. Accept student detail (Reg.no, Name, Branch, Marks of 5 subject (Data Structure,
Math, Computer networking, Computer Architecture, Operating System) through
parameterized constructor. Write display () method to display details. Create a main class
which will use package and calculate total marks and percentage.

Answers

1. Difference between Object-Oriented Programming Language and Object-


Based Programming Language

Object-Oriented Programming (OOP) Languages:

 Supports all OOP features: Encapsulation, Inheritance, Polymorphism, and


Abstraction.
 Examples: Java, C++, C#, Python.
 Inheritance: Allows the creation of new classes that reuse, extend, and modify the
behavior defined in other classes.

Object-Based Programming Languages:

 Do not support all OOP features: Specifically, they do not support inheritance and
polymorphism.
 Examples: JavaScript (though modern versions now support a form of inheritance),
Visual Basic.
 Limited in creating hierarchical classifications: Since there's no inheritance, objects
can be created but without the advantage of reusing the common logic.
2. Access Specifiers available in Java

Java has four access specifiers:

 private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
 default (no modifier): If no access specifier is defined, Java assumes a default access
level, which means it is accessible within the same package.
 protected: The protected access level provides access to the class itself, its package, and
its subclasses.
 public: The public access level means that the class, method, or field is accessible from
any other class.

3. Difference between Abstraction and Encapsulation

Abstraction:

 Hides the complex implementation details and shows only the necessary features of
the object.
 It focuses on what the object does.
 Achieved using abstract classes and interfaces.

Encapsulation:

 Binds (encapsulates) the data and the code that manipulates the data into a single
unit called class.
 It focuses on keeping the data safe from outside interference and misuse.
 Achieved using access modifiers (private, public, protected).

4. Preventing a Method from Being Overridden

In Java, you can prevent a method from being overridden by using the final keyword in the
method declaration. For example:

java
Copy code
class SuperClass {
public final void show() {
System.out.println("This method cannot be overridden.");
}
}

5. What is Garbage Collection?

Garbage collection is the process of automatically freeing memory on the heap by deleting
objects that are no longer reachable in your program. In Java, garbage collection is managed by
the Java Virtual Machine (JVM), which removes objects from memory when they are no longer
in use, thus preventing memory leaks and inefficient use of resources.

6. Why Java Does Not Support Pointers

Java does not support pointers (in the sense of memory addresses that can be manipulated as in
languages like C or C++) for several reasons:

 Security: Direct access to memory can lead to vulnerabilities where malicious code
could manipulate memory addresses, leading to unauthorized access or corruption of
data.
 Simplicity: By abstracting away the complexity of pointers, Java simplifies
programming and reduces errors related to memory management.
 Garbage Collection: Java's garbage collection relies on being able to know exactly
which objects are still in use. Pointers would complicate this process, potentially leading
to memory leaks or other issues.

7. Java Packages

Usage and Benefits:

 Namespace Management: Helps in organizing classes, interfaces, enumerations, and


annotations.
 Access Protection: Provides access control through access specifiers.
 Avoid Naming Conflicts: By prefixing the class name with a package name, it helps in
distinguishing the classes.

Creating a Package in Java: To create a package in Java, use the package keyword followed
by the package name at the top of your Java source file. For example:

java
Copy code
package com.example.myapp;

public class MyClass {


// Class content
}

To compile: javac -d . MyClass.java (This will place the compiled class in the correct
directory structure)
8. Method Overloading vs Method Overriding

Method Overloading:

 Occurs within the same class.


 Methods must have the same name but different parameter lists (different type, number,
or both).
 It is a compile-time polymorphism.

Method Overriding:

 Occurs in two classes that have an IS-A (inheritance) relationship.


 Method in the child class has the same name, return type, and parameters as in the parent
class.
 It is runtime polymorphism.

Fibonacci Series Program:

java
Copy code
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series till " + n + " terms:");

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


System.out.print(firstTerm + ", ");

// compute the next term


int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

9. Interface and Multiple Inheritances in Java

An interface in Java is a reference type that can contain only constants, method signatures,
default methods, static methods, and nested types. Interfaces cannot contain instance fields. The
methods in interfaces are abstract by default.

Java does not support multiple inheritances with classes to avoid the "Diamond Problem."
However, it supports multiple inheritances through interfaces. A class can implement multiple
interfaces, thereby inheriting the abstract methods of multiple interfaces.
Example:

java
Copy code
interface InterfaceA {
void methodA();
}

interface InterfaceB {
void methodB();
}

class MyClass implements InterfaceA, InterfaceB {


public void methodA() {
System.out.println("Implementing methodA");
}

public void methodB() {


System.out.println("Implementing methodB");
}
}

10. Static vs Non-static Variables and this Keyword

Static Variables:

 Belong to the class, not instances of the class.


 There is only one copy of a static variable for all objects of the class.
 Accessed using the class name.

Non-static Variables (Instance Variables):

 Each instance (object) of the class has its own copy.


 Accessed through object references.

this Keyword:

 Refers to the current object in a method or constructor.


 Useful for distinguishing between class fields and parameters with the same name.
 Example:

java
Copy code
public class ExampleClass {
int instanceVar;

ExampleClass(int instanceVar) {
this.instanceVar = instanceVar; // Using 'this' to refer to the
instance variable
}
}
Let's continue with the detailed responses to your questions:

11. Can I Import the Same Package/Class Twice? Will the JVM Load the
Package Twice at Runtime?

You can technically import the same package or class more than once in your Java source file,
but the Java compiler and JVM are smart enough to recognize and ignore redundant imports.
This means that the JVM will not load the package or class twice at runtime. Import statements
are primarily for the compiler to locate and reference the classes you're using in your code. Once
compiled, the bytecode contains fully qualified class names, and the import statements have
served their purpose.

12. Differentiate Between Interface and Abstract Class

Interface:

 Cannot have any concrete methods (Java 8 and earlier). Java 8 onwards, interfaces can
have default and static concrete methods.
 All fields are public, static, and final by default.
 A class can implement multiple interfaces, supporting multiple inheritance.
 Used to define a contract for what a class can do, without saying anything about how the
class will do it.

Abstract Class:

 Can have both abstract and concrete methods.


 Can contain fields with any visibility (private, protected, public).
 A class can extend only one abstract class due to single inheritance in Java.
 Used when you want to share code among several closely related classes.

13. Explain Casting in Java and Its Types

Casting in Java is the process of converting a value from one data type to another. There are two
types of casting:

Implicit Casting (Widening Conversion):

 Automatically done by the JVM.


 Occurs when assigning a value of a smaller data type to a larger data type (e.g., int to
long).

java
Copy code
int myInt = 9;
long myLong = myInt; // Implicit casting
Explicit Casting (Narrowing Conversion):

 Must be done manually by the programmer.


 Occurs when assigning a value of a larger data type to a smaller data type (e.g., double to
int).

java
Copy code
double myDouble = 9.78;
int myInt = (int) myDouble; // Explicit casting

14. Illustrate the Use Cases of the final Keyword

The final keyword in Java can be used in several contexts:

 Final Variables: When applied to variables, final makes the variable unchangeable
after it's initialized.

java
Copy code
final int MY_CONSTANT = 100;

 Final Methods: A final method cannot be overridden by subclasses.

java
Copy code
public final void myFinalMethod() {}

 Final Classes: A final class cannot be extended.

java
Copy code
public final class MyFinalClass {}

15. Can Other Non-Abstract Methods Access an Abstract Method?

Yes, non-abstract methods in an abstract class can access abstract methods. Abstract methods act
as placeholders for methods that must be implemented in non-abstract subclasses. Non-abstract
methods can invoke abstract methods, expecting that the subclass will provide the concrete
implementation.

java
Copy code
abstract class MyAbstractClass {
abstract void myAbstractMethod();

void myConcreteMethod() {
myAbstractMethod(); // Calling an abstract method
}
}
16. Can We Have a Method With the Same Name as the Class? How Is It
Different From a Constructor?

Yes, you can have a method with the same name as the class, but it's generally not recommended
due to readability and convention reasons. However, this method must have a return type,
distinguishing it from a constructor, which does not have a return type.

 Method with the Same Name as Class:

java
Copy code
public class MyClass {
void MyClass() { // This is a method, not a constructor
System.out.println("This is a method, not a constructor.");
}
}

 Constructor:

java
Copy code
public class MyClass {
MyClass() { // This is a constructor
System.out.println("This is a constructor.");
}
}

Constructors are special methods used to initialize new objects. They are called when an instance
of the class is created, and they have the same name as the class but no return type, not even
void.

17. Differentiate Between Checked and Unchecked Exceptions in Java

In Java, exceptions are divided into two main categories: checked and unchecked exceptions.

Checked Exceptions:

 Are checked at compile-time.


 Must be either caught or declared in the method signature using throws.
 Extends Exception (except RuntimeException and its subclasses).
 Represents conditions that a reasonable application might want to catch.
 Example: IOException, SQLException.

java
Copy code
import java.io.*;

public class CheckedExample {


public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream("nonexistent.txt");
}
}

Unchecked Exceptions:

 Are not checked at compile-time but at runtime.


 Extends RuntimeException.
 Represents problems that are the result of a programming error, like accessing a null
pointer or out-of-bounds array indexing.
 Do not need to be declared in a method's throws clause.
 Example: NullPointerException, ArrayIndexOutOfBoundsException.

java
Copy code
public class UncheckedExample {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
}
}

18. Explain CRUD Operations in Java

CRUD stands for Create, Read, Update, and Delete. These are the four basic functions of
persistent storage (e.g., databases).

 Create: Inserting new records into the database.


 Read: Retrieving or reading information from the database.
 Update: Modifying existing records in the database.
 Delete: Removing records from the database.

In Java, CRUD operations are typically performed using JDBC (Java Database Connectivity) for
relational databases or through libraries/frameworks like JPA (Java Persistence API), Hibernate
for both SQL and NoSQL databases.

19. Define Autoboxing and Unboxing

Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to an
Integer, a double to a Double, etc.

java
Copy code
Integer myInteger = 25; // Autoboxing from int to Integer

Unboxing is the reverse process of converting an object of a wrapper type to its corresponding
primitive type.
java
Copy code
int myInt = myInteger; // Unboxing from Integer to int

20. Define the Output of the Following Java Code


java
Copy code
class multithreaded_programing {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println(t);
}
}

This code snippet will print details about the current thread executing the main method. The
output will include the name of the thread (typically "main"), its priority, and the thread group it
belongs to, in a format similar to:

Copy code
Thread[main,5,main]

This indicates that the thread's name is "main", its priority is 5, and it belongs to the "main"
thread group.

21. Distinguish Between == and equals() Method

 == is a reference comparison operator. It checks if two references point to the same object
in the memory. It is used for primitive data types and reference comparisons.

java
Copy code
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2); // false, because two different String
objects are created.

 equals() method is defined in Object class in Java and it is used for checking logical
equality of two objects. Classes can override equals() method to check if two instances
are logically equal.

java
Copy code
System.out.println(str1.equals(str2)); // true, because `equals()` checks the
content equality.
22. State Object Cloning and Its Need

Object cloning in Java is the process of creating an exact copy of an object. It is achieved using
the clone() method of the Object class. Cloning is needed when you want to duplicate an
existing object to modify the original or the copy without affecting the other.

To use cloning, a class must implement the Cloneable interface and override the clone()
method from the Object class.

java
Copy code
class Example implements Cloneable {
int a;

public Object clone()throws CloneNotSupportedException{


return super.clone();
}
}

Cloning can be shallow (default) or deep, depending on whether the object references inside are
copied or also cloned.

Continuing with the detailed explanations:

23. Explain the Thread Synchronization in Java. Why Is It Necessary, and How
Is It Achieved?

Thread Synchronization in Java: Thread synchronization is a mechanism that ensures two or


more concurrent threads do not simultaneously execute some particular program segment known
as critical section. Its primary purpose is to prevent race conditions when threads access shared
resources.

Necessity:

 To prevent thread interference and memory consistency errors.


 Ensures that only one thread can access the resource at a given point of time, maintaining
data integrity and consistency.

How It Is Achieved:

 Synchronized Methods: By declaring methods with the synchronized keyword. This


locks the object for any synchronized method.

java
Copy code
public synchronized void method() {
// critical section
}
 Synchronized Blocks: More fine-grained than synchronized methods. They allow
locking for any object, providing flexibility in the choice of the lock.

java
Copy code
public void method() {
synchronized(this) {
// code block
}
}

 Static Synchronization: When you synchronize a static method, you lock the class, not
the object.

24. Write the Difference Between Static Variable and Final Variable in Java

Static Variable:

 Belongs to the class rather than any instance of the class (object).
 Initialized only once, at the start of the execution and will be destroyed at the end of the
execution.
 A static variable can be changed by the user.

Final Variable:

 Once assigned a value, it cannot be changed, essentially making it a constant.


 A final variable can be initialized when it is declared or in the constructor of the class in
which it is declared.
 It’s not necessary to initialize at the time of declaration.

25. Explain indexOf() and lastIndexOf() with a Suitable Example

The indexOf() method in Java is used to return the index within the calling String object of the
first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is
not found.

The lastIndexOf() method returns the index within the calling String object of the last
occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value
is not found.

java
Copy code
String example = "This is a test string";
int index = example.indexOf('i'); // Returns 2, the first occurrence of 'i'
int lastIndex = example.lastIndexOf('i'); // Returns 13, the last occurrence
of 'i'
26. Briefly Discuss Various Features of Object-Oriented Programming. Write a
Java Program to Find Factorial of a Number

Features of Object-Oriented Programming:

 Encapsulation: The bundling of data, along with the methods that operate on that data,
into a single unit or class.
 Inheritance: The mechanism wherein a new class is derived from an existing class.
 Polymorphism: The ability of a single function or method to work in different ways
based on the input.
 Abstraction: The concept of hiding complex implementation details and showing only
the necessary features of an object.

Java Program to Find Factorial of a Number:

java
Copy code
public class Factorial {
public static void main(String[] args) {
int number = 5; // Example number
int factorial = 1;
for(int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
}

27. Derive the Advantages of ArrayList over Arrays

Advantages of ArrayList over Arrays:

 Dynamic Sizing: ArrayList can dynamically grow and shrink after addition and
removal of elements. In contrast, arrays are fixed in size.
 API Methods: ArrayList offers more methods and features, such as add(), remove(),
indexOf(), etc., making it easier to work with.
 Type Safety: ArrayList can be made type-safe using generics, providing compile-time
type checking and reducing runtime errors.

Example of Using ArrayList:

java
Copy code
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> cguSubjects = new ArrayList<>();
cguSubjects.add("Java");
cguSubjects.add("Machine Learning");
cguSubjects.add("Database");

cguSubjects.add(2, "DAA"); // Adds DAA before Database


cguSubjects.add(3, "DL"); // Adds DL before Database

System.out.println("CGU_Subjects: " + cguSubjects);


}
}

28. Define Super Keyword and Its Need. Illustrate the Implementation of
Multilevel Inheritance Using Super Keyword with a Suitable Example

Super Keyword: The super keyword in Java is a reference variable that is used to refer to the
immediate parent class object. It is used to access:

 Parent class methods


 Parent class constructor
 Parent class instance variables

Need for super:

 To avoid naming conflicts between the base and derived classes.


 To explicitly call the superclass’s methods or constructor.

Multilevel Inheritance Example Using super:

java
Copy code
class Grandparent {
void display() {
System.out.println("Grandparent class.");
}
}

class Parent extends Grandparent {


void display() {
super.display(); // Calls Grandparent's display method
System.out.println("Parent class.");
}
}

class Child extends Parent {


void display() {
super.display(); // Calls Parent's display method
System.out.println("Child class.");
}
}

public class TestInheritance {


public static void main(String[] args) {
Child child = new Child();
child.display(); // Displays Grandparent, Parent, and Child class
messages
}
}

29. Explain the Different Stages of the Thread Life Cycle in Java. Explain the
Concept of Thread Priorities in Java.

Thread Life Cycle in Java:

1. New: When a thread is created, it is in the new state. It remains in this state until the program
starts the thread.
2. Runnable: A thread enters the runnable state either after being started with the start()
method or when it is reactivated from a paused state. In this state, a thread might be running or
ready to run at any instant of time.
3. Blocked: A thread can enter this state because it is waiting for a monitor lock to enter a
synchronized block/method or reenter a synchronized block/method after calling wait().
4. Waiting: A thread transitions to this state because of calling wait() (without timeout), join()
(without timeout), or LockSupport.park(). It will remain in this state until some other thread
calls notify() or notifyAll() on the object.
5. Timed Waiting: A thread is in this state when it calls a method with a time-out parameter like
sleep(long millis), wait(long timeout), join(long millis), or
LockSupport.parkNanos().
6. Terminated: A thread enters this state when it completes its execution or due to an unexpected
exception.

Thread Priorities in Java:

Thread priorities in Java help the scheduler determine when each thread should run. Java
provides a default priority of 5 (defined by Thread.NORM_PRIORITY) and allows for a range of
priorities from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10). Threads with higher
priority are generally executed in preference to threads with lower priority. However, thread
scheduling is not guaranteed and is dependent on the JVM and underlying operating system.

30. Write Short Notes on:

i. Callable Statement in JDBC

A CallableStatement is used in JDBC to call stored procedures from the database. Unlike
Statement and PreparedStatement, which execute regular SQL queries, CallableStatement
can execute stored procedures, which can return results and accept parameters both as input ( IN),
output (OUT), and both (INOUT).
ii. Clone ()

The clone() method creates and returns a copy of the object. The default implementation in the
Object class is a shallow copy. To use clone(), a class must implement the Cloneable
interface, otherwise, it throws CloneNotSupportedException. For a deep copy, you must
override clone() and manually copy the deeply nested objects.

iii. Thin Driver

A thin driver is a type of JDBC driver that provides a direct connection to a database server by
converting JDBC calls directly into the vendor-specific database protocol. This means that,
unlike thick drivers, thin drivers do not require additional software on the client side. Thin
drivers are fully written in Java and are platform-independent, making them a popular choice for
web applications.

31. Write a Program to Demonstrate the Knowledge of Students in Advanced


Concepts of Java String Handling
java
Copy code
import java.util.Scanner;

public class GenomeFinder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a genome string: ");
String genome = scanner.nextLine();
boolean geneFound = false;

int start = 0;
while ((start = genome.indexOf("ATG", start)) != -1) {
int end = genome.indexOf("TAG", start + 3);
if (end == -1) end = genome.indexOf("TAA", start + 3);
if (end == -1) end = genome.indexOf("TGA", start + 3);
if (end != -1 && (end - start) % 3 == 0) {
String gene = genome.substring(start + 3, end);
System.out.println(gene);
geneFound = true;
start = end + 3;
} else {
start += 3;
}
}
if (!geneFound) {
System.out.println("No gene found.");
}
}
}

This program prompts the user to enter a genome sequence and displays all genes based on the
specified criteria. If no gene is found, it displays "No gene found."
32. Differentiate Between Constructor and Method. Explain Constructor
Overloading with a Suitable Example

Constructor vs. Method:

 Constructor:
o Used to initialize the state of an object.
o Has no return type, not even void.
o Automatically called when an instance of the class is created.
o Must have the same name as the class itself.
 Method:
o Used to expose the behavior of an object.
o Must have a return type.
o Needs to be called explicitly.
o Can have any name.

Constructor Overloading Example:

java
Copy code
public class Rectangle {
private int length;
private int breadth;

// Constructor with no parameter


public Rectangle() {
this.length = 0;
this.breadth = 0;
}

// Constructor with two parameters


public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}

public int getArea() {


return this.length * this.breadth;
}

public static void main(String[] args) {


Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle(10, 20);

System.out.println("Area of rect1: " + rect1.getArea()); // 0


System.out.println("Area of rect2: " + rect2.getArea()); // 200
}
}

Constructor overloading allows a class to have more than one constructor that differs in
parameter lists. It enables the class to be initialized in different ways.
Certainly! Here are the answers with proper numbering as per the questions:

33. Differentiate between constructor and method.

Constructor:

 A constructor is a special type of method in Java that is used to initialize objects.


 It has the same name as the class in which it resides.
 A constructor is called automatically when a new instance of an object is created.
 Constructors do not have a return type, not even void.

Method:

 A method is a block of code that performs a specific task.


 It is defined within a class and can be called or invoked anywhere after it has been
declared.
 Methods can have any name, different from the class name.
 Methods must have a return type. If no data is returned, the void keyword is used.

Constructor Overloading: Constructor overloading in Java is a technique where a class can


have more than one constructor that differ in parameters. It allows the creation of multiple
constructors with different initializations.

Example:

java
Copy code
class Box {
double width, height, depth;

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified


Box() {
width = height = depth = 0;
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

34. Write a Java program to solve the given problem statement of


CGU_Banking_System.
java
Copy code
class Bank {
public void transfer(Account from, Account to, double amount) {
synchronized (from) {
synchronized (to) {
if (from.getBalance() >= amount) {
from.withdraw(amount);
to.deposit(amount);
}
}
}
}

public synchronized void credit(Account account, double amount) {


account.deposit(amount);
}
}

35. Solving Thread Deadlock in CGU_Banking_System

To solve the deadlock, we can ensure that locks on accounts are acquired in a consistent order,
thus avoiding the circular wait condition.

36. Inheriting Properties from Multiple Classes in Java

Java does not support multiple inheritance directly due to the Diamond Problem. However, you
can achieve this using interfaces or composition.

37. CGU_Match Class with Overloaded Methods


java
Copy code
class CGU_Match {
// Overloaded methods here
}

38. Character Stream in Java

Character streams in Java are used to perform input and output of characters. They use Unicode
and are thus text-based.
Copy Content Example:

java
Copy code
import java.io.*;

public class CopyFile {


public static void main(String[] args) throws IOException {
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("D:\\javaprg.txt");
out = new FileWriter("D:\\javaout.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

39. JDBC in Java

JDBC (Java Database Connectivity) is an API that enables Java programs to execute SQL
statements. This allows Java applications to interact with a database.

Statement vs. PreparedStatement:

 Statement is used for executing a simple SQL query. It is not precompiled, and the query
is compiled every time it is executed.
 PreparedStatement is used for executing precompiled SQL queries. This improves
performance, especially for queries executed multiple times. It also provides features to
prevent SQL injection through parameterized queries.

Connecting to a Database using JDBC:

java
Copy code
import java.sql.*;

public class TestJDBC {


public static void main(String[] args) {
try {
// Load the driver class
Class.forName("com.mysql.jdbc.Driver");

// Establish connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "password");

// Create statement
Statement stmt = con.createStatement();

// Execute query
ResultSet rs = stmt.executeQuery("select * from emp");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));

// Close connection
con.close();

} catch (Exception e) {
System.out.println(e);
}
}
}

40. User-Defined Package in Java

Engineering Package:

Student Class:

java
Copy code
package Engineering;

public class Student {


String regNo, name, branch;
int[] marks = new int[5];

public Student(String regNo, String name, String branch, int[] marks) {


this.regNo = regNo;
this.name = name;
this.branch = branch;
this.marks = marks;
}

public void display() {


System.out.println("Registration Number: " + regNo);
System.out.println("Name: " + name);
System.out.println("Branch: " + branch);
// Display marks and calculate total and percentage
int total = 0;
for (int mark : marks) {
total += mark;
}
double percentage = total / 5.0;
System.out.println("Total Marks: " + total);
System.out.println("Percentage: " + percentage + "%");
}
}

Main Class:

java
Copy code
import Engineering.Student;

public class Main {


public static void main(String[] args) {
int[] marks = {75, 85, 65, 90, 80};
Student student = new Student("REG123", "John Doe", "Computer
Science", marks);
student.display();
}
}

This program demonstrates basic concepts from object-oriented programming, thread


synchronization, file I/O operations, JDBC connectivity, and package creation in Java.

You might also like