Java Final Qna Arpita 250504 121954
Java Final Qna Arpita 250504 121954
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.
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.
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:
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:
• 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:
• 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.
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:
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
34.Notice and determine if there are any problem with the code below. If there is, correct and explain.
Ans:
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.
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.
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: