Professional Documents
Culture Documents
Questionswithanswer
Questionswithanswer
Part A 6x1=6
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Output:
29 is a primer number
(or)
7b. Outline the working of garbage collector in Java. CO1 K3
During the garbage collection process, the collector scans different parts of the heap, looking for
objects that are no longer in use. If an object no longer has any references to it from elsewhere in
the application, the collector removes the object, freeing up memory in the heap. This process
continues until all unused objects are successfully reclaimed.
Sometimes, a developer will inadvertently write code that continues to be referenced even
though it’s no longer being used. The garbage collector will not remove objects that are being
referenced in this way, leading to memory leaks. After memory leaks are created, it can be hard
to detect the cause, so it’s important to prevent memory leaks by ensuring that there are no
references to unused objects.
To ensure that garbage collectors work efficiently, the JVM separates the heap into separate
spaces, and then garbage collectors use a mark-and-sweep algorithm to traverse these spaces
and clear out unused objects. Let’s take a closer look at the different generations in the memory
heap, then go over the basics of the mark-and-sweep algorithm.
The keyword Super in Java refers to the immediate parent class object. The Super keyword came into
existence with the concept of Java inheritance. When you create an instance of a subclass, it creates an
instance of a parent class, which is referred to by a super reference variable.
The Super keyword is used to access data methods, members, and constructors of the parent class.
Moreover, it is used to avoid ambiguity between the child class and the parent class with the same data
members or methods.
Eg:
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void eat() {
System.out.println("The animal is eating.");
}
}
void display() {
System.out.println("Name: " + super.name); // Accessing superclass member variable
super.eat(); // Invoking superclass method
System.out.println("Breed: " + breed);
}
}
Output:
Name: Buddy
Breed: Labrador
(or)
8b. Illustrate about Divide by zero exception with example program CO1 K2
class Main {
public static void main(String[] args) {
try {
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output:
ArithmeticException => / by zero
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will
focus on runtime polymorphism in java.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
1. interface I{}
2. class A{}
3. class B extends A implements I{}
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
(or)
9b. Compare the Method Overriding and Method Overloading techniques. CO2 K4
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Java is an object-oriented programming language. The core concept of the object-oriented approach
is to break complex problems into smaller objects.
An object is any entity that has a state and behavior. For example, a bicycle is an object. It has
States: idle, first gear, etc
Behaviors: braking, accelerating, etc.
Before we learn about objects, let's first know about classes in Java.
Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a
class.
For example,
class ClassName {
// fields
// methods
Here, fields (variables) and methods represent the state and behavior of the object respectively.
fields are used to store data
methods are used to perform some operations
For our bicycle object, we can create the class as
Eg:
class Bicycle {
// state or field
// behavior or method
public void braking() {
System.out.println("Working of Braking");
In the above example, we have created a class named Bicycle. It contains a field named gear and
a method named braking().
Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And,
all the bicycles will share the fields and methods of the prototype.
Note: We have used keywords private and public. These are known as access modifiers. To
learn more, visit Java access modifiers.
Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of
the class.
Creating an Object in Java
Here is how we can create an object of a class.
We have used the new keyword along with the constructor of the class to create an object.
Constructors are similar to methods and have the same name as the class. For
example, Bicycle() is the constructor of the Bicycle class. To learn more, visit Java
Constructors.
Here, sportsBicycle and touringBicycle are the names of objects. We can use them to access
fields and methods of the class.
As you can see, we have created two objects of the class. We can create multiple objects of a single
class in Java.
Note: Fields and methods of a class are also called members of the class.
// field of class
int gear = 5;
// method of class
void braking() {
...
// create object
sportsBicycle.gear;
sportsBicycle.braking();
In the above example, we have created a class named Bicycle. It includes a field named gear and
a method named braking(). Notice the statement,
Here, we have created an object of Bicycle named sportsBicycle. We then use the object to
access the field and method of the class.
sportsBicycle.gear - access the field gear
sportsBicycle.braking() - access the method braking()
We have mentioned the word method quite a few times. You will learn about Java methods in detail
in the next chapter.
Now that we understand what is class and object. Let's see a fully working example.
// true if light is on
void turnOn() {
isOn = true;
void turnOff() {
isOn = false;
class Main {
led.turnOn();
halogen.turnOff();
Output:
class Lamp {
// true if light is on
boolean isOn;
void turnOn() {
isOn = true;
led.turnOn();
}
Output
Light on?true
Here, we are creating the object inside the main() method of the same class.
(or)
10b. Illustrate about the types of constructors with examples. CO1 K2
Java Constructors
A constructor in Java is similar to a method that is invoked when an object of the class is
created.
Unlike Java methods, a constructor has the same name as that of the class and does not
have any return type. For example,
class Test {
Test() {
// constructor body
Here, Test() is a constructor. It has the same name as that of the class and doesn't have
a return type.
Types of Constructor
1. 1.No-Arg Constructor
2. 2.Parameterized Constructor
3. 3.Default Constructor
Similar to methods, a Java constructor may or may not have any parameters
(arguments).
int i;
private Main() {
i = 5;
System.out.println("Constructor is called");
Output:
Constructor is called
Value of i: 5
String name;
// public constructor
public Company() {
name = "Programiz";
}
}
class Main {
Output:
Company name = Programiz
A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructor with parameters).
String languages;
Main(String lang) {
languages = lang;
Output:
Java Programming Language
C Programming Language
If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.
int a;
boolean b;
System.out.println("Default Value:");
Output:
Default Value:
a=0
b = false
11a. Develop a Java program to create own exception for Negative Value Exception if the CO1 K3
user enter negative value.
Output:
Error:Negative values are not allowed.
(or)
11b. Develop a class Book and define display method to display book information. Inherit CO1 K3
Reference_Book and Magazine classes from Book class and override display
method of Book class in Reference_Book and Magazine classes. Make necessary
assumptions required.
class Book {
constructor(title, author, publicationYear) {
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
}
displayDetails() {
console.log(`Title: ${this.title}`);
console.log(`Author: ${this.author}`);
console.log(`Publication Year: ${this.publicationYear}`);
}
}
displayDetails() {
super.displayDetails();
console.log(`Price: $${this.price}`);
}
}
output:
"Title: Don Quixote"
"Author: Miguel de Cervantes"
"Publication Year: 1605"
"Price: $21.49"
12a. Analyze the Abstract Classes and Methods in Java with example. CO2 K4
The abstract class in Java cannot be instantiated (we cannot create objects of abstract
classes). We use the abstract keyword to declare an abstract class. For example,
An abstract class can have both the regular methods and abstract methods. For
example,
abstract class Language {
...
// throws an error
nguage();
To know about the non-abstract methods, visit Java methods. Here, we will learn about
abstract methods.
abstract class Language {
// abstract method
// regular method
void method2() {
System.out.println("This is regular method");
A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods. For example,
abstract void display();
class Language {
// abstract method
Though abstract classes cannot be instantiated, we can create subclasses from it. We
can then access members of the abstract class using the object of the subclass. For
An abstract class can have constructors like the regular class. And, we can access the
constructor of an abstract class from the subclass using the super keyword. For example,
abstract class Animal {
Animal() {
….
}
class Dog extends Animal {
Dog() {
super();
...
Here, we have used the super() inside the constructor of Dog to access the constructor of
the Animal .
Note that the super should always be the first statement of the subclass constructor.
Visit Java super keyword to learn more.
Java Abstraction
The major use of abstract classes and methods is to achieve abstraction in Java.
System.out.println("SportsBike Brake");
System.out.println("MountainBike Brake");
class Main {
m1.brake();
s1.brake();
Output:
MountainBike Brake
SportsBike Brake
In the above example, we have created an abstract super class MotorBike . The
superclass MotorBike has an abstract method brake() .
The brake() method cannot be implemented inside MotorBike . It is because every bike has
different implementation of brakes. So, all the subclasses of MotorBike would have
different implementation of brake() .
(or)
12b. Examine the Packages and Interfaces in Java. CO2 K4
Java Interface
An interface is a fully abstract class. It includes a group of abstract methods (methods
without a body).
We use the interface keyword to create an interface in Java. For example,
interface Language {
Here,
Language is an interface.
It includes abstract methods: getType() and getVersion() .
Implementing an Interface
To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
Eg: Java Interface
interface Polygon {
class Main {
public static void main(String[] args) {
r1.getArea(5, 6);
Output
The area of the rectangle is 30
In the above example, we have created an interface named Polygon . The interface
contains an abstract method getArea() .
Here, the Rectangle class implements Polygon . And, provides the implementation of
the getArea() method.
interface Language {
class Main {
public static void main(String[] args) {
language.getName("Java");
Output
Programming Language: Java
In the above example, we have created an interface named Language . The interface
includes an abstract method getName() .
Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.
// members of A
interface B {
// members of B
class C implements A, B {
// abstract members of A
// abstract members of B
Java Package
Java Package
A package is simply a container that groups related types (Java classes, interfaces,
enumerations, and annotations). For example, in core Java, the ResultSet interface
belongs to the java.sql package. The package contains all the related types that are
needed for the SQL query and database connection.
If you want to use the ResultSet interface in your code, just import the java.sql package
(Importing packages will be discussed later in the article).
As mentioned earlier, packages are just containers for Java classes, interfaces and so
on. These packages help you to reserve the class namespace and create a maintainable
code.
For example, you can find two Date classes in Java. However, the rule of thumb in Java
programming is that only one unique class name is allowed in a Java project.
How did they manage to include two classes with the same name Date in JDK?
This was possible because these two Date classes belong to two different packages:
java.util.Date - this is a normal Date class that can be used anywhere.
java.sql.Date - this is a SQL Date used for the SQL query and such.
Based on whether the package is defined by the user or not, packages are divided into
two categories:
Built-in Package
Built-in packages are existing java packages that come along with the JDK. For
example, java.lang , java.util , java.io , etc. For example:
import java.util.ArrayList;
class ArrayListUtilization {
myList.add(2);
myList.add(1);
System.out.println(myList);
Output:
myList = [3, 2, 1]
The ArrayList class belongs to java.util package . To use it, we have to import the
package first using the import statement
import java.util.ArrayList;