0% found this document useful (0 votes)
3 views48 pages

Java Final Qna Arpita 250504 121954

The document contains a series of Java programming questions and answers covering various topics such as inheritance, constructors, polymorphism, exception handling, and data types. It explains concepts like multiple inheritance, encapsulation, and the differences between data structures like ArrayList and Vector. Additionally, it discusses the principles of object-oriented programming and provides examples of method overloading and overriding.

Uploaded by

Rirobin Khan
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)
3 views48 pages

Java Final Qna Arpita 250504 121954

The document contains a series of Java programming questions and answers covering various topics such as inheritance, constructors, polymorphism, exception handling, and data types. It explains concepts like multiple inheritance, encapsulation, and the differences between data structures like ArrayList and Vector. Additionally, it discusses the principles of object-oriented programming and provides examples of method overloading and overriding.

Uploaded by

Rirobin Khan
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/ 48

Horipriya Das Arpita - 2019831068

এক্সামে কেন পড়িমে ট্রিট ড়িমেন 


Java Question Answer

1. Write the output of the following java program-


Public static void main (String args[]){
int i = 0;
i = i++ + i;
System.out.println(“i= “+i);
}
Output: i = 1

2. Does java support multiple inheritance? If yes, how and if not, why?
Ans: No, JAVA doesn’t support multiple inheritance. This means you can’t extend two or more classes in a
single class. The reason behind this is to prevent ambiguity. Consider a case where class C extends class A and
class B. Both class A and class B have a common method named display(). Now, Java compiler cannot decide
which display method it should inherit. To prevent such situation java doesn’t allow multiple inheritance.
When we need to extend two or more classes in Java, we need to refactor the classes as interfaces.

This is not allowed. We have to initialize first. This is because Java allows implementing multiple interfaces on
a single class.
3. Can constructor be inherited?
Ans: Constructor is a block of code that allows you to create an object of class and has same name as class
with no explicit return type.
Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in
the form of variables and methods from its super class but it does not inherit constructor of super class
because of following reasons:
• Constructors are special and have same name as class name. So, if constructors were inherited in child
class, then child class would contain a parent class constructor which is against the constraint that
constructor should have same name as class name. If we define Parent class constructor inside Child
class it will give compile time error for return type and consider it a method. But for print method it
does not give any compile time error and consider it an overriding method.
• Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation.
Because by using a super class’s constructor we can access/initialize private members of a class.
• A constructor cannot be called as a method. It is called when object of the class is created so it does
not make sense of creating child class object using parent class constructor notation. i.e. Child c = new
Parent();
• A parent class constructor is not inherited in child class and this is why super() is added automatically in
child class constructor if there is no explicit call to super or this.

4. Compare structure from C and class in java.


5. Can you declare a constructor private?
Ans: Yes, we can declare a constructor as private. But if we declare a constructor as private, we are not able to
create an object of a class.
• A private constructor does not allow a class to be subclassed.
• A private constructor does not allow to create an object outside the class.
• If all the constant methods are there in our class we can use a private constructor.
• If all the methods are static then we can use a private constructor.
• If we try to extend a class which is having private constructor compile time error will occur.
For example, here we have created a class named “Box” and made its constructor as private. Now if we want
to make an object of this Box class in the main function, compile time error will occur.
Here is the solution:
We can create a static method named getBoxObject() which return new Box. We can call this method to
create an object of Box class. This will not show any error.

6. If a class want to partially implement an interface, what is the solution?


Ans: If a class want to partially implement an interface, we can create an abstract class that implements the
interface. Any sub class of this abstract class can partially implement the interface.
7. Why Java is called platform independent? Explain using JVM and compare it to “C”.

Java is platform-independent because it does not depend on any platform. It uses a virtual machine. The Java
programming language and all APIs are compiled into bytecodes. Bytecodes are effectively platform-
independent. The virtual machine takes care of the differences between the bytecodes for the different
platforms. The run-time requirements for Java are therefore very small. The Java virtual machine takes care of
all hardware-related issues, so that no code has to be compiled for different hardware.

8. Explain pass-by-value and pass-by-reference with example.


Ans: Basically, pass-by-value means that the actual value of the variable is passed and pass-by-reference
means the memory location is passed where the value of the variable is stored.
9. You defined, for example a variable-“b”. Discuss it’s scope and lifetime with example.
Ans: A variable which is declared inside a class and outside all the methods and blocks is an instance variable.
The general scope of an instance variable is throughout the class except in static methods. The lifetime of an
instance variable is until the object stays in memory.

10. Define and initialize 5 dimensional int array.


Ans: We can define multidimensional arrays in simple words as an array of arrays. Data in multidimensional
arrays are stored in tabular form.
Int ar[][][][][] = new int[5][5][5][5][5];

11. Let there is a class – table. In the following sentence, what would be the output-
Table t = new Table();
System.out.println(t);

12. Now you want to print = “this is a table class” when we print “System.out.println(t)” statement earlier
question without changing the print statement. How will you achieve that? Explain with code.
13.Differentiate and explain with example – nested class and inner class.
Ans: When a class is defined within a scope of another class, then it becomes inner class. If the access modifier
of the inner class is static, then it becomes nested class.
There are two types of nested classes: static and non-static. A static nested class is one that has the static
modifier applied. Because it is static, it must access the non-static members of its enclosing class through an
object. That is, it cannot refer to non-static members of its enclosing class directly. Because of this restriction,
static nested classes are seldom used. The most important type of nested class is the inner class. An inner class
is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to
them directly in the same way that other non-static members of the outer class do.
Nested class:

Inner class:

Page-149
14. In light of three principles of OOP, explain with example method overloading, overriding. Concisely
explain encapsulation with example.
Ans:
Java is a class-based object-oriented programming (OOP) language built around the concept of objects. OOP
concepts are intended to improve code readability and reusability by defining how to structure your Java
program efficiently. The core principles of object-oriented programming are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
1. Abstraction
Abstraction aims to hide complexity from users and show them only relevant information. For example, if
you’re driving a car, you don’t need to know about its internal workings.
The same is true of Java classes. You can hide internal implementation details using abstract classes or
interfaces. On the abstract level, you only need to define the method signatures (name and parameter list)
and let each class implement them in their own way.
Abstraction in Java:

• Hides the underlying complexity of data


• Helps avoid repetitive code
• Presents only the signature of internal functionality
• Gives flexibility to programmers to change the implementation of abstract behavior
• Partial abstraction (0-100%) can be achieved with abstract classes
• Total abstraction (100%) can be achieved with interfaces

2. Encapsulation
Encapsulation helps with data security, allowing you to protect the data stored in a class from system-wide
access. As the name suggests, it safeguards the internal contents of a class like a capsule.
You can implement encapsulation in Java by making the fields (class variables) private and accessing them via
their public getter and setter methods. JavaBeans are examples of fully encapsulated classes.
Encapsulation in Java:

• Restricts direct access to data members (fields) of a class


• Fields are set to private
• Each field has a getter and setter method
• Getter methods return the field
• Setter methods let us change the value of the field
3. Inheritance
Inheritance makes it possible to create a child class that inherits the fields and methods of the parent class.
The child class can override the values and methods of the parent class, but it’s not necessary. It can also add
new data and functionality to its parent.
Parent classes are also called superclasses or base classes, while child classes are known as subclasses or
derived classes as well. Java uses the extends keyword to implement the principle of inheritance in code.
Inheritance in Java:

• A class (child class) can extend another class (parent class) by inheriting its features
• Implements the DRY (Don’t Repeat Yourself) programming principle
• Improves code reusability
• Multi-level inheritance is allowed in Java (a child class can have its own child class as well)
• Multiple inheritances are not allowed in Java (a class can’t extend more than one class)

4. Polymorphism
Polymorphism refers to the ability to perform a certain action in different ways. In Java, polymorphism can
take two forms: method overloading and method overriding.
Method overloading happens when various methods with the same name are present in a class. When they
are called, they are differentiated by the number, order, or types of their parameters. Method overriding
occurs when a child class overrides a method of its parent.
Polymorphism in Java:

• The same method name is used several times


• Different methods of the same name can be called from an object
• All Java objects can be considered polymorphic (at the minimum, they are of their own type and
instances of the Object class)
• Static polymorphism in Java is implemented by method overloading
• Dynamic polymorphism in Java is implemented by method overriding

Method overloading and method overriding – question 46


Encapsulation with example – question 30 & 38

15. How would you pause a java program for a while?


Ans: To pause the execution of a thread, we use "sleep()" method of Thread class.
Syntax: Thread.currentThread().sleep(miliseconds).
Example: Thread.currentThread().sleep(100);
16. Which class would you inherit to make a java application program?
Ans: Don’t know… may be Jframe..

17.Which method is used to register a mouse motion listener?


Ans: addMouseMotionListener() method is used to register a mouse motion listener.

18. Differentiate Vector vs ArrayList.


Ans: ArrayList and Vectors both implement the List interface, and both use (dynamically resizable) arrays for
their internal data structure, much like using an ordinary array.
ArrayList and Vector both implements List interface and maintains insertion order.
19. Differentiate primitive data type vs rest of the data types.
Ans:
Primitive Data Type:
In Java, the primitive data types are the predefined data types of Javas. They specify the size and type of any
standard values. Java has 8 primitive data types namely byte, short, int, long, float, double, char and boolean.
When a primitive data type is stored, it is the stack that the values will be assigned. When a variable is copied
then another copy of the variable is created and changes made to the copied variable will not reflect changes
in the original variable. Here is a Java program to demonstrate all the primitive data types in Java.

Object Data Type:


These are also referred to as Non-primitive or Reference Data Type. They are so-called because they refer to
any particular objects. Unlike the primitive data types, the non-primitive ones are created by the users in Java.
Examples include arrays, strings, classes, interfaces etc. When the reference variables will be stored, the
variable will be stored in the stack and the original object will be stored in the heap. In Object data type
although two copies will be created, they both will point to the same variable in the heap, hence changes
made to any variable will reflect the change in both the variables. Here is a Java program to demonstrate
arrays (an object data type) in Java.
20.Why do you override constructor?
Ans: Overriding occurs when a subclass (child class) has the same method as the parent class.
Constructor is a block of code that allows you to create an object of class and has same name as class with no
explicit return type.
Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in
the form of variables and methods from its super class but it does not inherit constructor of super class
because Constructors are special and have same name as class name. So, if constructors were inherited in
child class, then child class would contain a parent class constructor which is against the constraint that
constructor should have same name as class name. If we define Parent class constructor inside Child class it
will give compile time error for return type and consider it a method.

21. Show the auto type-promotion rules in java.


Ans: There are several type promotion rules in Java that are followed while evaluating expressions-

• All byte, short and char values are promoted to int.


• If any operand is long then the expression result is long. i.e. whole expression is promoted to long.
• If any operand is a float then the expression result is float. i.e. whole expression is automatically promoted
to float.
• If any operand is a double then the expression result is double. i.e. whole expression is promoted to
double in Java.

22. Differentiate Set vs Map.


Ans: Both interfaces are used to store the collection of objects as a single unit. The main difference between
Set and Map is that Set contains only data elements, and the Map contains the data in the key-value pair, so
Map contains key and its value.
Now, let's understand some major differences between both of them.

23. Why do we use finally in exception handling?


Ans: A finally block contains all the crucial statements that must be executed whether exception occurs or
not. The statements present in this block will always execute regardless of whether exception occurs in try
block or not such as closing a connection, stream etc.
24. Write a recursive method Sum (as a class member) to sum the first N Fibonacci numbers.
Ans:

25. What is thread synchronization? How would you achieve that?


Ans: Synchronization in Java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
26. Create simple 2 thread program that prints 1 to 10 maintaining following structure- “Thread-1 1”,
“Thread-2 1” etc.

27. Explain wait(), notify(), notifyAll() with example.


Ans:
wait() -> Waits on another thread of execution.
notify() -> Resumes execution of a thread waiting on the invoking object.
notifyAll() -> Resumes execution of all threads waiting on the invoking object.
To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All
three methods can be called only from within a synchronized context. Although conceptually advanced from a
computer science perspective, the rules for using these methods are actually quite simple:
• wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the
same monitor and calls notify( ) or notifyAll( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be granted
access.
Example:
28. There are two types of input streams in JAVA. Explain those.
Ans: Java defines two types of streams:
Byte streams and Character streams.

• Byte streams provide a convenient means for handling input and output of bytes. Byte streams are
used, for example, when reading or writing binary data.
• Character streams provide a convenient means for handling input and output of characters. They use
Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more
efficient than byte streams.
29. What is buffer? Explain and show use of buffer in code.
Ans: It is the block of memory into which we can write data, which we can later be read again. The memory
block is wrapped with a NIO buffer object, which provides easier methods to work with the memory block.
A Buffer is a portion in the memory that is used to store a stream of data from peripheral devices. Then from
this buffer this stream of data is collected and stored in variables. A stream can be defined as a continuous
flow of data. The buffer is quite useful as Java deals everything as a String.

30. Differentiate and explain different access modifiers with example.


Ans:
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
31. Notice the code below. Is there any problem? If it is, correct the code and explain.
public class MainClass {
void course() {
System.out.println(“JAVA”);
}
public static void main(String[] args) {
course();
}
}

Ans: Here the problem is course() method is a non-static method. Non-static method course can-not be
referenced from a static context.
So, the solution is:

32.Can you override a private or static method in java? Explain.


Ans: No, we cannot override private or static methods in Java.
Private methods in Java are not visible to any other class which limits their scope to the class in which they are
declared.
No, you cannot override private method, hence the method is called private so that no class extending that
class has any access to the private method. Private methods are not visible to child classes.
Static methods also cannot be overridden, because static methods are a part of the Class itself, and not a part
of any instance(object) of that class. You however can declare same static method with same signature in child
classes, but that would not be considered as runtime polymorphism (override of methods).

NOTE: Static methods can’t be overridden because methods are overridden at run time. Static methods are
associated with classes while instance methods are associated with objects. So in Java, the main() method also
can’t be overridden.
NOTE: Constructors can be overloaded but not overridden.
33.What do you mean by ‘Object’ in oop. Dissect and explain ‘Car’ object with a diagram.
Ans: In OOP, objects are the things you think about first in designing a program and they are also the units of
code that are eventually derived from the process.
What is class? -A blueprint to create objects
What is Object? - An instance of a class

Suppose that we have a factory and this factory produces cars.


In order to be able to produce a car we should have some characteristics or properties for each car. So, this
factory contains the characteristics or properties of a car. For example, the color of the car, the model and
other information. So, in this case, the factory is the class, and each car will be an object. So, A class is a
blueprint to create objects. It has the properties of each object. And we can create objects from this class.
Moreover, each object is an instance of a class.

34.Notice and determine if there are any problem with the code below. If there is, correct and explain.
Ans:

35.What is meant by “this” in java?


Ans: The “this” keyword refers to the current object in a method or constructor.
The most common use of the “this” keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter).
this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
** Interface abstract method cannot have a body;

36.Let’s assume we defined a variable ‘test’. Explain its scope and lifetime with example.
Ans: A variable which is declared inside a class and outside all the methods and blocks is an instance variable.
The general scope of an instance variable is throughout the class except in static methods. The lifetime of an
instance variable is until the object stays in memory.

37.Explain the keyword “Super” in java.


Ans: The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
The super keyword refers to superclass (parent) objects.
It is used to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the confusion between super classes and
subclasses that have methods with the same name.
Usage of Java super Keyword

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

• super can be used to invoke immediate parent class method.

• super() can be used to invoke immediate parent class constructor


38.What is encapsulation?
Ans: Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private. Now we
can use setter and getter methods to set and get the data in it.
It provides you the control over the data. Suppose you want to set the value of id which should be greater
than 100 only, you can write the logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through the
private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
create an encapsulated class in Java.
39.What is Inheritance in Java?
Ans: Inheritance in Java is a concept that acquires the properties from one class to other classes; for
example, the relationship between father and son.

In Java, a class can inherit attributes and methods from another class. The class that inherits the
properties is known as the sub-class or the child class. The class from which the properties are inherited is
known as the superclass or the parent class.

In Inheritance, the properties of the base class are acquired by the derived classes.
40.Difference Between Throw and Throws.
Ans:
The throw and throws is the concept of exception handling where the throw keyword throw the exception
explicitly from a method or a block of code whereas the throws keyword is used in signature of the method.

Example:
41.For java what does it mean by write once, run anywhere.
Ans: JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually
calls the main method present in Java code. JVM is a part of the JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java
code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is
all possible because of JVM.
In traditional programming languages like C, C++ when programs were compiled, they used to be converted into
the code understood by the particular underlying hardware, so If we try to run the same code at another
machine with different hardware, which understands different code will cause an error, so you have to re-
compile the code to be understood by the new hardware.

In Java, the program is not converted to code directly understood by Hardware, rather it is converted to
bytecode(.class file) which is interpreted by JVM, so once compiled it generates bytecode file, which can be run
anywhere (any machine) which has JVM( Java Virtual Machine) and hence it gets the nature of Write Once and
Run Anywhere.

Related Question - 7

42.Write a program in Java that generates and catch “Null Pointer Exception” and “ArrayIndexOutofBounds
“ Exception.

Ans:

ArrayIndexOutOfBoundsException:

NullPointerException:
43.What is “Static”? Why would you use them? Provide example and explain.

Ans: Static Variables and Static Methods are class level and can be accessed through class name without need
to create object of the class itself. In Java, it is possible to use the static keyword with methods, blocks, variables,
as well as nested classes.

If any member in a class is declared as static, it means that even before the class is initiated, all the static
members can be accessed and become active. In contrast to this, non-static members of the same class will
cease to exist when there is no object or the object goes out of scope.

Why we use - The most important reason why static keywords are heavily used in Java is to efficiently manage
memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance
or object of that class. However, there might be situations where you want to access only a couple of methods
or variables of a class and you don’t want to create a new instance for that class just for accessing these
members. This is where you can use the static keyword in Java.
44.Write a java code that will print the most three frequent characters in a given string.

Ans:
45.Why should you prefer OOP Language over structured programming language? Explain in your words.

Ans:

Object-Oriented Programming, as name suggests, is a different approach to programming that brings together
data and functions that execute on them. It basically supports encapsulation, abstraction, inheritance,
polymorphism, etc. It also includes data hiding feature therefore it is more secure. This model is based on real
life entities that focuses on by whom task is to be done rather than focusing on what to do.
46.What is the difference between method overloading vs method overriding?

Ans:

Overloading occurs when two or more methods in one class have the same method name but different
parameters.

Overriding occurs when two methods have the same method name and parameters. One of the methods is in
the parent class, and the other is in the child class. Overriding allows a child class to provide the specific
implementation of a method that is already present in its parent class.
47.Write Output of the following Java Program sequence.

Ans:
48. Modify the class Account to provide a method called debit that withdraws money from an Account.
Ensure that the debit amount does not exceed the account’s balance, if it does, the balance should be left
unchanged and the method should print a message indicating “Debit amount exceeded account balance”.

Ans:
49. Write a program in JAVA to calculate the area of geometric shapes by maintaining following conventions–
i)Create a generic parent object Area with common parameters and methods.
ii)Create child objects Triangle and Rectangle by inheriting Area and specifying separate functions for
respective objects.
iii)Specify constructors for the object where possible.
iv)Create separate main class to call Triangle and Rectangle objects.
v)Show use of super and this where possible.
vi)Use your creativity.

Ans:
50. Show an example of Mutex lock using JAVA.

Ans:

In a multithreaded application, two or more threads may need to access a shared resource at the same time,
resulting in unexpected behavior. A mutex (or mutual exclusion) is the simplest type of synchronizer – it ensures
that only one thread can execute the critical section of a computer program at a time.

To access a critical section, a thread acquires the mutex, then accesses the critical section, and finally releases
the mutex. In the meantime, all other threads block till the mutex releases. As soon as a thread exits the critical
section, another thread can enter the critical section.

The simplest way to implement a mutex in Java is using synchronized keyword. Every object in Java has an
intrinsic lock associated with it. The synchronized method and the synchronized block use this intrinsic lock to
restrict the access of the critical section to only one thread at a time. Therefore, when a thread invokes
a synchronized method or enters a synchronized block, it automatically acquires the lock. The lock releases
when the method or block completes or an exception is thrown from them.

Example:
51. How many ways we can create threads? Show example.

Ans: There are two ways to create a thread:

1.By extending Thread class


2.By implementing Runnable interface.

52. What is the type and value of the following expression? -4 + ½ + 2*-3 + 5.0.

Ans: The type of the following expression is double and the value is -5.0.
53. Write down the output of the following program.

Ans:

54.Look at the code carefully. Does the code have any bug? If not, write no problem found. If yes, correct the
code and explain why.
public class Why{
void hello(){
System.out.println(“Hello World”);
}
public static void main(String[] args) {
hello();
}
}
Ans: Here the problem is hello() method is a non-static method. Non-static method course can-not be
referenced from a static context.
So, the solution is:

55. Show two ways to concatenate the following two strings together to get the string “Hi, mom.”:
String hi = “Hi, ”;
String mom = “mom.”;

Ans:

1st way:
2nd way:

56.Write a java program to read a number of integers from a text file (ended by a string “end”) using the
scanner class. Calculate and display the sum of the numbers.

Ans:
57. Write a simple program to replace all the occurrences of a given word str1 in a string of several lines by
another word str2.

Ans:

You might also like