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

Java Programming

Part A 6x1=6

Choose the Correct Answer


1. Predict the output of the given code
int Integer = 24;
char String = ‘I’; CO1 K1
System.out.print(Integer);
System.out.print(String);
a. Compile error b. 1 c. Throws exception d. 24 I
2. Which variables are created when an object is created with the use of the keyword CO1 K1
'new' and destroyed when the object is destroyed?
a. Local variables b. Instance variables c. Class Variables d. Static variables

3. Which of the following is a garbage collection technique? CO1 K1


a. Cleanup model Mark and Space d. Sweep model
b. c.
sweep model management model
4. When Exceptions in Java does arises in code sequence? CO1 K1
a. Run Time b. Compilation c. Can Occur Any d.
No Exception
Time Time
5. In java control statements break, continue, return, try-catch-finally and assert
CO2 K1
belongs to?
a. Selection Loop Transfer
b. c. d. Pause Statement
statements Statements statements
6. _________ is the process of defining a method in a subclass having same name &
CO2 K1
type signature as a method in its superclass.
a. Method b. Method c. Method hiding d. Method prototype
overloading overriding
Part B 3 x 6 = 18
Answer ALL questions
7a. Develop a Java program to check whether given number is prime or not. CO1 K3

public class Main {

public static void main(String[] args) {

int num = 29;


boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}

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

How does garbage collection work in Java?

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.

8a Interpret about the super keyword in Java with example. CO1 K2

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.");
}
}

class Dog extends Animal {


String breed;
Dog(String name, String breed) {
super(name); // Invoke the superclass constructor
this.breed = breed;
}

void display() {
System.out.println("Name: " + super.name); // Accessing superclass member variable
super.eat(); // Invoking superclass method
System.out.println("Breed: " + breed);
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Buddy", "Labrador");
dog.display();
}
}

Output:

Name: Buddy

The animal is eating.

Breed: Labrador

(or)

8b. Illustrate about Divide by zero exception with example program CO1 K2

class Main {
public static void main(String[] args) {
try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}

Output:
ArithmeticException => / by zero

9a. Examine how polymorphism plays a useful role in Java CO2 K4

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.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.

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.

Let's first understand the upcasting before Runtime Polymorphism.

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{}

Here, the relationship of B class would be:

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

Method Overloading Method Overriding

Method overloading is a compile- Method overriding is a run-time


time polymorphism. polymorphism.

Method overriding is used to grant the


Method overloading helps to
specific implementation of the method
increase the readability of the
which is already provided by its parent
program.
class or superclass.

It is performed in two classes with


It occurs within the class.
inheritance relationships.
Method overloading may or may Method overriding always needs
not require inheritance. inheritance.

In method overloading, methods


In method overriding, methods must have
must have the same name and
the same name and same signature.
different signatures.

In method overloading, the return


type can or cannot be the same, In method overriding, the return type must
but we just have to change the be the same or co-variant.
parameter.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

It gives better performance. The reason


Poor Performance due to compile behind this is that the binding of
time polymorphism. overridden methods is being done at
runtime.

Private and final methods can be Private and final methods can’t be
overloaded. overridden.

The argument list should be


The argument list should be the same in
different while doing method
method overriding.
overloading.
Part C 3x 12 = 36
Answer ALL questions
10a. Explain in detail about the class and objects in Java with example. CO1 K2
Java Class and Objects

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.

Create a class in Java


We can create a class in Java using the class keyword.

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

private int gear = 5;

// 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.

className object = new className();

// for Bicycle class

Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();

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.

Access Members of a Class


We can use the name of objects along with the . operator to access members of a class. For
example,
class Bicycle {

// field of class

int gear = 5;

// method of class

void braking() {

...

// create object

Bicycle sportsBicycle = new Bicycle();

// access field and method

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,

Bicycle sportsBicycle = new Bicycle();

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.

Example: Java Class and Objects


class Lamp {

// stores the value for light

// true if light is on

// false if light is off


boolean isOn;

// method to turn on the light

void turnOn() {

isOn = true;

System.out.println("Light on? " + isOn);

// method to turnoff the light

void turnOff() {

isOn = false;

System.out.println("Light on? " + isOn);

class Main {

public static void main(String[] args) {

// create objects led and halogen

Lamp led = new Lamp();

Lamp halogen = new Lamp();

// turn on the light by

// calling method turnOn()

led.turnOn();

// turn off the light by

// calling method turnOff()

halogen.turnOff();

Output:

Light on? true

Light on? false


In the above program, we have created a class named Lamp. It contains a variable: isOn and two
methods: turnOn() and turnOff().
Inside the Main class, we have created two objects: led and halogen of the Lamp class. We then
used the objects to call the methods of the class.
 led.turnOn() - It sets the isOn variable to true and prints the output.
 halogen.turnOff() - It sets the isOn variable to false and prints the output.
The variable isOn defined inside the class is also called an instance variable. It is because when we
create an object of the class, it is called an instance of the class. And, each instance will have its
own copy of the variable.
That is, led and halogen objects will have their own copy of the isOn variable.

Example: Create objects inside the same class


Note that in the previous example, we have created objects inside another class and accessed the
members from that class.

However, we can also create objects inside the same class.

class Lamp {

// stores the value for light

// true if light is on

// false if light is off

boolean isOn;

// method to turn on the light

void turnOn() {

isOn = true;

System.out.println("Light on? " + isOn);

public static void main(String[] args) {

// create an object of Lamp

Lamp led = new Lamp();

// access method using object

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

In Java, constructors can be divided into 3 types:

1. 1.No-Arg Constructor

2. 2.Parameterized Constructor

3. 3.Default Constructor

1. Java No-Arg Constructors

Similar to methods, a Java constructor may or may not have any parameters
(arguments).

If a constructor does not accept any parameters, it is known as a no-argument


constructor. For example,
private Constructor() {

// body of the constructor

Eg:Java private no-arg constructor


class Main {

int i;

// constructor with no parameter

private Main() {

i = 5;

System.out.println("Constructor is called");

public static void main(String[] args) {

// calling the constructor without any parameter

Main obj = new Main();

System.out.println("Value of i: " + obj.i);

Output:
Constructor is called

Value of i: 5

Eg:Java public no-arg constructors


class Company {

String name;

// public constructor

public Company() {

name = "Programiz";

}
}

class Main {

public static void main(String[] args) {

// object is created in another class

Company obj = new Company();

System.out.println("Company name = " + obj.name);

Output:
Company name = Programiz

2. Java Parameterized Constructor

A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructor with parameters).

Eg: Parameterized constructor


class Main {

String languages;

// constructor accepting single value

Main(String lang) {

languages = lang;

System.out.println(languages + " Programming Language");

public static void main(String[] args) {

// call constructor by passing a single value

Main obj1 = new Main("Java");

Main obj2 = new Main("Python");

Main obj3 = new Main("C");

Output:
Java Programming Language

Python Programming Language

C Programming Language

3. Java Default Constructor

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.

Eg: Default Constructor


class Main {

int a;

boolean b;

public static void main(String[] args) {

// A default constructor is called

Main obj = new Main();

System.out.println("Default Value:");

System.out.println("a = " + obj.a);

System.out.println("b = " + obj.b);

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}`);
}
}

class Ebook extends Book {


constructor(title, author, publicationYear, price) {
super(title, author, publicationYear);
this.price = price;
}

displayDetails() {
super.displayDetails();
console.log(`Price: $${this.price}`);
}
}

// Create an instance of the Ebook class


const ebook = new Ebook('Don Quixote', 'Miguel de Cervantes', 1605, 21.49);

// Display the ebook details


ebook.displayDetails();

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

Java Abstract Class and Abstract Methods


Java Abstract Class

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 {

// fields and methods

...

// try to create an object Language

// throws an error

Language obj = new La//

create an abstract class

nguage();

To know about the non-abstract methods, visit Java methods. Here, we will learn about
abstract methods.
abstract class Language {

// abstract method

abstract void method1();

// regular method

void method2() {
System.out.println("This is regular method");

Java Abstract 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();

Here, display() is an abstract method. The body of display() is replaced by ; .


If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error. For example,
// error

// class should be abstract

class Language {

// abstract method

abstract void method1();

Eg: Java Abstract Class and 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

Accesses Constructor of Abstract Classes

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.

Abstraction is an important concept of object-oriented programming that allows us to hide


unnecessary details and only show the needed information.

Eg: Java Abstraction abstract class MotorBike {


abstract void brake();

class SportsBike extends MotorBike {

// implementation of abstract method

public void brake() {

System.out.println("SportsBike Brake");

class MountainBike extends MotorBike {


// implementation of abstract method

public void brake() {

System.out.println("MountainBike Brake");

class Main {

public static void main(String[] args) {

MountainBike m1 = new MountainBike();

m1.brake();

SportsBike s1 = new SportsBike();

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() .

So, the implementation of brake() in MotorBike is kept hidden.


Here, MountainBike makes its own implementation of brake() and SportsBike makes its own
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 {

public void getType();

public void getVersion();}

Here,

 Language is an interface.
 It includes abstract methods: getType() and getVersion() .

Implementing an Interface

Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
Eg: Java Interface
interface Polygon {

void getArea(int length, int breadth);

// implement the Polygon interface

class Rectangle implements Polygon {

// implementation of abstract method

public void getArea(int length, int breadth) {

System.out.println("The area of the rectangle is " + (length * breadth));

class Main {
public static void main(String[] args) {

Rectangle r1 = new Rectangle();

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.

Eg: Java Interface


// create an interface

interface Language {

void getName(String name);

// class implements interface

class ProgrammingLanguage implements Language {

// implementation of abstract method

public void getName(String name) {

System.out.println("Programming Language: " + name);

class Main {
public static void main(String[] args) {

ProgrammingLanguage language = new ProgrammingLanguage();

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.

Implementing Multiple Interfaces

In Java, a class can also implement multiple interfaces. For example,


interface A {

// 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 {

public static void main(String[] args) {\ ArrayList<Integer> myList = new ArrayList<>(3);


myList.add(3);

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;

You might also like