0% found this document useful (0 votes)
93 views148 pages

r23 Oops Qb With Answers

Uploaded by

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

r23 Oops Qb With Answers

Uploaded by

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

Course Code: 23CS0508 R23

SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY:: PUTTUR


(AUTONOMOUS)
Siddharth Nagar,Narayanavanam Road–517583
Subject with Code: Object Oriented Programming Through Java(23CS0508)
Course & Branch: CSE,CAD, CSM,CCC,CIC and CAI
Year & Sem: II B.Tech & I Sem Regulation: R23

UNIT I

Introduction to OOP,Operators and Statements in Java


1 a) What is a variable? [L1,CO1][2M]
Variables are the containers for storing the data values or you can also call it a
memory location name for the data. Every variable has a:
Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
Variable Name – To identify the variable uniquely within the scope.
Value – The data assigned to the variable.
b) What are the different types of variables? [L1,CO1][2M]
Types of Variables
There are three types of variables in Java:
local variable
instance variable
static variable
c) Define ternary operator with syntax. [2M]
[L1,CO1
]
The ternary operator (? :) consists of three operands. It is used to evaluate Boolean
expressions. The operator decides which value will be assigned to the variable. It is
the only conditional operator that accepts three operands. It can be used instead of the
if-else statement. It makes the code much more easy, readable, and shorter.
Syntax:
variable = (condition) ? expression1 : expression2
d) List out Java language BUZZWORDS. [L1,C [2M]
O1]
List out Java language BUZZWORDS.
Java language BUZZWORDS

 Simple
 Object-Oriented
 Distributed
 Compiled and Interpreted
 Robust
 Secure
 Architecture-Neutral
 Portable
 High Performance

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Multithreaded
 Dynamic

e) What are the core OOP’s concepts? [L1,C [2M]


O1]
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
2 a) Describe the structure of java. [L2,C [5M]
O1]
Java is an object-oriented programming, platform-independent, and secure
programming language that makes it popular. Using the Java programming language,
we can develop a wide variety of applications.
structure of java:

o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors
Documentation Section:
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes
the author's name, date of creation, version, program name, company
name, and description of the program.
To write the statements in the documentation section, we use comments. The
comments may be single-line, multi-line, and documentation comments.
Single-line Comment: It starts with a pair of forwarding slash (//).For example
//First Java Program
Multi-line Comment: It starts with a /* and ends with */. For example
1. /*It is an example of
2. multiline comment*/
Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example
1. /**It is an example of documentation comment*/
Package Declaration:
The package declaration is optional. It is placed just after the documentation section.
In this section, we declare the package name in which the class is placed. Note that
there can be only one package statement in a Java program. It must be defined before
any class and interface declaration.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
We use the keyword package to declare the package name.
For example:package javatpoint; //where javatpoint is the package name
package com.javatpoint; //where com is the root directory and javatpoint is the
subdirectory

Import Statements:
The package contains the many predefined classes and interfaces. If we want to use
any class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to
import the class. It is written before the class declaration and after the package
statement. We use the import statement in two ways, either import a specific class or
import all classes of a particular package. In a Java program, we can use multiple
import statements. For example:
1. import java.util.Scanner; //it imports the Scanner class only
2. import java.util.*; //it imports all the class of the java.util package
Interface Section
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from
the class. It contains only constants and method declarations. Another difference is
that it cannot be instantiated. We can use interface in classes by using
the implements keyword. An interface can also be used with other interfaces by using
the extends keyword. For example:
1. interface car
2. {
3. void start();
4. void stop();
5. }
Class Definition:
In this section, we define the class. It is vital part of a Java program. Without
the class, we cannot create any Java program. A Java program may conation more
than one class definition. We use the class keyword to define the class. The class is a
blueprint of a Java program. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class that contains the
main() method. For example:
1. class Student //class definition
2. {
3. }
Class Variables and Constants:
In this section, we define variables and constants that are to be used later in the
program. In a Java program, the variables and constants are defined just after the class
definition. The variables and constants store values of the parameters. It is used
during the execution of the program. We can also decide and define the scope of
variables by using the modifiers. It defines the life of the variables. For example:
1. class Student //class definition
2. {
3. String sname; //variable
4. int id;
5. double percentage;
6. }

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Main Method Class
In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method. In other
words, it is an entry point of the class. It must be inside the class. Inside the main
method, we create objects and call the methods. We use the following statement to
define the main() method:
1. public static void main(String args[])
2. {
3. }
b) Create a simple java program to understand structure of java program [L6,C [5M]
O1]
// Java Program to Sum of Three Numbers
import java.io.*;
class GFG {
public static void main (String[] args) {
// Three Integers
int a=1,b=2,c=3;
// Method 1:
// Adding sum of a+b and then
// sum of a+b with c
int k=a+b;
int result=k+c;
// Printing to Sum
System.out.println("Method 1: Sum a+b+c = "+result);
// Method 2:
// Printing the Sum of Three
// Variables(Numbers)
System.out.println("Method 2: Sum a+b+c = "+(a+b+c));
}
}
OUTPUT:
Method 1: Sum a+b+c = 6
Method 2: Sum a+b+c = 6
3 a) Describe the principles of object oriented programming. [L2,C [5M]
O1]
bject-Oriented Programming (OOP) in Java is a programming paradigm based on the
concept of "objects", which can contain data (fields, attributes) and methods
(functions or procedures). The core principles of OOP in Java are:
1. Encapsulation
Encapsulation is the bundling of data (variables) and methods (functions) that
operate on the data into a single unit or class. It restricts direct access to some of an
object's components, which is a means of preventing unintended interference and
misuse of the data.
Private fields are used to hide the internal state of an object.
Public methods (getters and setters) provide controlled access to the fields.
Example:
public class Person {
private String name;
private int age;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
2. Abstraction
Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of an object. In Java, this can be achieved using
abstract classes and interfaces.
An abstract class can have abstract methods (without implementation) as well as
concrete methods.
An interface is a contract that defines a set of methods but does not provide
implementation.
Example:
abstract class Animal {
abstract void sound(); // Abstract method
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
java
Copy code
// Interface
interface Drawable {
void draw(); // Method signature
}
class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
3. Inheritance
Inheritance is the mechanism by which one class can inherit fields and methods from
another class. This promotes code reusability and establishes a relationship between
parent and child classes.
The child class (subclass) inherits the properties and behaviors of the parent class
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
(superclass).
Java uses the keyword extends to denote inheritance.
Example:
class Animal {
void eat() {
System.out.println("This animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}
4. Polymorphism
Polymorphism allows objects to be treated as instances of their parent class rather
than their actual class. The two types of polymorphism in Java are:
Compile-time polymorphism (Method Overloading): Occurs when multiple
methods have the same name but different parameters.
Runtime polymorphism (Method Overriding): Occurs when a subclass provides a
specific implementation of a method that is already defined in its superclass.
Example:

java
Copy code
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
class Test {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Outputs: Bark (Runtime polymorphism)
}
}
b) Explain the step-by-step process for creating, compiling & running java [L2,C [5M]

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
program using JVM. O1]
Here's a step-by-step guide on creating, compiling, and running a Java program using
the Java Virtual Machine (JVM):
Step 1: Creating a Java Program
1. Open a text editor (e.g., Notepad, TextEdit, or Sublime Text).
2. Create a new file and save it with a .java extension (e.g., HelloWorld.java).
3. Write your Java program in the file. For example:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Step 2: Compiling the Java Program
1. Open a terminal or command prompt.
2. Navigate to the directory where you saved your .java file.
3. Compile the Java program using the javac command:
javac HelloWorld.java
This will create a HelloWorld.class file in the same directory.
Step 3: Running the Java Program
1. Stay in the same terminal or command prompt.
2. Run the Java program using the java command:
java HelloWorld
Note: You don't need to include the .class extension when running the program.
1. The JVM will load the HelloWorld.class file and execute the main method.
2. You should see the output "Hello, World!" in the terminal or command prompt.
4 a) List and explain about the rules for creating identifier. [L2,C [5M]
O1]
An identifier in Java is the name given to Variables, Classes, Methods, Packages,
Interfaces, etc. These are the unique names and every Java Variables must be
identified with unique names.
Example:
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above Java code, we have 5 identifiers as follows:
Test: Class Name
main: Method Name
String: Predefined Class Name
args: Variable Name
a: Variable Name
Rules For Naming Java Identifiers
There are certain rules for defining a valid Java identifier. These rules must be
followed, otherwise, we get a compile-time error. These rules are also valid for other
languages like C, and C++.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore). For
example “geek@” is not a valid Java identifier as it contains a ‘@’ a special
character.
 Identifiers should not start with digits([0-9]). For example “123geeks” is not
a valid Java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an
optimum length of 4 – 15 letters only.
 Reserved Words can’t be used as an identifier. For example “int while = 20;”
is an invalid statement as a while is a reserved word. There are 53 reserved
words in Java.
b) What is a token in Java? Illustrate the tokens available in Java. [L3,C [5M]
O1]
In Java, Tokens are the smallest elements of a program that is meaningful to the
compiler. They are also known as the fundamental building blocks of the program.
Tokens can be classified as follows:
Keywords
Identifiers
Constants
Special Symbols
Operators
Comments
Separators
1. Keyword:
Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing
so, we are trying to assign a new meaning to the keyword which is not allowed. Java
language supports the following keywords:
abstract assert boolean
break byte case
catch char class
const continue default
do double else
enum exports extends
Identifiers:
Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user-defined names consisting of an arbitrarily long sequence of
letters and digits with either a letter or the underscore (_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers; they are reserved for special use. Once declared, you can use
the identifier in later program statements to refer to the associated value. A special
kind of identifier, called a statement label, can be used in goto statements.
Examples of valid identifiers:
MyVariable
MYVARIABLE
myvariable

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
Constants/Literals:
Constants are also like normal variables. But the only difference is, their values
cannot be modified by the program once they are defined. Constants refer to fixed
values. They are also called as literals. Constants may belong to any of the data type.
Syntax:
final data_type variable_name;
Special Symbols:
The following special symbols are used in Java having some special meaning and
thus, cannot be used for some other purpose.
[] () {}, ; * =
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces marks the start and end of a block
of code containing more than one executable statement.
comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
semi colon : It is an operator that essentially invokes something called an
initialization list.
asterick (*): It is used to create pointer variable.
assignment operator: It is used to assign values.
Comments:
In Java, Comments are the part of the program which are ignored by the compiler
while compiling the Program. They are useful as they can be used to describe the
operation or methods in the program.
The Comments are classified as follows:
1. Single Line Comments
// This is a Single Line Comment
2. Multiline Comments
/*
This is a Multiline Comment
*/
Separators:
Separators are used to separate different parts of the codes. It tells the compiler about
completion of a statement in the program. The most commonly and frequently used
separator in java is semicolon (;).
int variable; //here the semicolon (;) ends the declaration of the variable
5 a) Identify different types of literals with examples [L3,C [5M]
O1]
Literals in Java:
In Java, literal is a notation that represents a fixed value in the source code. In lexical

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
analysis, literals of a given type are generally known as tokens. In this section, we
will discuss the term literals in Java.
Literals:
In Java, literals are the constant values that appear directly in the program. It can be
assigned directly to a variable. Java has various types of literals. The following figure
represents a literal.

Types of Literals in Java


There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:

o Decimal Integer: These are the set of numbers that consist of digits from 0 to
9. It may have a positive (+) or negative (-) Note that between numbers
commas and non-digit characters are not permitted. For example, 5678, +657,
-89, etc.
1. int decVal = 26;

o Octal Integer: It is a combination of number have digits from 0 to 7 with a


leading 0. For example, 045, 026,
1. int octVal = 067;

o Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as


hexadecimal integers. It may also include a character from a to f or A to F that
represents numbers from 10 to 15, respectively. For example, 0xd, 0xf,
1. int hexVal = 0x1a;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you
can create binary literals in Java SE 7 and later). Prefix 0b represents the
Binary system. For example, 0b11010.
1. int binVal = 0b11010;
Real Literals
The numbers that contain fractional parts are known as real literals. We can also
represent real literals in exponent form. For example, 879.90, 99E-3, etc.

Backslash Literals:
Java supports some special backslash character literals known as backslash literals.
They are used in formatted output. For example:

\n: It is used for a new line


\t: It is used for horizontal tab
\b: It is used for blank space
\v: It is used for vertical tab
\a: It is used for a small beep
\r: It is used for carriage return
\': It is used for a single quote
\": It is used for double quotes
Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, 'a', '%', '\
u000d', etc.

String Literals
String literal is a sequence of characters that is enclosed between double quotes ("")
marks. It may be alphabet, numbers, special characters, blank space, etc. For example,
"Jack", "12345", "\n", etc
b) Illustrate scope of a variable and method with examples. [L3,C [5M]
O1]
In Java, the scope of a variable or method determines where it can be accessed or
used within a program. Scopes ensure that variables and methods are only accessible
where they are relevant, promoting efficient memory management and preventing
name conflicts.

Variable Scope
There are three main types of variable scopes:
Instance (Object-Level) Scope
Local Scope
Class (Static) Scope
1. Instance Variable Scope
Definition: Instance variables are declared inside a class but outside any method or
constructor.
Scope: Accessible throughout the class, but only via an instance (object).
Lifetime: Exists as long as the object exists.
Example:
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
class InstanceScopeExample {
int instanceVar = 10; // Instance variable

void display() {
System.out.println("Instance Variable: " + instanceVar);
}
}

public class Main {


public static void main(String[] args) {
InstanceScopeExample obj = new InstanceScopeExample();
obj.display(); // Output: Instance Variable: 10
}
}
2. Local Variable Scope
Definition: Local variables are declared inside a method, constructor, or block.
Scope: Limited to the block in which they are declared.
Lifetime: Created when the method/block is called and destroyed when it exits.
Example:
class LocalScopeExample {
void display() {
int localVar = 20; // Local variable
System.out.println("Local Variable: " + localVar);
}
// localVar cannot be accessed here
}

public class Main {


public static void main(String[] args) {
LocalScopeExample obj = new LocalScopeExample();
obj.display(); // Output: Local Variable: 20
}
}
3. Class (Static) Variable Scope
Definition: Class variables are declared using the static keyword.
Scope: Shared across all instances of the class and can be accessed without creating
an object.
Lifetime: Exists as long as the program runs.
Example:
class StaticScopeExample {
static int staticVar = 30; // Static variable

static void display() {


System.out.println("Static Variable: " + staticVar);
}
}

public class Main {


public static void main(String[] args) {
StaticScopeExample.display(); // Accessing static variable without creating an
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
object
// Output: Static Variable: 30
}
}
Method Scope
The scope of a method is determined by:
Where it is declared.
Its access modifier (public, private, protected, default).
1. Public Method
Scope: Accessible from anywhere in the program if the class is visible.
Example:
class PublicMethodExample {
public void display() {
System.out.println("Public Method");
}
}

public class Main {


public static void main(String[] args) {
PublicMethodExample obj = new PublicMethodExample();
obj.display(); // Output: Public Method
}
}
2. Private Method
Scope: Accessible only within the class where it is defined.
Example:

class PrivateMethodExample {
private void display() {
System.out.println("Private Method");
}

public void show() {


display(); // Can call private method within the class
}
}

public class Main {


public static void main(String[] args) {
PrivateMethodExample obj = new PrivateMethodExample();
// obj.display(); // Error: display() has private access
obj.show(); // Output: Private Method
}
}
3. Protected Method
Scope: Accessible within the same package and in subclasses (even in a different
package).
Example:

package package1;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
public class ProtectedMethodExample {
protected void display() {
System.out.println("Protected Method");
}
}

package package2;

import package1.ProtectedMethodExample;

class SubClass extends ProtectedMethodExample {


public void show() {
display(); // Protected method accessible in subclass
}
}

public class Main {


public static void main(String[] args) {
SubClass obj = new SubClass();
obj.show(); // Output: Protected Method
}
}
4. Default (Package-Private) Method
Scope: Accessible only within the same package.
Example:

class DefaultMethodExample {
void display() { // Default access modifier
System.out.println("Default Method");
}
}

public class Main {


public static void main(String[] args) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.display(); // Output: Default Method
}
}
6 a) Develop a program to understand the command line arguments. [L6,C [5M]
O1]
Command Line Arguments
The command line argument in java is the information passed to the program at
the time of running the program. It is the argument passed through the console when
the program is run. The command line argument is the data that is written right after
the program’s name at the command line while executing the program.
Program:-
class command

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
{
public static void main(String args[])
{
for(String i:args)
System.out.println(i);
}
Output:-

b) Explain user input to program using scanner class. [L2,C [5M]


O1]
Scanner Class:- The Scanner is used to get user input, and it is found in the java.util
package.
Syntax To Import:-
import java.util.Scanner;
Syntax To Declare:-
Scanner object_name=new Scanner(System.in);
Syntax To Initialize:-
Datatype Variable_name=object_name.preferred_input;

7 a) List and explain about different data types with examples [L2,C [5M]
O1]

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Primitive:-
Int:-
 Int data type is a 32-bit signed two’s complement integer.
 Its value ranges from -217483648 to 217483647.
 Its default value is 0.
 Eg:-int a=1000;
Short:-
 Short datatype is a 16-bit signed two’s complement integer.
 Its value ranges from -32786 to 32787.
 Its default value is 0.
 Eg:-int a=1000;
Long:-
 Long data type is a 64-bit signed two’s complement integer.
 Its value ranges from -9223372036854 to 9223372036853.
 Its default value is 0.
 Eg:-int a=1000;
Float:-
 Float is a single-precision 32-bit IEEE 754 floating point .
 Its value ranges unlimited.
 Its default value is 0.0f.
 Eg:-float f=234.5f;

Double:-
 Float is a double-precision 64-bit IEEE 754 floating point .
 Its value ranges unlimited.
 Its default value is 0.0d.
 Eg:- double d=12.3;
Char:-
 Its is a single 16-bit Unicode character.
 Range lies between 0 to 65,535.
 Used to store characters.
Boolean:-
 Its is used to store only two possible values.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Values:True and False.
 Eg:- boolean a=false;
Program:-
//Data types
class datatypes
{
public static void main(String args[])
{
int num=5;
float f=5.99f;
char c=’d’;
boolean b=true;
String s=”hello”;
System.out.println(“Sreenivasulu”);
System.out.println(“Integer=”+num);
System.out.println(“Float=”+f);
System.out.println(“Char=”+c);
System.out.println(“Boolean=”+b);
System.out.println(“String=”+s);
}
}

Output:-

Non Primitive:-
String:-
 It contains a collection of characters surrounded by double quotes.
 Eg:- String s=”Hello World”
Array:-
 Arrays are used to store the multiple values in a single variable, instead of
declaring separate variables for each value.
 It can declare or define the variables in square brackets.
Class:-
 Java is associated with classes and objects along with its attributes and
methods.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 A class is like a object constructer or a blueprint for creating object.
Interface:-
 Another way to achieve abstraction in java is with interface.
 An interface is used to group related methods with empty bodies.
Object:-
 Object is created from a class we have already created a class named main.
b) Illustrate briefly type Conversion and type casting. [L3,C [5M]
O1]

Type Conversion in Java (Implicit or Automatic Conversion)

Type conversion in Java can be implicit (automatic), where the Java


compiler automatically converts one type of data to another when it’s necessary. This
typically occurs when there’s no risk of losing data, such as when converting a
smaller data type to a larger one.

Characteristics of Type Conversion (Implicit):


 Automatic: Java does this automatically when it can ensure no loss of
information.
 Safe: It’s generally safe because it occurs when there’s no risk of truncating
or losing data.
 Occurs between compatible types: Usually, Java performs implicit type
conversion between types with compatible sizes, such as from int to long,
float to double, etc.

Example

public class Main


{
public static void main(String[] args)
{
int a = 10; // Integer
double b = a; // Implicit conversion from int to double
System.out.println("The value of b is: " + b); // Output: 10.0
}}
Type Casting
Typecasting in Java is the process of converting one data type to another data type
using the casting operator. When you assign a value from one primitive data type
to another type, this is known as type casting. To enable the use of a variable in a
specific manner, this method requires explicitly instructing the Java compiler to
treat a variable of one data type as a variable of another data type.

Syntax:
<datatype> variableName = (<datatype>) value;
Types of Type Casting
There are two types of Type Casting in java:
 Widening Type Casting

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Narrow Type Casting

Widening Type Casting

A lower data type is transformed into a higher one by a process known as widening
type casting. Implicit type casting and casting down are some names for it. It occurs
naturally. Since there is no chance of data loss, it is secure. Widening Type casting
occurs when:
 The target type must be larger than the source type.
 Both data types must be compatible with each other.
Syntax:
larger_data_type variable_name = smaller_data_type_variable;

Example
// Java program to demonstrate Widening TypeCasting
import java.io.*;

class GFG {
public static void main(String[] args)
{
int i = 10;

// Wideing TypeCasting (Automatic Casting)


// from int to long
long l = i;

// Wideing TypeCasting (Automatic Casting)


// from int to double
double d = i;

System.out.println("Integer: " + i);


System.out.println("Long: " + l);
System.out.println("Double: " + d);
}
}
Output
Integer: 10
Long: 10
Double: 10.0
Narrow Type Casting
The process of downsizing a bigger data type into a smaller one is known as
narrowing type casting.Narrowing type casting is unsafe because data loss might
happen due to the lower data type’s smaller range of permitted values. A cast
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
operator assists in the process of explicit casting.

Syntax:
smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

Example
// Java Program to demonstrate Narrow type casting
import java.io.*;

class GFG {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;

System.out.println("Original Value before Casting"


+ i);
System.out.println("After Type Casting to short "
+ j);
System.out.println("After Type Casting to int "
+ k);
}
}

Output

Original Value before Casting100.245


After Type Casting to short 100
After Type Casting to int 100
8 a) What is an operator? Explain different types of operators. [L2,C [5M]
O1]
Operators:- In programming, operators are the special symbol that tells the compiler
to perform a special operation. Java provides different types of operators that can be
classified according to the functionality they provide.
 Arithmetic Operators
 Assignment Operators
 Bitwise Operators
 Relational Operators
 Ternary Operators

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Logical Operators
 Unary Operators
 Shift Operators
Arithmetic Opertors:- Arithmetic operators are the symbols used to perform basic
mathematical operators data.

Program:-
//Arithmetic operators
class arith
{
public static void main(String args[])
{
int a=10,b=5;
System.out.println(“Sreenivasulu”);
System.out.println(“a+b=”+(a+b));
System.out.println(“a-b=”+(a-b));
System.out.println(“a*b=”+(a*b));
System.out.println(“a/b=”+(a/b));
System.out.println(“a%b=”+(a%b));
}
}
Output:-

Assignment operator: These operators are used to assign values to a variable. The
left side operand of the assignment operator is a variable, and the right side operand
of the assignment operator is a value. The value on the right side must be of the
same data type of the operand on the left side. Otherwise, the compiler will raise an
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
error. This means that the assignment operators have right to left associativity, i.e.,
the value given on the right-hand side of the operator is assigned to the variable on
the left. Therefore, the right-hand side value must be declared before using it or
should be a constant.

Program:
class assign
{
public static void main(String args[])
{
int a=10,b=5;
System.out.println(“Sreenivasulu”);
a+=b;
System.out.println(a);
a-=b;
System.out.println(a);
a*=b;
System.out.println(a);
a/=b;
System.out.println(a);
a%=b;
System.out.println(a);
}
}
Output:

Bitwise Operator:- Bitwise operators are used to performing the manipulation of


individual bits of a number. They can be used with any integral type (char, short, int,
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
etc.). They are used when performing update and query operations of the Binary
indexed trees.

Truth Table:
X Y X&Y X|Y X^Y ~X
1 1 1 1 0 0
1 0 0 1 1 0
0 1 0 1 1 1
0 0 0 0 0 1
Program:-
//Bitwise operators
class bitwise
{
public static void main(String args[])
{
int a=3, b=4;
System.out.println(“Sreenivasulu”);
System.out.println(“a&b=”+(a&b));
System.out.println(“a|b=”+(a|b));
System.out.println(“a^b=”+(a^b));
System.out.println(“~a=”+(~a));
}
}
Output:-

Relational Operators:- Java Relational Operators are a bunch of binary operators


used to check for relations between two operands, including equality, greater than,
less than, etc. They return a boolean result after the comparison and are extensively
used in looping statements as well as conditional if-else statements and so on.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Program:-
//Relational operators
import java.util.*;
class comp
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
int b=obj.nextInt();
System.out.println(“Sreenivasulu”);
System.out.println(“a>b “+(a>b));
System.out.println(“a<b “+(a<b));
System.out.println(“a>=b “+(a>=b));
System.out.println(“a<=b “+(a<=b));
System.out.println(“a==b “+(a==b));
System.out.println(“a!=b “+(a!=b));
}
}
Output:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Conditional Operator:- Java ternary operator is the only conditional operator that
takes three operands. It’s a one-liner replacement for the if-then-else statement and is
used a lot in Java programming. We can use the ternary operator in place of if-else
conditions or even switch conditions using nested ternary operators. Although it
follows the same algorithm as of if-else statement, the conditional operator takes less
space and helps to write the if-else statements in the shortest way possible.

Program:-
//Ternary operator
import java.util.*;
class ternary
{
public static void main(String args[])
{
int a, b, result;
Scanner obj=new Scanner(System.in);
a=obj.nextInt();
b=obj.nextInt();
result=a>b?a:b;
System.out.println(“Sreenivasulu”);
System.out.println(result+” is big”);
}
}
Output:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Logical Operators:- Logical operators are used to perform logical “AND”, “OR” and
“NOT” operations, i.e. the function similar to AND gate and OR gate in digital
electronics. They are used to combine two or more conditions.

Program:-
//Logical And
import java.util.*;
class logicaland
{
public static void main(String args[])
{
int d;
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
int b=obj.nextInt();
int c=obj.nextInt();
d=((a>b)&&(a>c))?a:(b>c?b:c);
System.out.println(“Sreenivasulu”);
System.out.println(d+” is big”);
}
}
Output:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Program:-
//Logical Or
import java.util.*;
class or
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
char ch=obj.next().charAt(0);
System.out.println(“Sreenivasulu”);
System.out.println((ch==’a’)||(ch==’e’)||(ch==’i’)||(ch==’o’)||(ch==’u’));
}
}

Output:-

Unary Operators:- Java unary operators are the types that need only one operand to
perform any operation like increment, decrement, negation, etc. It consists of various
arithmetic, logical and other operators that operate on a single operand.
Types Description Example
Pre Increment First it performs increment and then it assigns value ++i
Post Increment First it assigns value and then it performs increment i++
Pre Decrement First it performs decrement and then it assign value --i
Post Decrement First it assigns value and then it performs decrement i--
Program:-
//Unary Operators
import java.util.*;
class unary
{
public static void main(String args[])
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
{
Scanner obj=new Scanner(System.in);
int i=obj.nextInt();
System.out.println(“Sreenivasulu”);
System.out.println(“Pre Increment=”+(++i));
System.out.println(“Post Increment=”+(i++));
System.out.println(“Pre Decrement=”+(--i));
System.out.println(“Post Decrement=”+(i--));
}
}
Output:

Shift Operator:- In Java, shift operators are used to manipulate bits. They shift bits to
the right or left.
Symbol Description Example
>> It shifts bits towards right a>>1
<< It shifts bits towards left a<<1

Program:-
//Shift Operators
import java.util.*;
class shift
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
System.out.println(“Sreenivasulu”);
System.out.println(“a>>2=”+(a>>2));
System.out.println(“a<<2=”+(a<<2));
}
}
Output:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

b) Illustrate static and final keywords with example. [L3,C [5M]


O1]
Static Keyword
The static keyword in Java is a powerful modifier used for memory management and
class-level behaviors. It can be applied to variables, methods, blocks, and nested
classes.
Static Variables (Class Variables)

 Definition: A static variable is shared among all instances of a class. Instead


of being tied to individual objects, it belongs to the class.
 Purpose: Used when a property needs to be common for all objects, such as a
constant or a counter.

Example:

class Example {
static int count = 0; // Static variable
Example() {
count++; // Increment count for every object created
}
}
public class Test {
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
System.out.println("Count: " + Example.count); // Output: Count: 2
}
}
2. Static Methods

 Definition: A static method belongs to the class rather than any object. It can
be called without creating an object of the class.
 Rules:
o Static methods cannot access instance variables or call non-static
methods directly because they don’t belong to any instance.
o They can directly access static variables and methods.

Example:

class Example
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
{
static int sum(int a, int b) {
return
a + b; // Static method
}
}
public class Test {
public static void main(String[] args) {
System.out.println(Example.sum(5, 10)); // Output: 15
}
}

3. Static Blocks

 Definition: A static block is executed when the class is loaded into memory. It
is often used for initialization tasks.
 Usage: Useful for initializing static variables or performing setup that only
needs to happen once.

Example:

class Example {
static int value;
static {
value = 42; // Static block
System.out.println("Static block executed!");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Value: " + Example.value); // Output: Static block executed!
Value: 42
}
}

Final Keyword:-
Final is the keyword which makes a variable or method to be override i.e., can’t be
modified. We can use final for both variables and methods.
Syntax:-
final public static datatype variable_name=value;
final return_type method_name( )
{
statements;
}
Program:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
class finalkey
{
public static void main(String args[])
{
int x=10;
final int y=20;
System.out.println(x+" "+y);
y=30;//this will raise an error
}
}

Output:-

9 a) List out the selection statements available in Java. Explain with an example. [L2,C [5M]
O1]
Selection Statements:-
 Simple if
 if-else
 if-else-if ladder
 nested if
 switch
Simple if:- The simple if statement is the most simple decision making statement. It
is used to decide whether a certain block of statements will be executed or not.
Syntax:
if(condition)
{
Statements;
Control flow:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Program:-
//Simple if statement
import java.util.*;
class control
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
int b=obj.nextInt();
System.out.println(“Sreenivasulu”);
if (a>b)
System.out.println(“a is big”);
}
}
Output:-

if-else:- In the statement, if the specified is true, the if block is executed. Otherwise,
the else block is executed.
Syntax:
if (condition)
{
Statements;
}
else
{
Statements;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
}
Control flow:

Program:
//Biggest of two numbers
import java.util.*;
class sample
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
int b=obj.nextInt();
System.out.println(“Sreenivasulu”);
if(a>b)
System.out.println(“a is big”);
else
System.out.println(“b is big”);
}
}
Output:

if-else-if ladder:- It is used to decide among multiple options. The if statements are
executed form top down. As soon as one of the conditions controlling the if is true,
the statements of that block is executed, and the rest of the ladder is bypassed.
Syntax:
if(condition)
{
Statements;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
}
else if(condition)
{
Statements;
}
else
{
Statements;
}
Control flow:

Program:
//To check n value is positive or negative
import java.util.*;
class statement
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
if(n>0)
System.out.println(“n is positive”);
else if(n<0)
System.out.println(“n is negative”);
else
System.out.println(“n is zero”);
}
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Output:

Nested if-else: As if present inside an if block is known as a nested if block. It is


similar to an if-else statement, except they are defined inside another if-else statement.
Syntax:
if (condition)
{
if (condition)
{
Statements;
}
else
{
Statements;
}
}
else
{
Statements;
}

Control flow:

Program:
//To find biggest from three numbers
import java.util.*;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
class sample
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
int b=obj.nextInt();
int c=obj.nextInt();
System.out.println(“Sreenivasulu”);
if(a>b)
{
if(a>c)
System.out.println(“a is big”);
else
System.out.println(“c is big”);
}
else
{
if (b>c)
System.out.println(“b is big”);
else
System.out.println(“c is big”);
}
}
}
Output:

Switch statement: A switch statement in java is used to execute a single statement


from multiple conditions. The switch statement can be used with short, byte, int, long,
enum types, etc. One or N number of case values can be specified for a switch
expression. Case values that are duplicate are not permissible. A compile-time error is
generated by the compiler if unique values are not used. The case value must be
literal or constant. Variables are not permissible. Usage of break statement is made to
terminate the statement sequence. It is optional to use this statement. If this statement
is not specified, the next case is executed.
Syntax:
switch(expression)
{
case 1: Statements;
break;
case 2: Statements;
break;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
case n: Statements;
break;
default: Statements;
break;
}
Control flow:

Program:
//To check given character is vowel or not
import java.util.*;
class select
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
char op=obj.next().charAt(0);
System.out.println(“Sreenivasulu”);
switch(op)
{
case ‘a’:System.out.println(“It is an vowel”);
break;
case ‘e’:System.out.println(“It is an vowel”);
break;
case ‘i’:System.out.println(“It is an vowel”);
break;
case ‘o’:System.out.println(“It is an vowel”);
break;
case ‘u’:System.out.println(“It is an vowel”);
break;
default:System.out.println(“It is not an vowel”);
break;
}
}
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Output:

b) Explain Precedence and associativity of operators. [L2,C [5M]


O1]
In Java, precedence and associativity determine the order in which operators are
evaluated in an expression.

 Precedence: The priority level of an operator.


 Associativity: The direction (left-to-right or right-to-left) in which operators
with the same precedence are evaluated.

Java Operator Precedence and Associativity Table

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

10 a) Classify looping statements available in Java. Explain with an example. [L4,C [5M]
O1]
Loops:
 while()
 do-while()
 for()
 for each()
while:- while is known as the most common loop, the while loop evaluates a certain
condition. If the condition is true, the code is executed. This process is continued until
the specified condition turns out to be false.
Syntax:
initialization;
while(condition)
{
Statements;
increment/decrement;
}
Control flow:

Program:
//To print n natural numbers
import java.util.*;
class sample
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=1;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
while(i<=n)
{
System.out.println(i);
i++;
}
}
}
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Output:

Program:
//Factorial of a given number
import java.util.*;
class fact
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=1,f=1;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
while(i<=n)
{
f=f*i;
i++;
}
System.out.println(“Factorial=”+f);
}
}
Output:

Program:
//Sum of n natural numbers
import java.util.*;
class sum
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=1, s=1;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
while (i<=n)
{
s=s+i;
i++;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
}
System.out.println(“Sum=”+s);
}
}

Output:

Program:
//To display fibonacci series
import java.util.*;
class Fibonacci
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=1,f1=0,f2=1,f3;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
System.out.println(f1+”\n”+f2);
while(i<=n)
{
f3=f1+f2;
f1=f2;
f2=f3;
System.out.println(f3);
i++;
}
}
}

Output:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Program:
//To check given number is prime or not
import java.util.*;
class prime
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=2,count=0;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
while(i<=(n/2))
{
if (n%2==0)
count++;
i++;
}
if (count==0)
System.out.println(“It is an prime number”);
else
System.out.println(“It is not an prime number”);
}
}
Output:

do-while: The do-while loop is similar to the while loop, the only difference being
that the condition in the do-while loop is evaluated after the execution of the loop
body. This guarantees that the loop is executed at least once.
Syntax:
Initialization;
do
{
Statements;
increment/decrement;
}while(condition);
Control Flow:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Program:
//To print “Hello” for n times
import java.util.*;
class loop
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=1;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
do
{
System.out.println(“Hello”);
i++;
}while(i<=n);
}
}
Output:

Nested While:-
A nested while loop is a while statement inside another while statement. In a nested
while loop, one iteration of the output loop is first executed, after which the inner
loop is executed.
Syntax:-
Initialization for outer loop;
while(Condition)
{
Initialization for inner loop;
while(Condition)
{
Statements;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
inc/dec;
}
inc/dec;
}
Program:-
import java.util.*;
class nested_while
{
public static void main(String args[])
{
int i=1,j=1;
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
while(i<=n)
{
j=1;
while(j<=i)
{
System.out.println(i);
j++;
}
i++;
}
}
}
Output:-

Infinite while loop:-


The while loop undergoing infinite times of loops is known as infinite while loop. It
won't terminate the loop, there is only one way to stop this is to stop execution of the
program.
Program:-
class infinite
{
public static void main(String args[])
{
while(1)
System.out.println("Hello");
}
Output:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Differences:-
While Do-While
1.First it check the condition and then 1.First it executes the body and then it
execute the block. checks the condition.
2.If the condition is false it execute 2.If the condition is false it executes
nothing. atleast once.
3.It is entry control loop. 3.It is exit control loop.
4.Semi colon(;) is not required after 4.Semicolon(;) is required after while.
while.
For loop:-
The for loop in java is used to iterate and evaluate a code multiple times. When the
number of iterations is known by the user, it is recommended to use for loop.
Syntax:-
for(Initialization;condition;increment/decrement)
{
statements;
}

Program:-
class forloop
{
public static void main(String args[])
{
for(int i=0;i<=5;i++)
System.out.println(i);
}
}
Output:-

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

Types of Represenstations of for loop:-


1. Initialization;
for(;condition;inc/dec)
{
Statements;
}
2. for(Initialization;condition;)
{
Statements;
Inc/dec;
}
3. Initialization;
for(;condition;)
{
Statements;
inc/dec;
}
Infinite for loop:-
Infinite loop is an instruction sequence that loops endlessly when a terminating
condition isn't met. Creating an infinite loop might be a programming error, but may
also be intentional based on the application behavior.
Representation:-
for (;;)
{
Statements;
}

Nested for:-
A for loop containing another for loop is known as nested for loop.
Syntax:-
for(Initialization;condition;inc/dec)
{
for(initialization;condition;inc/dec)
{
statements;
}
}
Program:-
import java.util.*;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
class nestedfor{
public static void main(String args[]){
int i,j;
Scanner obj=new Scanner(System.in);
System.out.println("Enter n value:");
int n=obj.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
System.out.println(i+" "+j);
}
}
Output:-

Program:-
import java.util.*;
class nestedfor1
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter n value:");
int n=obj.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
System.out.print("*");
System.out.println("");
}
}
}
Output:-

Program:-
import java.util.*;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
class nestedfor2
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter n value:");
int n=obj.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
System.out.print(i);
System.out.println("");
}
}
}
Output:-

b) Create a java program to find Factorial of given number. [L6,C [5M]


O1]
//Factorial of a given number
import java.util.*;
class fact
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int i=1,f=1;
int n=obj.nextInt();
System.out.println(“Sreenivasulu”);
while(i<=n)
{
f=f*i;
i++;
}
System.out.println(“Factorial=”+f);
}
}
Output:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

11 a) Classify jump statement available in Java. Explain with an example. [L4,C [5M]
O1]
Jump statements are used to alter the normal flow of control with in a program.
Break:-
The break statement is used to terminate the execution of the nearest looping
statement or switch statement.
Program:-
class break_stmt
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i==5)
break;
System.out.print(i+" ");
}
}
}
Output:-

Continue:-
The continue statement pushes the next repetition of the loop to take place. That
means its just skips the present iteration execution.
Program:-
class continue_stmt
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
{
if(i==5)
continue;
System.out.print(i+" ");
}
}
}
Output:-

b) Develop a java program to design calculator with basic operations using switch. [L6,C [5M]
O1]
Program
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // Input two numbers
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble(); // Input the operator
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result; // Perform operation using switch
switch (operator)
{
case '+': result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break; case '/':
if (num2 != 0)
{
// Avoid division by zero
result = num1 / num2;
System.out.println("Result: " + result);
}
else
{
System.out.println("Error: Division by zero is not allowed.");

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
}
break;
default:
System.out.println("Error: Invalid operator."); break;
}
scanner.close();
// Close the scanner } }
Output
Enter the first number: 10
Enter the second number: 5
Enter an operator (+, -, *, /): +
Result: 15.0

UNIT II
Classes,Objects and Methods
1 a) What is constructor overloading? [L1,CO2] [2M]
Constructor Overloading in Java refers to defining multiple constructors within a
class, each having a different number or type of parameters.
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Constructor Overloading is used
 To provide multiple ways to initialize an object.
 To allow for default, partial, or full initialization of object fields.

To make code more readable and flexible.


b) What is meant by an Nestedclass? [L1,CO2] [2M]
Nested Class in Java refers to a class defined within another class. Nested classes are
often used to logically group classes that are only used in one place, improving
encapsulation and readability.
Types of Nested Classes
In Java, nested classes are broadly classified into two categories:
1. Static Nested Class
Non-Static Nested Class (Inner Class)
c) List Access Specifiers in java. [L1,CO2] [2M]
In Java, access specifiers (modifiers) control the visibility and accessibility of classes,
methods, variables, and constructors. They determine where a particular member or
class can be accessed.
Types of Access Specifiers in Java
Java has four access specifiers:
1. Public
2. Protected
3. Default
Private
d) Define method. [L1,CO2] [2M]
A method in Java is a block of code that performs a specific task and can be executed
when called. Methods are used to define the behavior of a class or object. They are
essential for writing modular, reusable, and organized code.
accessSpecifier returnType methodName(parameterList)
{ // method body
// optional return statement }
e) What is the use of ‘this’ Keyword? [L1,CO2] [2M]
The this keyword in Java is a reference variable that refers to the current object of
the class. It is used primarily to resolve ambiguities and provide clarity when referring
to instance variables, methods, or constructors within a class.
The this keyword is used to refer to instance variables of the current object when
they are shadowed by method or constructor parameters with the same name.
2 a) Describe the definition and syntax of Class, Method and Object. [L2,CO2] [5M]
1. Class
A class is a blueprint or template for creating objects. It defines the properties (fields)
and behaviors (methods) that the objects created from the class will have. It is the
fundamental building block of object-oriented programming in Java.
Definition
 A class is a user-defined data type that serves as the template for objects. It
encapsulates data and methods to operate on that data.
Syntax
java
Copy code
class ClassName {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
// Fields (variables)
dataType variableName;

// Methods
returnType methodName(parameters) {
// Method body
}
}
Example
java
Copy code
class Car {
// Fields
String brand;
int speed;

// Method
void displayDetails() {
System.out.println("Brand: " + brand + ", Speed: " + speed + " km/h");
}
}

2. Method
A method is a block of code within a class that performs a specific task. Methods
define the behavior of a class and are invoked to execute logic.
Definition
 A method is a reusable block of code that performs an operation, such as
calculations or processing data. It can return a value or perform an action
without returning anything (void).
Syntax:
accessSpecifier returnType methodName(parameterList) {
// Method body
// Optional return statement
}
Example
class Calculator {
// Method to add two numbers
int add(int a, int b) {
return a + b;
}

// Method to print a message


void displayMessage() {
System.out.println("Welcome to Calculator");
}
}

3. Object
An object is an instance of a class. It is a real-world entity created based on the class
definition and represents a specific example of the class.
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Definition
 An object is an instance of a class that contains the actual values of fields
defined in the class and can invoke the methods of the class.
Syntax:
ClassName objectName = new ClassName();
Example
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car();
myCar.brand = "Toyota"; // Setting fields
myCar.speed = 120;

myCar.displayDetails(); // Calling a method


}
}
Output:
yaml
Copy code
Brand: Toyota, Speed: 120 km/h
Create a java program to display “Hello! Java” using Class, Object and [L6,CO2] [5M]
b)
Method.
// Define a class
class Greeting {
// Define a method to display the message
void displayMessage() {
System.out.println("Hello! Java");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Greeting class
Greeting obj = new Greeting();

// Call the method using the object


obj.displayMessage();
}
}
Explanation

1. Class Definition (Greeting):


o A class named Greeting is defined, which serves as the blueprint.
o It contains a method displayMessage() to display the message.

2. Method (displayMessage):
o The method displayMessage() is defined inside the Greeting class.
o It contains the code to print the message "Hello! Java" to the console.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
3. Object Creation (obj):
o In the main method (entry point of the program), an object of the
Greeting class is created: Greeting obj = new Greeting();.

4. Method Invocation:
o The method displayMessage() is invoked using the object:
obj.displayMessage();.

Output
Hello! Java
3 a) Define constructor. Classify the types of constructors in Java. [L4,CO2] [5M]
Constructor:-
Constructor is a method in a class which is automatically executed when we create an
object for the class. It should be declared by with no return type and it should be with
class name only.
Syntax:-
class classname
{
classname(parameters)
{
statements;
}
}
Program:-
//Constructor
import java.util.*;
class addition
{
int x,y;
addition(int a,int b)
{
x=a;
y=b;
}
void add()
{
System.out.println("Addition="+(x+y));
}
}
class constructer

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter two values to add:");
int x=ob.nextInt();
int y=ob.nextInt();
addition obj=new addition(x,y);
obj.add();
}
}
Output:-

Constructor is classified into two types

1. Default Constructor: A default constructor is a constructor provided by Java or


explicitly defined by the programmer that takes no arguments and initializes an object
with default values.

class Student {

String name;

int age;

// Default constructor

Student() {

name = "Unknown";

age = 18;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
void display() {

System.out.println("Name: " + name + ", Age: " + age);

public class Main {

public static void main(String[] args) {

Student student = new Student(); // Calls the default constructor

student.display(); // Output: Name: Unknown, Age: 18

2.Parameterized Constructor: A parameterized constructor is a constructor that takes


arguments (parameters) to initialize an object with specific values. It provides
flexibility in object creation by allowing different initial values to be assigned to fields.
class Student {
String name;
int age;

// Parameterized constructor
Student(String name, int age) {
this.name = name; // Using 'this' to refer to the current instance's variable
this.age = age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
// Creating objects using the parameterized constructor

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Student student1 = new Student("Alice", 20);
Student student2 = new Student("Bob", 22);

// Displaying details of the objects


student1.display(); // Output: Name: Alice, Age: 20
student2.display(); // Output: Name: Bob, Age: 22
}
}
b) Develop a java program to illustrate constructor overloading. [L6,CO2] [5M]
Constructor Overloading: Constructor overloading is a feature in Java that allows a
class to have more than one constructor, each with a different number or type of
parameters. It enables the creation of objects with different initializations depending on
the constructor called.
Program:-
//Constructor overloading
class overload
{
int x,y;
overload(int a,int b)
{
x=a;
y=b;
}
overload(int a)
{
x=a;
y=a;
}
overload()
{
x=10;
y=20;
}
void add()
{
System.out.println("Addition="+(x+y));
}
}
class overloading

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
{
public static void main(String args[])
{
overload obj1=new overload(30,40);
overload obj2=new overload(50);
overload obj3=new overload();
obj1.add();
obj2.add();
obj3.add();
}
}

Output:-

4 a) Create a java program for Assigning One Object to Another. [L6,CO2] [5M]
In Java, assigning one object to another means making both objects refer to the same
memory location. Changes made through one object will affect the other since they
point to the same data.

Here’s an example program demonstrating object assignment:

Code Example
class Student {
String name;
int age;

// Method to display student details


void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
// Creating the first object
Student student1 = new Student();
student1.name = "Alice";
student1.age = 20;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
// Display details of student1
System.out.println("Details of student1:");
student1.displayDetails();

// Assigning student1 to student2


Student student2 = student1;

// Display details of student2


System.out.println("Details of student2 (after assignment):");
student2.displayDetails();

// Modifying student2's properties


student2.name = "Bob";
student2.age = 22;

// Display details of both student1 and student2 after modification


System.out.println("\nDetails after modifying student2:");
System.out.println("Details of student1:");
student1.displayDetails();
System.out.println("Details of student2:");
student2.displayDetails();
}
}
Output
Details of student1:
Name: Alice, Age: 20
Details of student2 (after assignment):
Name: Alice, Age: 20

Details after modifying student2:


Details of student1:
Name: Bob, Age: 22
Details of student2:
Name: Bob, Age: 22
b) Differentiate between static and final keywords. [L4,CO2] [5M]
Static final
Indicates that a member belongs to the Used to declare constants, prevent
class rather than any instance. method overriding, or restrict
inheritance.
Shared across all objects of a class (class- Applies to individual variables,
level). methods, or classes.
Declares class-level variables shared by Declares constants that cannot be
all instances. reassigned after initialization.
Declares methods that belong to the class Prevents methods from being
and can be accessed without an object. overridden in subclasses.
Cannot be directly applied to a class. Declares a class that cannot be
inherited (final class).
static members can be modified final variables or objects cannot be

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
unless explicitly declared final. reassigned.
Does not restrict inheritance. Prevents inheritance (for classes) or
overriding (for methods).
Can be initialized once and modified Must be initialized once and cannot be
later. changed afterward.
Accessed using the class name without Access depends on the access
creating an object. modifier.
Can define static blocks for static Not applicable to blocks.
variable initialization.
Explain the application of final keyword with variable, method and class in [L2,CO2] [5M]
5 a)
detail with an example.
The final keyword in Java is used to impose restrictions on variables, methods,
and classes. It ensures immutability for variables, prevents method overriding,
and restricts inheritance for classes.
1. Final with Variables

A variable declared as final cannot have its value reassigned after it has been
initialized. It is essentially used to create constants.

Rules:

1. final variables must be initialized when declared or in a constructor.


2. Once assigned, the value cannot be changed.

Example:
class FinalVariableExample {
final int MAX = 100; // Final variable must be initialized

void display() {
// MAX = 200; // Compilation error: Cannot reassign a final variable
System.out.println("The value of MAX is: " + MAX);
}
}

public class Main {


public static void main(String[] args) {
FinalVariableExample obj = new FinalVariableExample();
obj.display(); // Output: The value of MAX is: 100
}
}
2. Final with Methods

A method declared as final cannot be overridden by subclasses. This ensures that the
implementation of the method remains unchanged.

Rules:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
1. Final methods can still be inherited but cannot be overridden.
2. Typically used when the behavior of a method is critical and should not be
altered.

Example:
class Parent {
final void display() {
System.out.println("This is a final method in the Parent class.");
}
}

class Child extends Parent {


// void display() { // Compilation error: Cannot override a final method
// System.out.println("Trying to override final method.");
// }
}

public class Main {


public static void main(String[] args) {
Child obj = new Child();
obj.display(); // Output: This is a final method in the Parent class.
}
}
3. Final with Classes

A class declared as final cannot be extended. This is useful when you want to prevent
inheritance for security or design reasons.

Rules:

1. A final class cannot have any subclasses.


2. All methods in a final class are implicitly final.

Example:
java
Copy code
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}

// class Child extends FinalClass { // Compilation error: Cannot inherit from a final
class
// }

public class Main {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display(); // Output: This is a final class.
}
}
b) Explain about accessing private members with example [L2,CO2] [5M]
In Java, private members (fields, methods, constructors) of a class are
accessible only within the same class. They cannot be accessed directly from
outside the class, including subclasses or other classes. This is part of Java's
encapsulation principle, which restricts direct access to an object's internal
details.
class Employee {
// Private members
private String name;
private double salary;

// Constructor to initialize private members


Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}

// Public getter method for 'name'


public String getName() {
return name;
}

// Public setter method for 'name'


public void setName(String name) {
this.name = name;
}

// Public getter method for 'salary'


public double getSalary() {
return salary;
}

// Public setter method for 'salary'


public void setSalary(double salary) {
if (salary > 0) {
this.salary = salary;
} else {
System.out.println("Invalid salary amount!");
}
}
}

public class Main {


public static void main(String[] args) {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
// Creating an Employee object
Employee emp = new Employee("Alice", 50000);

// Accessing private members through public methods


System.out.println("Name: " + emp.getName()); // Output: Name: Alice
System.out.println("Salary: " + emp.getSalary()); // Output: Salary: 50000.0

// Modifying private members through public methods


emp.setName("Bob");
emp.setSalary(60000);

System.out.println("Updated Name: " + emp.getName()); // Output: Updated


Name: Bob
System.out.println("Updated Salary: " + emp.getSalary()); // Output: Updated
Salary: 60000.0
}
}
6 a) Describe the access control for class members with example. [L2,CO2] [5M]
Access control in Java defines the visibility or accessibility of class members (fields,
methods, and constructors) to other classes, subclasses, or packages. Java provides
four levels of access control using access modifiers: public, protected, default (no
keyword), and private.
Access Modifiers and Their Scope

1. Public

 A public member is accessible from anywhere.


 Commonly used for methods and constants that should be universally
accessible.

class PublicExample {
public int value = 10;

public void display() {


System.out.println("Public Value: " + value);
}
}

public class Main {


public static void main(String[] args) {
PublicExample obj = new PublicExample();
obj.display(); // Accessible from another class
}
}
2. Private

 A private member is accessible only within the class where it is defined.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Used to enforce encapsulation and restrict access to sensitive data.

class PrivateExample {
private int value = 20;

private void display() {


System.out.println("Private Value: " + value);
}

public void show() {


display(); // Private method can be called within the same class
}
}

public class Main {


public static void main(String[] args) {
PrivateExample obj = new PrivateExample();
// obj.display(); // Error: Cannot access private method
obj.show(); // Output: Private Value: 20
}
}
3. Protected

 A protected member is accessible within the same package and in subclasses,


even if they are in different packages.
 Commonly used for inheritance.

package package1;

public class ProtectedExample {


protected int value = 30;

protected void display() {


System.out.println("Protected Value: " + value);
}
}

// In another package
package package2;
import package1.ProtectedExample;

class SubClass extends ProtectedExample {


public void show() {
display(); // Accessible in subclass
}
}

public class Main {


public static void main(String[] args) {
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
SubClass obj = new SubClass();
obj.show(); // Output: Protected Value: 30
}
}
4. Default (Package-Private)

 When no access modifier is specified, the member is accessible only within the
same package.
 Useful for classes or members that are internal to a package.

class DefaultExample {
int value = 40; // Default access

void display() {
System.out.println("Default Value: " + value);
}
}

public class Main {


public static void main(String[] args) {
DefaultExample obj = new DefaultExample();
obj.display(); // Accessible within the same package
}
}
b) Explain about constructor overloading with example. [L2,CO2] [5M]
Constructor Overloading: Constructor overloading is a feature in Java that allows a
class to have more than one constructor, each with a different number or type of
parameters. It enables the creation of objects with different initializations depending on
the constructor called.
Program:-
//Constructor overloading
class overload
{
int x,y;
overload(int a,int b)
{
x=a;
y=b;
}
overload(int a)
{
x=a;
y=a;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
}
overload()
{
x=10;
y=20;
}
void add()
{
System.out.println("Addition="+(x+y));
}
}
class overloading
{
public static void main(String args[])
{
overload obj1=new overload(30,40);
overload obj2=new overload(50);
overload obj3=new overload();
obj1.add();
obj2.add();
obj3.add();
}
}

Output:-

Define Method overloading. How the method can be overloaded with suitable [L2,CO2] [10M]
7
Example?
Method overloading
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading. Method overloading in Java is also known
as Compile-time Polymorphism, Static Polymorphism, or Early binding.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
1.Method Overloading: changing no. of arguments
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
In this example, we have created two methods, first add() method performs addition of
two numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance
for calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:

22
33
2.Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.
EXAMPLE:
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
8 a) Create a java program for understanding the pass by value. [L6,CO2] [5M]
Pass by Value: In the pass by value concept, the method is called by passing a value.
So, it is called pass by value. It does not affect the original parameter.
PROGRAM:
public class PBVDemo
{
int a=100;
void change(int a)
{
a=a+100;//Changing values It will be locally)
}
public static void main(String args[]){
PBVDemo p=new PBVDemo(); //Creating object
10. System.out.println(" Value (before change)="+p.a);
11. p.change(500); //Passing value

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
12. System.out.println(" Value (after change)="+p.a);
13. }
14. }
15. OUTPUT:
Value (before change)= 100
Value (after change)= 600
b) Distinguish method Overriding and method Overloading. [L4,CO2] [5M]
Distinguish method Overriding and method Overloading.
The differences between Method Overloading and Method Overriding in Java are as
follows:
SNo Method Overloading Method Overriding
.

1) Method overloading is used to Method overriding is used to provide


increase the readability of the the specific implementation of the
program. method that is already provided by its
super class.

2) Method overloading is Method overriding occurs in two


performed within class. classes that have IS-A (inheritance)
relationship.
3) In case of method In case of method
overloading, parameter must be overriding, parameter must be same.
different.
4) Method overloading is the Method overriding is the example
example of compile time of run time polymorphism.
polymorphism.
5) In java, method overloading Return type must be same or
can't be performed by changing covariant in method overriding.
return type of the method
only. Return type can be same
or different in method
overloading. But you must have
to change the parameter.

Java Method Overloading example


class OverloadingExample{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
Java Method Overriding example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
9 a) Create a java program for pass by Reference. [L6,CO2] [5M]
Pass by Reference: In the pass by reference concept, the method is called using an
alias or reference of the actual parameter. So, it is called pass by reference.
PROGRAM:
class Operation2{
int data=50;
void change(Operation2 op){
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[]){
Operation2 op=new Operation2();

System.out.println("before change "+op.data);


op.change(op);//passing object
System.out.println("after change "+op.data);

}
}
Output:
before change 50
after change 150
b) Explain about Nested Classes with example. [L2,CO2] [5M]
Explain about Nested Classes with example.
 In Java, it is possible to define a class within another class, such classes are
known as nested classes.
 Java inner class or nested class is a class that is declared inside the class or
interface.We use inner classes to logically group classes and interfaces in one
place to be more readable and maintainable.
 The scope of a nested class is bounded by the scope of its enclosing class.
 A nested class has access to the members, including private members, of the
class in which it is nested. But the enclosing class does not have access to the
member of the nested class.
 A nested class is also a member of its enclosing class.
 As a member of its enclosing class, a nested class can be
declared private, public, protected, or package-private(default).
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Example:
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
Output:
15
10 a) Elaborate method overriding with suitable example. [L3,CO2] [5M]
Elaborate method overriding with suitable example.
 If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java.
 In other words, If a subclass provides the specific implementation of the
method that has been declared by one of its parent class, it is known as method
overriding.
 Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
 Method overriding is used for runtime polymorphism
 The version of a method that is executed will be determined by the object
that is used to invoke it. If an object of a parent class is used to invoke the
method, then the version in the parent class will be executed, but if an
object of the subclass is used to invoke the method, then the version in the
child class will be executed

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example:
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Output:
Bike is running safely
Create a java program to find the factorial value of the given number using
b) [L6,CO2] [5M]
recursive method.
Create a java program to find the factorial value of the given number using recursive
method.
Recursive method.
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
Factorial Program Using Recursion in Java
class FactorialExample2{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 4 is: 24
11 a) Explain the importance of recursive methods with example program. [L2,CO2] [5M]
In Java, Recursion is a process in which a function calls itself directly or indirectly
is called recursion and the corresponding function is called a recursive function.
Using a recursive algorithm, certain problems can be solved quite easily.
Importance of Recursive Function:
A recursive function is a function that solves a problem by solving smaller instances
of the same problem. This technique is often used in programming to solve problems
that can be broken down into simpler, similar subproblems.
1. Solving complex tasks:
Recursive functions break complex problems into smaller instances of the same
problem, resulting in compact and readable code.
2. Divide and Conquer:
Recursive functions are suitable for divide-and-conquer algorithms such as merge
sort and quicksort, breaking problems into smaller subproblems, solving them
recursively, and merging the solutions with the original problem.
3. Backtracking:
Recursive backtracking is ideal for exploring and solving problems like N-Queens
and Sudoku.
4. Dynamic programming:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Recursive functions efficiently solve dynamic programming problems by solving
subproblems and combining their solutions into a complete solution.
5. Tree and graph structures:
Recursive functions are great for working with tree and graph structures, simplifying
traversal and pattern recognition tasks.
Example:
class FactorialExample2{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 4 is: 24
b) Write a java program for Nesting of Methods. [L3,CO2] [5M]
Nesting of Methods
In java, the methods and variables which we create in a class can only be called by
using the object of that class or, in case of static methods, we can directly call it by
using the name of the class. The methods and variables can be called with the help
of the dot operator. But there is a special case that a method can also be called by
another method with the help of class name, but the condition is they should be
present in the same class.
Syntax:
class Main
{
method1(){

// statements
}
method2()
{
// statements

// calling method1() from method2()


method1();
}
method3()
{
// statements
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
// calling of method2() from method3()
method2();
}
}
Example:
public class NestingMethodCalls1 {
public void Area(double r)
{
System.out.println( "****** Inside Area method ******");
double a = 4 * Math.PI * r * r;
System.out.println("Surface area of a Sphere is : " + a);
}
public void Volume(double r)
{

System.out.println("****** Inside Volume method ******");


double v = (4 / 3) * Math.PI * r * r * r;
System.out.println("Volume of a Sphere is : " + v);
}
public static void main(String args[])
{
GeeksforGeeks gfg = new GeeksforGeeks();
gfg.Area(12);
gfg.Volume(12);
}
}
Output
****** Inside Area method ******
Surface area of a Sphere is : 1809.5573684677208
****** Inside Volume method ******
Volume of a Sphere is : 5428.672105403162

UNIT III

Arrays,Inheritance and Interfaces


1 a) How to declare an array in Java? [L1,CO3] [2M]
To declare an array in Java:
 Specify the data type of the array's elements.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Use square brackets [].
 Provide the array name.
Examples:
1. Without Initialization:
int[] numbers; // Declares an integer array
String[] names; // Declares a string array
2. With Fixed Size:
int[] numbers = new int[5]; // Array of size 5
3. With Values:
int[] numbers = {1, 2, 3, 4, 5}; // Initialized with values
b) How to Access Elements of an Array in Java? [L1,CO3] [2M]
Array elements are accessed using their index. The index starts from 0.
Examples:
1. Accessing an Element:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]); // Output: 30
2. Modifying an Element:
numbers[1] = 25; // Changes the second element to 25
3. Using a Loop:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
c) What is the use of ‘Super’ Keyword? Give an example. [L1,CO3] [2M]
The super keyword in Java refers to the parent class of the current object. It is used in
the following scenarios:
1. Access Parent Class Variables:
class Parent {
String name = "Parent Class";
}

class Child extends Parent {


String name = "Child Class";

void display() {
System.out.println(super.name); // Access Parent Class name
}
}
2. Call Parent Class Methods:
class Parent {
void greet() {
System.out.println("Hello from Parent");
}
}

class Child extends Parent {


void greet() {
super.greet(); // Calls Parent's greet() method
}
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
3. Call Parent Class Constructor:
class Parent {
Parent(String message) {
System.out.println(message);
}
}

class Child extends Parent {


Child() {
super("Message from Parent Constructor");
}
}
d) What is the use of Interface? [L1,CO4] [2M]
An interface in Java is a blueprint of a class that contains:
 Abstract methods (methods without a body).
 Static or default methods with implementations (from Java 8 onward).
Uses of Interface:
1. Achieve Abstraction: An interface specifies "what to do" without specifying
"how to do it."
2. Multiple Inheritance: A class can implement multiple interfaces, overcoming
the single inheritance limitation of classes.
3. Decoupling Code: Interfaces allow unrelated classes to implement the same set
of methods.
Example:
interface Animal {
void sound(); // Abstract method
}

class Dog implements Animal {


public void sound() {
System.out.println("Bark");
}
}

class Cat implements Animal {


public void sound() {
System.out.println("Meow");
}
}
e) Define annotations. [L1,CO4] [2M]
Annotations in Java provide metadata about the code to the compiler or runtime
environment. They are not part of the program logic but are used to give additional
information.
Common Uses:
1. Compilation Instructions: (@Override, @SuppressWarnings)
2. Runtime Processing: (@Deprecated, @FunctionalInterface)
3. Frameworks: Custom annotations for configurations (e.g., Spring, JPA).
Example:
class Example {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
@Override // Indicates this method overrides a parent method
public String toString() {
return "Example Class";
}

@Deprecated // Marks this method as outdated


public void oldMethod() {
System.out.println("This is an old method");
}
}
Custom Annotation:
@interface MyAnnotation {
String value();
}

@MyAnnotation(value = "Custom Annotation Example")


class CustomAnnotatedClass {
2 Define an Array? Classify the types of arrays in Java. [L4,CO3] [10M]
An array in Java is a data structure that stores a fixed-size collection of elements of
the same data type. Arrays are used to store multiple values in a single variable, which
makes it easier to organize and manipulate data efficiently.
Key Characteristics of Arrays:
1. Fixed Size: Once an array is created, its size cannot be changed.
2. Same Data Type: All elements in the array must be of the same type (e.g., int,
float, String).
3. Index-Based Access: Each element in the array can be accessed using an
index, starting from 0.
Syntax for Declaring an Array:
java
Copy code
dataType[] arrayName; // Declaration only
dataType[] arrayName = new dataType[size]; // Declaration with size
dataType[] arrayName = {value1, value2, ...}; // Declaration with initialization
Examples:
1. Declaration and Initialization:
int[] numbers = {10, 20, 30, 40, 50}; // Integer array with 5 elements
String[] names = {"Alice", "Bob", "Charlie"}; // String array
2. Accessing Elements:
System.out.println(numbers[0]); // Outputs: 10
3. Modifying Elements:
numbers[2] = 35; // Changes the third element to 35

Types of Arrays in Java


In Java, arrays are classified based on their dimensions:

1. One-Dimensional Arrays
A one-dimensional array is the simplest form of an array, where elements are arranged
in a linear format (single row).
Syntax:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
dataType[] arrayName = new dataType[size];
dataType[] arrayName = {value1, value2, ..., valueN};
Example:
int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < numbers.length; i++) {


System.out.println(numbers[i]); // Prints elements one by one
}

2. Multi-Dimensional Arrays
Multi-dimensional arrays are arrays within arrays. The most commonly used type is
the two-dimensional array, which is like a matrix with rows and columns.
2.1 Two-Dimensional Arrays
A 2D array represents a table of data.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
dataType[][] arrayName = {{value1, value2}, {value3, value4}};
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // Accesses element in 2nd row, 3rd column: Output
6
Iterating through a 2D Array:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
2.2 Higher-Dimensional Arrays
Arrays with more than two dimensions are rare but supported.
Example:
int[][][] threeDArray = new int[3][4][5]; // 3D array with 3 layers, each 4x5

3. Jagged Arrays
A jagged array is an array of arrays where each sub-array can have a different size.
This is also known as a ragged array.
Syntax:
dataType[][] jaggedArray = new dataType[rows][];
jaggedArray[rowIndex] = new dataType[size];
Example:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2]; // First row has 2 columns
jaggedArray[1] = new int[3]; // Second row has 3 columns
jaggedArray[2] = new int[1]; // Third row has 1 column

jaggedArray[0][0] = 1;
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
jaggedArray[1][2] = 5;

for (int i = 0; i < jaggedArray.length; i++) {


for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}

Differences Between Types of Arrays


Type Description Example
One- Stores elements in a single linear int[] numbers = {1, 2, 3,
Dimensional sequence. 4};
Two- Represents a matrix or table-like int[][] matrix = {{1, 2}, {3,
Dimensional structure. 4}};
int[][] jagged = new int[3]
Jagged Array Array of arrays with different sizes.
[];

Advantages of Arrays
1. Efficient Storage: Arrays provide a compact way to store multiple values of
the same type.
2. Index-Based Access: Enables fast access to elements using indices.
3. Simplifies Code: Reduces the need for multiple variables.
3 a) Discuss about operations on array elements. [L2,CO3] [5M]
operations on array elements:

 Insertion in an array
 Deletion in the array
 Searching in the array
Insertion in the array
To insert any element in an array in java programming, you have to ask the user to
enter the array size and array element. Now ask the user to enter the element and
position where we want to insert that element at the desired position

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int size,insert,poss;
//creation of the array
int[] arr = new int[50];
//declare scanner class
Scanner sc= new Scanner(System.in);
System.out.print("enter array size ");
size=sc.nextInt();
System.out.println("enter array elements");

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
System.out.println("the array before insertion");
for(int i=0;i<size;i++)
System.out.print(arr[i]+" ");
System.out.println();
System.out.print("enter element to be insert ");
insert=sc.nextInt();
System.out.print("enter the position ");
poss=sc.nextInt();
for(int i=size;i>poss-1;i--)
arr[i]=arr[i-1];
arr[poss-1]=insert;
System.out.println("element successfully inserted");
System.out.println("the array after insertion");
for(int i=0;i<=size;i++)
System.out.print(arr[i]+" ");

}
}
Output:
enter array size 4
enter array elements
12
55
3
8
the array before insertion
12 55 3 8
enter element to be insert 2
enter the position 4
element successfully inserted
the array after insertion
12 55 3 2 8
Deletion in the array
 To delete an element from an array in Java programming, you have to
first ask the user to enter the size and elements of the array, now ask to
enter the element/number which is to be deleted.

 Now to delete that element from the array first you have to search that
element to check whether that number is present in the array or not if
found then place the next element after the founded element to the
back until the last

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
{
int size,delete,c=0;
int[] arr = new int[50];
//declare the scanner class
Scanner sc= new Scanner(System.in);
System.out.print("enter array size ");
size=sc.nextInt();
System.out.println("enter array elements");
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
System.out.println("the array before deletion");
for(int i=0;i<size;i++)
System.out.print(arr[i]+" ");
System.out.println();
System.out.print("enter element to be delete ");
delete=sc.nextInt();
for(int i=0;i<size;i++)
{
if(arr[i]==delete)
{
for(int j=i;j<size;j++)
arr[j]=arr[j+1];
c++;
break;
}
}
if(c==0)
{
System.out.print("Element Not Found");
}
else
{
System.out.println("element successfully deleted");
System.out.println("the array after deletion");
for(int i=0;i<size-1;i++)
System.out.print(arr[i]+" ");
}
}
}
Output:
enter array size 4
enter array elements
12
44
2
6
the array before deletion
12 44 2 6
enter element to be delete 2
element successfully deleted
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
the array after deletion
12 44 6
Searching in the array
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int size,search,c=0,pos=0;
int[] arr = new int[50];
Scanner sc= new Scanner(System.in);
System.out.print("enter array size ");
size=sc.nextInt();
System.out.println("enter array elements");
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
System.out.println("the array is");
for(int i=0;i<size;i++)
System.out.print(arr[i]+" ");
System.out.println();
System.out.print("enter element to be search ");
search=sc.nextInt();
for(int i=0;i<size;i++)
{
if(arr[i]==search)
{
c++;
pos=i+1;
break;
}
}
if(c==1)
System.out.println(search+" is found at the possition "+pos);
else
System.out.println("not found");
}
}
Output:
enter array size 4
enter array elements
12
33
2
8
the array is
12 33 2 8
enter element to be search 2
2 is found at the possition 3
b) Explain about 2D array and 3D array with an example. [L6,CO3] [5M]

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
2D Arrays in Java
A 2D array is an array of arrays, used to represent a table or matrix. It has rows and
columns.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
dataType[][] arrayName = {{value1, value2}, {value3, value4}};
Example of a 2D Array:
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing an element
System.out.println(matrix[1][2]); // Output: 6

// Iterating through a 2D array


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Copy code
123
456
789

3D Arrays in Java:
A 3D array is an array of 2D arrays. It can be used to represent a collection of
matrices or cubes of data.
Syntax:
dataType[][][] arrayName = new dataType[x][y][z];
dataType[][][] arrayName = {
{{value1, value2}, {value3, value4}},
{{value5, value6}, {value7, value8}}
};
Example of a 3D Array:
public class Main {
public static void main(String[] args) {
int[][][] cube = {
{
{1, 2, 3},
{4, 5, 6}
},
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
{
{7, 8, 9},
{10, 11, 12}
}
};

// Accessing an element
System.out.println(cube[1][0][2]); // Output: 9 (Layer 2, Row 1, Column 3)

// Iterating through a 3D array


for (int i = 0; i < cube.length; i++) {
for (int j = 0; j < cube[i].length; j++) {
for (int k = 0; k < cube[i][j].length; k++) {
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
Output:
Copy code
123
456

7 8 9
10 11 12

4 a) Create a Java Program to sort the elements of an array in ascending order [L6,CO3] [5M]
Java program to sort an array in ascending order using the built-in Arrays.sort()
method and a manual sorting approach:
import java.util.Arrays;

public class SortArray {


public static void main(String[] args) {
int[] numbers = {50, 10, 30, 40, 20};

// Using Arrays.sort() method


Arrays.sort(numbers);
System.out.println("Sorted Array using Arrays.sort():
"+Arrays.toString(numbers));

// Manual sorting using Bubble Sort


int[] a = {50, 10, 30, 40, 20};
for (int i = 0; i a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] a[j + 1]) {
// Swap elements

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

System.out.println("Sorted Array using Bubble Sort: " + Arrays.toString(a));


}
}
Output:
Sorted Array using Arrays.sort(): [10, 20, 30, 40, 50]
Sorted Array using Bubble Sort: [10, 20, 30, 40, 50]
b) Describe arrays of varying length with an example. [L2,CO3] [5M]
Arrays of Varying Length in Java (Jagged Arrays)
In Java, jagged arrays are arrays of arrays where each sub-array can have a different
size. This flexibility allows storing data in a non-uniform structure.
Key Points:
 Jagged arrays are declared by specifying the number of rows, but the number of
columns can vary for each row.
 Useful when dealing with irregularly structured data, like storing student grades
for different numbers of subjects.
Syntax:
dataType[][] arrayName = new dataType[rows][];
arrayName[rowIndex] = new dataType[columns];
Example:
public class JaggedArrayExample {
public static void main(String[] args) {
// Declaring a jagged array with 3 rows
int[][] a = new int[3][];

// Initializing each row with different column sizes


a[0] = new int[2]; // First row has 2 elements
a[1] = new int[4]; // Second row has 4 elements
a[2] = new int[3]; // Third row has 3 elements

// Assigning values to the jagged array


a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[1][2] = 5;
a[1][3] = 6;
a[2][0] = 7;
a[2][1] = 8;
a[2][2] = 9;

// Printing the jagged array


for (int i = 0; i < a.length; i++) {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
Output:
123
456
789
5 a) Develop a Java Program to Check if an Array Contains a Given Value. [L6,CO3] [5M]
Java program to check if a specific value exists in an array using both a linear search
and the Arrays utility class:
import java.util.Arrays;

public class ArraySearch {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;

// Method 1: Linear Search


boolean found = false;
for (int num : numbers) {
if (num == target) {
found = true;
break;
}
}
System.out.println("Using Linear Search: " + (found ? "Value Found" : "Value
Not Found"));

// Method 2: Using Arrays.asList() for non-primitive arrays


// Arrays.binarySearch() is better for sorted arrays
System.out.println("Using Arrays.binarySearch(): " +
(Arrays.binarySearch(numbers, target) >= 0 ? "Value Found" : "Value Not
Found"));
}
}
Output:
mathematica
Copy code
Using Linear Search: Value Found
Using Arrays.binarySearch(): Value Found

What is difference between arrays and vectors? Explain any 2 methods of vector [L2,CO3]
b) [5M]
with example
Difference Between Arrays and Vectors
Feature Array Vector

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Fixed size; cannot grow or shrink Dynamically resizable; grows as
Size
dynamically. needed.
Thread Safety Not synchronized; not thread-safe. Synchronized; thread-safe.
Faster as it doesn’t handle Slower due to synchronization
Performance
synchronization. overhead.
Memory Requires manual resizing or
Handles resizing automatically.
Management reallocation.
Suitable for simple, fixed-size data Suitable for dynamic, thread-safe
Usage
structures. environments.

Two Methods of Vector with Examples


Vectors are part of the java.util package and provide methods for dynamic array
manipulation. Below are two commonly used methods with examples:
1. add() Method
The add() method adds elements to the vector.
Example:
import java.util.Vector;

public class VectorAddExample {


public static void main(String[] args) {
Vector<String> fruits = new Vector<>();

// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

System.out.println("Fruits: " + fruits);


}
}
Output:
makefile
Copy code
Fruits: [Apple, Banana, Cherry]

2. remove() Method
The remove() method removes an element at a specific index or by value.
Example:
import java.util.Vector;

public class VectorRemoveExample {


public static void main(String[] args) {
Vector<String> cities = new Vector<>();
cities.add("New York");
cities.add("London");
cities.add("Tokyo");

// Removing element by index


cities.remove(1); // Removes "London"
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
// Removing element by value
cities.remove("Tokyo");

System.out.println("Cities after removal: " + cities);


}
}
Output:
less
Copy code
Cities after removal: [New York]
6 a) Explain about Inheritance .List out types of Inheritance. [L2,CO3] [5M]
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a class to acquire properties and methods from another class. It promotes code
reuse and establishes a relationship between classes.
Key Features:
1. The class inheriting properties is called the child class or subclass.
2. The class being inherited is the parent class or superclass.
3. The keyword extends is used to implement inheritance.

Types of Inheritance in Java


1. Single Inheritance: A subclass inherits from one superclass.
Example: A Dog class inherits from an Animal class.
2. Multi-level Inheritance: A class inherits from a subclass, forming a chain.
Example: Animal → Mammal → Dog.
3. Hierarchical Inheritance: Multiple subclasses inherit from one superclass.
Example: Car, Truck, and Bike inherit from Vehicle.
4. Hybrid Inheritance: A combination of multiple types of inheritance, but it is
not directly supported in Java due to the diamond problem. Interfaces are used
to achieve hybrid inheritance.

b) Create a java Program to explain multi-level inheritance. [L6,CO3] [5M]


Multi-Level Inheritance Example in Java
Below is a Java program that demonstrates multi-level inheritance:
// Base class (Parent)
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Intermediate class (Child of Animal)


class Mammal extends Animal {
void walk() {
System.out.println("This mammal walks on legs.");
}
}

// Derived class (Child of Mammal)

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
}

// Main class
public class MultiLevelInheritance {
public static void main(String[] args) {
// Creating an object of the Dog class
Dog dog = new Dog();

// Accessing methods from all levels of inheritance


dog.eat(); // Method of Animal class
dog.walk(); // Method of Mammal class
dog.bark(); // Method of Dog class
}
}
Output:
csharp
Copy code
This animal eats food.
This mammal walks on legs.
The dog barks.

Advantages of Inheritance
1. Code Reusability: Allows using existing code in new classes without rewriting
it.
2. Extensibility: Enables extending functionalities of existing classes.
3. Polymorphism: Facilitates method overriding for dynamic method dispatch.
4. Better Code Organization: Simplifies maintenance and understanding of
code.

Limitations of Inheritance
1. Tight coupling between parent and child classes.
2. May lead to a rigid structure, making it difficult to make changes in parent
classes without affecting subclasses.
3. Overuse of inheritance can lead to complexity.
7 a) Describe the use of ‘super’ and ‘final’ keyword in inheritance with an example. [L2,CO3] [5M]
super Keyword in Inheritance
The super keyword is used to refer to the immediate superclass of the current object. It
allows access to the parent class's methods, constructors, and variables.
Uses of super:
 Calling parent class constructor: The super() constructor is used to invoke
the parent class constructor.
 Accessing parent class methods and variables: The super keyword can be
used to call overridden methods and access parent class members that are
shadowed by the subclass.
Example:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
class Animal {
String name;

// Constructor of the parent class


Animal(String name) {
this.name = name;
}

void sound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {

// Constructor of the child class


Dog(String name) {
// Call to the parent class constructor
super(name);
}

// Overriding the sound method


@Override
void sound() {
super.sound(); // Calling the parent class method
System.out.println("Dog barks.");
}

void display() {
System.out.println("Dog's name is " + super.name); // Access parent class
member
}
}

public class SuperKeywordExample {


public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.sound(); // Calls the overridden method
dog.display(); // Accesses the parent class variable via super
}
}
Output:
Animal makes a sound.
Dog barks.
Dog's name is Buddy
In the above example:
 super(name) calls the constructor of the Animal class from the Dog class.
 super.sound() calls the sound() method of the parent class (Animal), which is
then followed by the subclass's overridden behavior.
 super.name accesses the name variable from the Animal class.
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
final Keyword in Inheritance
The final keyword can be applied to variables, methods, and classes to restrict
modification:
 final class: A class declared as final cannot be subclassed. This is used to
prevent further inheritance.
 final method: A method declared as final cannot be overridden by subclasses.
 final variable: A variable declared as final cannot be reassigned after
initialization.
Example:
// A final class cannot be inherited
final class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}

// This would result in a compile-time error


// class Dog extends Animal { }

public class FinalKeywordExample {


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound();
}
}
In the above example, the class Animal is declared as final. As a result, it cannot be
extended by any other class (like Dog). If you try to create a subclass of Animal, it will
lead to a compile-time error.
You can also use final to prevent overriding methods:
class Animal {
// A final method cannot be overridden by subclasses
final void sound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {


// The following line would cause a compile-time error
// void sound() {
// System.out.println("Dog barks.");
// }
}

public class FinalMethodExample {


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Calls the final method from Animal class
}
}
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Output:
css
Animal makes a sound.
In this case, the sound() method in the Animal class is declared as final, meaning it
cannot be overridden in the Dog class.
b) Create a java program to implement inheritance concept. [L6,CO3] [5M]
Java Program to Implement Inheritance Concept
Below is a simple Java program that demonstrates inheritance using the super
keyword and the use of final method:
// Parent class
class Vehicle {
String model;

// Constructor to initialize the model


Vehicle(String model) {
this.model = model;
}

// Method to display vehicle details


void display() {
System.out.println("Vehicle Model: " + model);
}

// Final method to prevent overriding


final void start() {
System.out.println("Vehicle is starting.");
}
}

// Child class
class Car extends Vehicle {

// Constructor of child class


Car(String model) {
// Calling parent class constructor using super
super(model);
}

// Overriding the display method


@Override
void display() {
super.display(); // Calling parent class method
System.out.println("This is a Car.");
}

// Method to demonstrate use of super keyword to access parent method


void showStart() {
super.start(); // Calling the final start method from parent class
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
}

public class InheritanceExample {


public static void main(String[] args) {
Car car = new Car("Tesla Model S");
car.display(); // Calls overridden method in Car
car.showStart(); // Calls the final method from Vehicle using super
}
}
Output:
Vehicle Model: Tesla Model S
This is a Car.
Vehicle is starting.
In this program:
 The Car class inherits from the Vehicle class.
 The super(model) in the Car constructor calls the constructor of the Vehicle
class to initialize the model.
 The super.display() method in the Car class calls the display() method from the
Vehicle class before adding its own functionality.
 The start() method in the Vehicle class is marked final, so it cannot be
overridden in the Car class.
8 a) Explain with example how to achieve multiple inheritance with interface. [L2,CO3] [5M]
Achieving Multiple Inheritance with Interface in Java
In Java, multiple inheritance (where a class inherits from more than one class) is not
allowed directly due to the diamond problem (ambiguity when two parent classes
have the same method). However, Java allows multiple inheritance through
interfaces.
An interface can have multiple methods, and a class can implement multiple
interfaces. This allows the class to inherit behavior from multiple sources (interfaces),
which simulates multiple inheritance.
Example of Multiple Inheritance Using Interfaces:
// First Interface
interface Animal {
void eat();
}

// Second Interface
interface Bird {
void fly();
}

// Class that implements multiple interfaces


class Eagle implements Animal, Bird {
@Override
public void eat() {
System.out.println("Eagle eats food.");
}

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
@Override
public void fly() {
System.out.println("Eagle flies high.");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
Eagle eagle = new Eagle();
eagle.eat(); // From Animal interface
eagle.fly(); // From Bird interface
}
}
Output:
Eagle eats food.
Eagle flies high.
In this example:
 Animal and Bird are two interfaces.
 Eagle implements both interfaces, inheriting the behavior of both Animal and
Bird.
 The class Eagle provides concrete implementations for the methods eat() and
fly().
This demonstrates multiple inheritance in Java through interfaces, allowing the class
to inherit functionality from both interfaces.
b) What is an abstract class? Explain all the cases to implement abstract class. [L2,CO3] [5M]
An abstract class in Java is a class that cannot be instantiated on its own. It is used to
define a base class that other classes can extend. An abstract class may have abstract
methods (methods without implementation), concrete methods (methods with
implementation), or a combination of both.
Key Features of Abstract Class:
1. Cannot be instantiated: You cannot create an object of an abstract class.
2. Can have abstract methods: These are methods that do not have any
implementation in the abstract class and must be implemented by subclasses.
3. Can have concrete methods: These are methods that are implemented in the
abstract class, which can be used directly by subclasses.
4. Can have constructors: Abstract classes can have constructors, which are
called when a subclass is instantiated.
5. Can have instance variables: Abstract classes can have fields (variables), just
like normal classes.

Implement an Abstract Class:


1. Abstract Class with Abstract Method:
// Abstract class with an abstract method
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();

// Concrete method
void sleep() {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
System.out.println("Animal is sleeping.");
}
}

// Subclass (inherited from Animal)


class Dog extends Animal {
// Providing implementation for the abstract method
@Override
void sound() {
System.out.println("Dog barks.");
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Calls the overridden method
dog.sleep(); // Calls the concrete method from the abstract class
}
}
Output:
Dog barks.
Animal is sleeping.
Explanation:
 Animal is an abstract class with an abstract method sound() and a concrete
method sleep().
 The class Dog extends Animal and provides an implementation for the sound()
method, while it can directly use the sleep() method from the Animal class.

Abstract Class Without Abstract Methods:


An abstract class can also be used without any abstract methods. This can be useful if
you want to provide a common base class with some implementation that can be
shared by subclasses.
abstract class Vehicle {
void start() {
System.out.println("Vehicle is starting.");
}

abstract void move(); // Abstract method


}

class Car extends Vehicle {


@Override
void move() {
System.out.println("Car is moving.");
}
}

public class AbstractWithoutAbstractMethods {


public static void main(String[] args) {
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Car car = new Car();
car.start(); // Concrete method from Vehicle class
car.move(); // Overridden method from Car class
}
}
Output:
Vehicle is starting.
Car is moving.
Explanation:
 Vehicle is an abstract class with one concrete method (start()) and one abstract
method (move()).
 Car extends Vehicle and provides an implementation for move(). The start()
method is directly used from the abstract class.

3. Abstract Class with Constructor:


Abstract classes can have constructors, and they are called when a subclass object is
created.
java
Copy code
abstract class Shape {
String color;

// Constructor of the abstract class


Shape(String color) {
this.color = color;
}

// Abstract method to be implemented by subclasses


abstract void draw();
}

class Circle extends Shape {


Circle(String color) {
super(color); // Calling constructor of Shape class
}

@Override
void draw() {
System.out.println("Drawing a " + color + " circle.");
}
}

public class AbstractClassWithConstructor {


public static void main(String[] args) {
Circle circle = new Circle("Red");
circle.draw(); // Calls the overridden method
}
}
Output:
arduino
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Copy code
Drawing a Red circle.
9 Describe about nested interface and inheritance of interface with an example? [L2,CO4] [10M]
Nested Interface
A nested interface is an interface that is declared inside another class or interface. The
purpose of a nested interface is to logically group functionality or to provide a
connection between the outer class and the interface.
Key Points:
1. A nested interface declared inside a class can be public, private, or protected.
2. A nested interface declared inside another interface is public and static by
default.
3. To implement a nested interface, you need to reference it using the enclosing
class or interface name.

Example of a Nested Interface in a Class


// Outer class
class OuterClass {
// Nested interface
interface NestedInterface {
void display();
}
}

// Implementing the nested interface in a class


class ImplementationClass implements OuterClass.NestedInterface {
@Override
public void display() {
System.out.println("This is the implementation of the nested interface.");
}
}

public class NestedInterfaceExample {


public static void main(String[] args) {
OuterClass.NestedInterface obj = new ImplementationClass(); // Using the nested
interface
obj.display();
}
}
Output:
This is the implementation of the nested interface.
In this example:
 NestedInterface is a nested interface inside the OuterClass.
 The class ImplementationClass implements OuterClass.NestedInterface.

Example of a Nested Interface in an Interface


// Outer interface
interface OuterInterface {
// Nested interface

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
interface NestedInterface {
void greet();
}
}

// Implementing the nested interface


class NestedInterfaceImpl implements OuterInterface.NestedInterface {
@Override
public void greet() {
System.out.println("Hello from the nested interface.");
}
}

public class NestedInterfaceInInterface {


public static void main(String[] args) {
OuterInterface.NestedInterface obj = new NestedInterfaceImpl(); // Using the
nested interface
obj.greet();
}
}
Output:
Hello from the nested interface.
In this case:
 The NestedInterface is declared inside the OuterInterface.
 It is implicitly public and static.

2. Inheritance of Interfaces
In Java, an interface can extend one or more other interfaces. When an interface
extends another interface, it inherits all the abstract methods of the parent interfaces. A
class implementing the child interface must provide implementations for all inherited
methods.
Key Points:
1. Single Inheritance: An interface can extend one interface.
2. Multiple Inheritance: An interface can extend multiple interfaces.
3. A class implementing the child interface must implement all methods from the
parent interfaces.

Example of Single Inheritance in Interfaces


// Parent interface
interface Animal {
void eat();
}

// Child interface
interface Mammal extends Animal {
void walk();
}

// Class implementing the child interface


class Dog implements Mammal {
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
@Override
public void eat() {
System.out.println("Dog eats food.");
}

@Override
public void walk() {
System.out.println("Dog walks on four legs.");
}
}

public class InterfaceInheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Method from Animal interface
dog.walk(); // Method from Mammal interface
}
}
Output:Dog eats food.
Dog walks on four legs.
In this example:
 Mammal extends Animal, inheriting the eat() method.
 The Dog class implements the Mammal interface and provides
implementations for both eat() and walk().

Example of Multiple Inheritance in Interfaces


// First parent interface
interface Flyable {
void fly();
}

// Second parent interface


interface Swimable {
void swim();
}

// Child interface extending multiple interfaces


interface Amphibious extends Flyable, Swimable {
void adapt();
}

// Class implementing the child interface


class Duck implements Amphibious {
@Override
public void fly() {
System.out.println("Duck flies in the sky.");
}

@Override
public void swim() {
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
System.out.println("Duck swims in the water.");
}

@Override
public void adapt() {
System.out.println("Duck adapts to both air and water.");
}
}

public class MultipleInterfaceInheritance {


public static void main(String[] args) {
Duck duck = new Duck();
duck.fly(); // From Flyable interface
duck.swim(); // From Swimable interface
duck.adapt(); // From Amphibious interface
}
}
Output:
Duck flies in the sky.
Duck swims in the water.
Duck adapts to both air and water.
In this example:
 The Amphibious interface extends both Flyable and Swimable.
 The Duck class implements all methods from the parent interfaces (Flyable,
Swimable) and its own method from Amphibious.
Illustrate the following
10 a) i)Static method in interface [L3,CO4] [5M]
ii)Functional interface
i) Static Method in Interface
In Java, static methods can be defined in interfaces starting from Java 8. These
methods are not inherited by implementing classes. Instead, they are accessed using the
interface name.
Key Points about Static Methods in Interface:
1. Static methods belong to the interface and cannot be overridden by
implementing classes.
2. They are used for utility or helper methods related to the interface.
3. Accessed using the interface name (InterfaceName.methodName()).
Example of Static Method in Interface:
interface MathOperations {
// Static method
static int add(int a, int b) {
return a + b;
}

// Abstract method
int multiply(int a, int b);
}

class Calculator implements MathOperations {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
@Override
public int multiply(int a, int b) {
return a * b;
}
}

public class StaticMethodInInterface {


public static void main(String[] args) {
// Accessing static method from the interface
int sum = MathOperations.add(5, 10);
System.out.println("Sum: " + sum);

// Using the implemented class to access abstract method


Calculator calc = new Calculator();
System.out.println("Product: " + calc.multiply(5, 10));
}
}
Output:
Sum: 15
Product: 50
Explanation:
 add() is a static method defined in the MathOperations interface.
 It is accessed using MathOperations.add(5, 10) in the main method.

ii) Functional Interface


A functional interface is an interface that contains exactly one abstract method.
Functional interfaces are commonly used in lambda expressions and method
references in Java.
Key Points about Functional Interfaces:
1. Can have only one abstract method.
2. Can have default and static methods.
3. Annotated with @FunctionalInterface (optional but recommended for clarity).
4. Used extensively in the context of functional programming and lambda
expressions.

Example of a Functional Interface:


@FunctionalInterface
interface Greeting {
void sayHello(String name); // Single abstract method
}

public class FunctionalInterfaceExample {


public static void main(String[] args) {
// Using a lambda expression to implement the functional interface
Greeting greet = (name) -> System.out.println("Hello, " + name + "!");
greet.sayHello("Alice"); // Calling the abstract method
}
}
Output:
Hello, Alice!
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
b) What is an interface? Rules to create an interface in java with example. [L6,CO4] [5M]
An interface in Java is a blueprint for a class. It is used to define a set of abstract
methods (methods without a body) that the implementing classes must provide.
Interfaces are a fundamental part of Java's abstraction mechanism, allowing multiple
inheritance of behavior.

Key Features of an Interface:


1. Abstract Methods: By default, all methods in an interface are abstract (before
Java 8). From Java 8, interfaces can have default and static methods.
2. Constants: All fields in an interface are implicitly public, static, and final.
3. No Constructors: Interfaces cannot be instantiated directly since they cannot
have constructors.
4. Multiple Implementation: A class can implement multiple interfaces,
enabling multiple inheritance of behavior.

Rules to Create an Interface in Java


1. Declaration:
o Use the interface keyword to declare an interface.
o Methods are abstract by default; no abstract modifier is needed.
2. Implementation:
o A class that implements an interface must provide concrete
implementations for all abstract methods unless the class itself is
abstract.
3. Access Modifiers:
o All methods in an interface are implicitly public.
o Fields are implicitly public, static, and final.
4. Extending Interfaces:
o Interfaces can extend other interfaces (multiple inheritance for
interfaces is allowed).
5. Default and Static Methods:
o From Java 8, interfaces can include default and static methods with a
body.

Example: Creating and Using an Interface


Defining an Interface
interface Animal {
// Abstract methods (implicitly public and abstract)
void eat();
void sleep();
}
Implementing the Interface
class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog eats food.");
}

@Override
public void sleep() {

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
System.out.println("Dog sleeps in the kennel.");
}
}

class Cat implements Animal {


@Override
public void eat() {
System.out.println("Cat eats fish.");
}

@Override
public void sleep() {
System.out.println("Cat sleeps on the couch.");
}
}
Using the Interface
public class InterfaceExample {
public static void main(String[] args) {
Animal dog = new Dog();
dog.eat();
dog.sleep();

Animal cat = new Cat();


cat.eat();
cat.sleep();
}
}
Output:
Dog eats food.
Dog sleeps in the kennel.
Cat eats fish.
Cat sleeps on the couch.

Rules with Examples


1. Interface Fields
java
Copy code
interface Constants {
int MAX_VALUE = 100; // Implicitly public, static, and final
}
 MAX_VALUE is a constant, accessible using Constants.MAX_VALUE.

2. Default Methods (Java 8 and above)


interface Vehicle {
void start();

// Default method with a body


default void honk() {
System.out.println("Vehicle is honking.");
}
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
}

class Car implements Vehicle {


@Override
public void start() {
System.out.println("Car is starting.");
}
}

public class DefaultMethodExample {


public static void main(String[] args) {
Vehicle car = new Car();
car.start();
car.honk(); // Using default method
}
}
Output:
Car is starting.
Vehicle is honking.

3. Static Methods (Java 8 and above)


interface Utility {
static void printMessage(String message) {
System.out.println("Message: " + message);
}
}

public class StaticMethodExample {


public static void main(String[] args) {
Utility.printMessage("Hello from static method!"); // Accessing static method
}
}
Output:
Message: Hello from static method!

4. Extending Interfaces
interface Flyable {
void fly();
}

interface Swimable {
void swim();
}

// Extending multiple interfaces


interface Amphibious extends Flyable, Swimable {
void adapt();
}

class Duck implements Amphibious {


OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
@Override
public void fly() {
System.out.println("Duck flies in the sky.");
}

@Override
public void swim() {
System.out.println("Duck swims in water.");
}

@Override
public void adapt() {
System.out.println("Duck adapts to both air and water.");
}
}
11 a) Differentiate between an interface and an abstract class. [L4,CO4] [5M]
Both interfaces and abstract classes provide abstraction in Java but differ significantly
in their design, purpose, and usage.

Feature Interface Abstract Class


Definition A blueprint for a class that A partially implemented
specifies what a class must do but class that can include
not how. abstract and concrete
methods.
Inheritance Supports multiple inheritance (a Supports single
Type class can implement multiple inheritance (a class can
interfaces). extend only one abstract
class).
Default Methods are abstract by default Can include both
Implementation (before Java 8). From Java 8, abstract methods
supports default and static (without body) and fully
methods. implemented methods
(with body).
Fields Fields are implicitly public, static, Can have instance
and final (constants). variables (non-static),
and they can have any
access modifier.
Constructors Cannot have constructors. Can have constructors
to initialize fields.
Access Methods are implicitly public in an Methods can have any
Modifiers interface. access modifier (public,
protected, private).
Implementation A class implements an interface A class extends an
using the implements keyword and abstract class using the
must define all abstract methods. extends keyword and
must define its abstract
methods.
Use Case Used to define a contract or a Used to define a
capability for unrelated classes. common base for
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
related classes.
Java Version Enhanced in Java 8 and later Available since the
(support for default and static beginning of Java.
methods).

Examples
1. Interface Example
interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method

// Default method (Java 8+)


default void sound() {
System.out.println("Animals make sounds.");
}
}

class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog eats food.");
}

@Override
public void sleep() {
System.out.println("Dog sleeps in the kennel.");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.sleep();
dog.sound(); // Using default method from the interface
}
}
Output:
go
Copy code
Dog eats food.
Dog sleeps in the kennel.
Animals make sounds.

2. Abstract Class Example


abstract class Shape {
// Abstract method
abstract double calculateArea();

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

class Circle extends Shape {


private double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Circle circle = new Circle(5.0);
circle.display(); // Calling concrete method
System.out.println("Area of the circle: " + circle.calculateArea());
}
}
Output:
This is a shape.
Area of the circle: 78.53981633974483
b) Develop a java program to implement default method in interfaces. [L6,CO4] [5M]
Java Program: Default Method in Interfaces
interface Vehicle {
// Abstract method
void start();

// Default method
default void honk() {
System.out.println("Vehicle is honking!");
}
}

class Car implements Vehicle {


@Override
public void start() {
System.out.println("Car has started.");
}

// Optional: Override the default method if needed


@Override

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
public void honk() {
System.out.println("Car horn: Beep Beep!");
}
}

class Bike implements Vehicle {


@Override
public void start() {
System.out.println("Bike has started.");
}

// Uses the default honk method from the interface


}

public class DefaultMethodExample {


public static void main(String[] args) {
Vehicle car = new Car();
car.start(); // Calls the overridden start method in Car
car.honk(); // Calls the overridden honk method in Car

Vehicle bike = new Bike();


bike.start(); // Calls the overridden start method in Bike
bike.honk(); // Calls the default honk method from the Vehicle interface
}
}

Output
Car has started.
Car horn: Beep Beep!
Bike has started.
Vehicle is honking!

UNIT IV

Packages, java Library, Exception Handling, Java I/O and File


1 a) What is a package? How to define a package? [L1,CO5] [2M]
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form,
 built-in package and
 user-defined package.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
b) Define java library. [L1,CO5] [2M]
 A Java library is a collection of pre-written code, classes, and methods that
developers can use to perform common tasks without having to write code from
scratch.
 Libraries in Java are often packaged as .jar (Java Archive) files and can
include any number of reusable components that help streamline development.
c) What is an uncaught exception? [L1,CO5] [2M]
 The uncaught exceptions are the exceptions that are not caught by the compiler
but automatically caught and handled by the Java built-in exception handler.
 Java programming language has a very strong exception handling mechanism.
It allow us to handle the exception use the keywords like try, catch, finally,
throw, and throws.
 When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the
exception occurs and terminates the thread.
d) What is class Math? [L1,CO5] [2M]
Class Math. The class Math contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric
functions.
e) Define Byte streams. [L1,CO5] [2M]
 ByteStream classes are used to read bytes from the input stream and write bytes
to the output stream. we can say that ByteStream classes read/write the data of
8-bits.

 We can store video, audio, characters, etc., by using ByteStream classes. These
classes are part of the java.io package.

 The ByteStream classes are divided into two types of classes, i.e., Input
Stream and Output Stream.

These classes are abstract and the super classes of all the Input/output stream classes.
2 a) Explain the usage of Java packages. [L2,CO5] [5M]
 Package in Java is used to group related classes. Think of it as a folder in a
file directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
Built-in Packages
 The Java API is a library of prewritten classes that are free to use, included in
the Java Development Environment.
 The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
 To use a class or a package from the library, you need to use
the import keyword
User Defined Package:
To create your own package, you need to understand that Java uses a file system
directory to store them.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
b) Illustrate packages in java SE in detail. [L3,CO5] [5M]
basic language functionality and fundamental types that is available
java.lang
without the use of an import statement.
java.util collection data structure classes
java.io file operations
java.math multiprecision arithmetics
java.nio the Non-blocking I/O framework for Java
java.net networking operations, sockets, DNS lookups, ...
java.security key generation, encryption and decryption
java.sql Java Database Connectivity (JDBC) to access databases
java.awt basic hierarchy of packages for native GUI components
Provides classes and interfaces for handling text, dates, numbers,
java.text
and messages in a manner independent of natural languages.
java.rmi Provides the RMI package.
java.time The main API for dates, times, instants, and durations.
The java.beans package contains classes and interfaces related to
java.beans
JavaBeans components.
This package provides classes and methods to create and
java.applet
communicate with the applets.
What is a Package? Explain the Packages with an example and how to import [L2,CO5] [10M]
3
packages?
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:
 Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
 Providing controlled access: protected and default have package level access
control. A protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible by
classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).
how to import packages
Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.
The general form of import statement is:
import package.name.ClassName; // To import a certain class only
import package.name.* // To import the whole package
For example:
import java.util.Date; // imports only Date class
import java.io.*; // imports everything inside java.io package
The import statement is optional in Java.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
If you want to use class/interface from a certain package, you can also use its fully
qualified name, which includes its full package hierarchy.
Here is an example to import a package using the import statement.

import java.util.Date;
class MyClass implements Date {
// body
}
The same task can be done using the fully qualified name as follows:
class MyClass implements java.util.Date {
//body
}
4 a) Illustrate Wrapper classes in java and its advantages. [L3,CO5] [5M]
A Wrapper class in Java is a class whose object wraps or contains primitive data
types. When we create an object to a wrapper class, it contains a field and in this
field, we can store primitive data types. In other words, we can wrap a primitive
value into a wrapper class object.
Advantages of Wrapper Classes
1. Collections allowed only object data.
2. On object data we can call multiple methods compareTo(), equals(), toString()
3. Cloning process only objects
4. Object data allowed null values.
Serialization can allow only object data.
b) Define Enumeration. How to use Enum keyword in java? [L2,CO5] [5M]
 Enumerations or Java Enum serve the purpose of representing a group of
named constants in a programming language.
 Java Enums are used when we know all possible values at compile time, such
as choices on a menu, rounding modes, command-line flags, etc.
 A Java enumeration is a class type. Although we don’t need to instantiate an
enum using new, it has the same capabilities as other classes.
 This fact makes Java enumeration a very powerful tool. Just like classes, you
can give them constructors, add instance variables and methods, and even
implement interfaces.
5 a) Demonstrate the auto-boxing and auto-unboxing in java. [L2,CO5] [5M]
Auto-Boxing
The automatic conversion of primitive data types into its equivalent Wrapper type is
known as boxing and opposite operation is known as unboxing. This is the new feature
of Java5. So java programmer doesn't need to write the conversion code.
Example:

class Boxing
{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
10. System.out.println(a2+" "+a3);

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
11. }
12. }
Advantage of Auto boxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is required.
Auto-Unboxing
he automatic conversion of wrapper class type into corresponding primitive type, is
known as Unboxing
13. Example:

class Unboxing
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
b) Create a java program for Date/Time formatting in java. [L6,CO5] [5M]
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormat
{
public static void main(String[] args)
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date);
10. System.out.println(strDate);
11. }
}
6 What is an Exception? Explain different types of Exception. [L2,CO5] [10M]
Exception Handling:
 The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be
maintained.
 Exception is an abnormal condition.
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in
exception. These exceptions are able to define the error situation so that we can
understand the reason of getting this error. It can be categorized into two broad
categories, i.e., checked exceptions and unchecked exception.

1. ArithmeticException: It is thrown when an exceptional condition has occurred


in an arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has
been accessed with an illegal index. The index is either negative or greater than

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to access a
class whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not accessible
or does not open.
5. IOException: It is thrown when an input-output operation failed or interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is not
found.

9. NullPointerException: This exception is raised when referring to the members


of a null object. Null represents nothing
10. NumberFormatException: This exception is raised when a method could not
convert a string into a numeric format.
11. RuntimeException: This represents an exception that occurs during runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods to
indicate that an index is either negative or greater than the size of the string
13. IllegalArgumentException : This exception will throw the error or error
statement when the method receives an argument which is not accurately fit to
the given relation or condition. It comes under the unchecked exception.
14. IllegalStateException : This exception will throw an error or error message
when the method is not accessed for the particular operation in the application. It
comes under the unchecked exception.
Checked Exception:
Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler. The compiler ensures whether the programmer
handles the exception or not. The programmer should have to handle the exception; otherwise,
the system has shown a compilation error.
7 a) What are Java’s Built-in Exception? Illustrate the importance of finally block. [L3,CO5] [7M]
Built-in Exception:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 Built-in exceptions are the exceptions which are available in Java libraries.
 These exceptions are suitable to explain certain error situations. Below is
the list of important built-in exceptions in Java.
 ArithmeticException :
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
 ArrayIndexOutOfBoundsException :
It is thrown to indicate that an array has been accessed with an illegal index.
The index is either negative or greater than or equal to the size of the array.
 ClassNotFoundException :
This Exception is raised when we try to access a class whose definition is not
found
 FileNotFoundException :
This Exception is raised when a file is not accessible or does not open.
 IOException:
It is thrown when an input-output operation failed or interrupted
 InterruptedException:
It is thrown when a thread is waiting, sleeping, or doing some processing, and
it is interrupted.
 NoSuchFieldException:
It is thrown when a class does not contain the field (or variable) specified
 NoSuchMethodException:
It is thrown when accessing a method which is not found.
 NullPointerException:
This exception is raised when referring to the members of a null object. Null
represents nothing
 NumberFormatException:
This exception is raised when a method could not convert a string into a
numeric format.
 RuntimeException:
This represents any exception which occurs during runtime.
 StringIndexOutOfBoundsException:
It is thrown by String class methods to indicate that an index is either
negative or greater than the size of the string.
Finally:
 Finally creates a block of data (code) that will be executed after
a by catch block has completed and before the code following the
try/catch block.
 The finally block will executed whether or not an exception is thrown.
 If an exception is thrown, the finally block will execute even if no
catch statement matches the exception.
 The finally clause is also executed just before the method returns, this
can be useful for closing file handles and freeing up any other resource
that might have been allocated at the beginning and the intent of
disposing of them before returning.
 The finally clause is optional.
However each try statement requires atleast one catch or a finally clause.
b) How to use of try and catch block in java? [L2,CO5] [3M]

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 A try block is the block of code (contains a set of statements) in which
exceptions can occur; it's used to enclose the code that might throw an
exception.
 The try block is always followed by a catch block, which handles the exception
that occurs in the associated try block.
 A try block must be used within the method and it must be followed by a catch
block(s) or finally block or both.

Syntax of Try block

ttry
{
/ //code that may throw an exception
}
catch(Exception)
{
/ //code
}
 A single try block can have one or several catch blocks associated with it.
 You can catch different exceptions in different catch blocks if it contains a
different exception handler.
 When an exception occurs in try block, the corresponding catch block that
handles that particular exception executes.
 So, if you have to perform different tasks at the occurrence of different
exceptions, you can use the multi-try catch in Java.
Example- creating an integer array named ‘arr’ of the size 10
class ListOfNumbers
{
public int[] arr = new int[10];
public void writeList()
{
try
{
arr[10] = 11;
}
catch (NumberFormatException e1)
{
System.out.println("NumberFormatException => " + e1.getMessage());
}
catch (IndexOutOfBoundsException e2)
{
System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
}
}
}
class Main
{
public static void main(String[] args)
{
ListOfNumbers list = new ListOfNumbers();
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
list.writeList();
}
}
8 a) Create a java program to create own exception for Negative Value Exception if [L6,CO5] [5M]
the user enter negative value.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class MyException extends Exception


{
public MyException(String str)
{
System.out.println(str);
}
}
public class SignException
{
public static void main(String[] args)throws IOException
{

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in)); System.out.print("Input
number :: ");
try
{
int num =
integer.parseInt(br
.readLine());
if(num < 0)
throw new MyException("Number is negative");
else
throw new MyException("Number is positive");
}
catch (MyException m)
{
System.out.println(m);
}
}

}
OUTPUT-1 :

Compilation: javac SignException.java Run/ execution: java


SignException Input number :: 45

Number is positive
exception.MyException

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
OUTPUT-2

Compilation: javacSignException.java Run/


execution: java SignException Input number :: -
35

Number is negative exception.MyException


b) Identify the use of throw,throws and throwable clause with examples. [L3,CO5] [5M]
 In Java, Exception Handling is one of the effective means to handle
runtime errors so that the regular flow of the application can be preserved.
 Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
Java throw
 The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code.
 We can throw either checked or unchecked exception . The throw keyword is
mainly used to throw custom exceptions.
Syntax in Java throw
throw Instance

Example:
throw new ArithmeticException("/ by zero");
Java throws
 throws is a keyword in Java that is used in the signature of a method to
indicate that this method might throw one of the listed type exceptions.
 The caller to these methods has to handle the exception using a try-catch
block.
Syntax of Java throws
type method_name(parameters) throws exception_list

exception_list is a comma separated list of all the


exceptions which a method might throw.

9 a) Differentiate Checked Exception and Unchecked Exception.


Checked Exception Unchecked Exception
Checked exceptions occur at compile Unchecked exceptions occur at
time. runtime.
The compiler checks a checked The compiler does not check these
exception. types of exceptions.
These types of exceptions can be These types of exceptions cannot
handled at the time of compilation. be a catch or handle at the time of
compilation, because they get
generated by the mistakes in the
program.
They are the sub-class of the exception They are runtime exceptions and
class. hence are not a part of the

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Exception class.
Here, the JVM needs the exception to Here, the JVM does not require the
catch and handle. exception to catch and handle.
b) Describe about multiple catch class with an example.
 Multiple catch blocks in Java are used to catch/handle multiple exceptions that
may be thrown from a particular code section.
 A try block can have multiple catch blocks to handle multiple exceptions.
Syntax:
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block
}
 The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code,
the exception is thrown to the first catch block in the list.
 If the data type of the exception thrown matches ExceptionType1, it gets
caught there.
 If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case
the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example:
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());

if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}

Discuss about the File Input Stream and File Output Stream in java with [L2,CO5] [10M]
10
examples.
Java provides I/O Streams to read and write data where, a Stream represents an input
source or an output destination which could be a file, i/o devise, other program etc.
There are two types of streams available −
 InputStream − This is used to read (sequential) data from a source.
 OutputStream − This is used to write data to a destination.
File Input Stream:
This writes data into a specific file or, file descriptor (byte by byte). It is usually
used to write the contents of a file with raw bytes, such as images.
The FileInputStream is a byte input stream class that provides methods for reading
bytes from a file. We can create an instance of this class by supplying a File or a path
name, using these two constructors:
 FileInputStream(File file)
 FileInputStream(String name)
And the following list describes the key methods implemented
by FileInputStream class:
 int available(): returns an estimate of the number of remaining bytes that can be
read.
 int read(): reads one byte of data, returns the byte as an integer value. Return -1 if
the end of the file is reached.
 int read(byte[]): reads a chunk of bytes to the specified byte array, up to the size
of the array. This method returns -1 if there’s no more data or the end of the file is
reached.
 int read(byte[], int offset, int length): reads up to length bytes of data from the
input stream.
 long skip(long n): skips over and discards n bytes of data from the input stream.
This method returns the actual number of bytes skipped.
 FileChannel getChannel(): returns the unique FileChannel object associated with
this file input stream. The FileChannel can be used for advanced file manipulation
(New IO).
 void close(): Closes this file input stream and releases any system resources
associated with the stream.

FileOutputStream
The FileOutputStream is a byte output stream class that provides methods for
writing bytes to a file. We can create an instance of this class by supplying a File or a
path name, and/or specify to overwrite or append to an existing file, using the
following constructors:
 FileOutputStream(File file)

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
 FileOutputStream(File file, boolean append): if append is true, then the bytes will
be written to the end of an existing file rather than the beginning.
 FileOutputStream(String name)
 FileOutputStream(String name, boolean append)
And the following list describes the key methods implemented
by FileOutputStream class:
 void write(int): writes the specified byte to the output stream.
 void write(byte[]): writes the specified array of bytes to the output stream.
 void write(byte[], int offset, int length): writes length bytes from the specified
byte array starting at offset to the output stream.
 FileChannel getChannel(): returns the unique FileChannel object associated with
this file output stream. The FileChannel can be used for advanced file manipulation
(New IO).
 void close(): Closes this file output stream and releases any system resources
associated with the stream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
11 a) How to create a file in java with example. [L2,CO5] [5M]
 To create a file in Java, you can use the createNewFile() method.
 This method returns a boolean value: true if the file was successfully
created, and false if the file already exists.
 Note that the method is enclosed in a try...catch block. This is
necessary because it throws an IOException if an error occurs
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile


{
public static void main(String[] args)
{
try
{
File myObj = new File("filename.txt");
if (myObj.createNewFile())
{
System.out.println("File created: " + myObj.getName());
}
else
{
System.out.println("File already exists.");
}
} catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
b) How to Write and Read a file in java with an example. [L2,CO5] [5M]
Read from a File:
 We will use the Scanner class in order to read contents from a file.
 used the Scanner class to read the contents of the text file.
EXAMPLE:
// Import the File class
import java.io.File;
// Import this class to handle errors
import java.io.FileNotFoundException;
// Import the Scanner class to read text files
import java.util.Scanner;
public class ReadFromFile
{
public static void main(String[] args)
{
try
{
// Creating an object of the file for reading the data
File myObj = new File("D:FileHandlingNewFilef1.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
System.out.println(data);
}
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
Java is the prominent programming language of the millennium!
Write to a File:
 We use the FileWriter class along with its write() method in order to write
 I have used the FileWriter class together with its write() method to write some
text into the file.
EXAMPLE:
// Import the FileWriter class
import java.io.FileWriter;
// Import the IOException class to handle errors
import java.io.IOException;
public class WriteToFile
{
public static void main(String[] args)
{
try
{
FileWriter myWriter = new
FileWriter("D:FileHandlingNewFilef1.txt");
// Writes this content into the specified file
myWriter.write(Java is the prominent programming language of the
millenium!");
// Closing is necessary to retrieve the resources allocated
myWriter.close();
System.out.println("Successfully wrote to the file.");
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
Successfully wrote to the file
12 a) List and explain File handling functions using File class. [L2,CO5] [5M]
Method Type Description
canRead() Boolean Tests whether the file is readable or

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
not
canWrite() Boolean Tests whether the file is writable or
not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of
the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the
directory
mkdir() Boolean Creates a directory
b) Illustrate different types of File operations in java. [L3,CO5] [5M]
The following are the several operations that can be performed on a file in Java :
 Create a File
 Read from a File
 Write to a File
 Delete a File
Now let us study each of the above operations in detail.
1. Create a File:
 In order to create a file in Java, you can use the createNewFile() method.
 If the file is successfully created, it will return a Boolean value true and false if
the file already exists.
EXAMPLE:
// Import the File class
import java.io.File;
// Import the IOException class to handle errors
import java.io.IOException;
public class CreateFile
{
public static void main(String[] args)
{
try
{
File Obj = new File("myfile.txt");
if (Obj.createNewFile())
{
System.out.println("File created: "+ Obj.getName());
}
else
{
System.out.println("File already exists.");
}
}
catch (IOException e)
{
System.out.println("An error has occurred.");
e.printStackTrace();
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
}
}
}
Output
An error has occurred.
2. Read from a File:
We will use the Scanner class in order to read contents from a file.
EXAMPLE:
// Import the File class
import java.io.File;
// Import this class for handling errors
import java.io.FileNotFoundException;
// Import the Scanner class to read content from text files
import java.util.Scanner;
public class ReadFromFile
{
public static void main(String[] args)
{
try
{
File Obj = new File("myfile.txt");
Scanner Reader = new Scanner(Obj);
while (Reader.hasNextLine())
{
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output
An error has occurred.
3. Write to a File:
We use the FileWriter class along with its write() method in order to write
EXAMPLE:
// Import the FileWriter class
import java.io.FileWriter;
// Import the IOException class for handling errors
import java.io.IOException;
public class WriteToFile
{
public static void main(String[] args)
{
try
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
{
FileWriter Writer= new FileWriter("myfile.txt");
Writer.write("Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e)
{
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output
An error has occurred.
4. Delete a File:
We use the delete() method in order to delete a file.
EXAMPLE:
// Import the File class
import java.io.File;
public class DeleteFile
{
public static void main(String[] args)
{
File Obj = new File("myfile.txt");
if (Obj.delete())
{
System.out.println("The deleted file is : "+ Obj.getName());
}
else
{
System.out.println("Failed in deleting the file.");
}
}
}
Output
Failed in deleting the file.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

UNIT–V
String Handling, Multithreading Programming and Java Database
Connectivity
1 a) What is String in Java ? Is String is data type? [L1,CO5] [2M]
Strings are the type of objects that can store the character of values and in Java,
every character is stored in 16 bits.A string acts the same as an array of
characters in Java.yes, A String in Java is actually a non-primitive data type,
because it refers to an object.
b) Difference between String and StringBuffer classes. [L3,CO5] [2M]
No. String StringBuffer
1) The String class is immutable. The StringBuffer class is mutable.
2) String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too memory when we concatenate t strings.
many strings because every time it
creates new instance.
3) String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you equals() method of Object class.
can compare the contents of two
strings by equals() method.
4) String class is slower while StringBuffer class is faster while
performing concatenation performing concatenation operation.
operation.
5) String class uses String constant StringBuffer uses Heap memory
pool.
c) What is the need of Thread Priorities? [L1,CO6] [2M]
Thread priorities and scheduling are important aspects of multithreading in Java.
Thread priorities allow you to influence the order in which threads are scheduled
for execution by the Java Virtual Machine (JVM)
d) What is difference between starting thread with Run () and start () method? [L1,CO6] [2M]
start() run()
Creates a new thread and the run() No new thread is created and the
method is executed on the newly created run() method is executed on the
thread. calling thread itself.
Can’t be invoked more than one time Multiple invocation is possible
otherwise
throws java.lang.IllegalStateException
Defined in java.lang.Thread class. Defined
in java.lang.Runnable interface and
must be overridden in the
implementing class.
e) List out JDBC Product Components. [L1,CO6] [2M]
JDBC has four Components:
1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
2 a) Define String. Explain different String declarations with an example. [L2,CO6] [5M]
String definition:
Strings are the type of objects that can store the character of values and in Java,
every character is stored in 16 bits i,e using UTF 16-bit encoding. A string acts
the same as an array of characters in Java.
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find
any string object with the value "Welcome" in string constant pool that is why it
will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the reference
to the same instance.
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool. The
variable s will refer to the object in a heap (non-pool).
Java String Example
StringExample.java
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
System.out.println(s2);
System.out.println(s3);
10. }}
Output:
Java
Strings
b) Create a java program to check the given string is palindrome or not. [L6,CO5] [5M]
public class PalindromeString
{
public static void main(String[] args) {
String string = "Kayak";
boolean flag = true;

//Converts the given string into lowercase


string = string.toLowerCase();

10. //Iterate the string forward and backward, compare one character at a time
11. //till middle of the string is reached
12. for(int i = 0; i < string.length()/2; i++){
13. if(string.charAt(i) != string.charAt(string.length()-i-1)){
14. flag = false;
15. break;
16. }
17. }
18. if(flag)
19. System.out.println("Given string is palindrome");
20. else
21. System.out.println("Given string is not a palindrome");
22. }
23. }
Output:

Given string is palindrome


3 Distinguish String and its methods and StringBuffer and its methods with [L5,CO5] [10M]
suitable example.
Aspect String StringBuffer
Immutable - once created, its Mutable - can be modified
Mutability
value cannot be changed. after it is created.
Less efficient in cases where More efficient for frequent
many modifications are needed, modifications, as it doesn't
Performance
as each modification creates a create new instances on
new string. modification.
StringBuffer is thread-safe and
Thread Strings are inherently thread-safe synchronized, ensuring safe
Safety due to immutability. use in multi-threaded
environments.
Memory Consumes more memory when Consumes less memory in a

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
scenario of frequent alterations
altered frequently because every
Usage as it modifies the same
alteration creates a new instance.
instance.
Provides methods for altering
Limited to operations that don't
the content,
alter the strings,
Methods like append(), insert(), delete(),
like concat(), substring(), replace
reverse(), directly altering the
(), which all return new strings.
buffer.
4 a) Illustrate String Literals with an examples. [L3,CO5] [5M]
String literals
Any sequence of characters within double quotes is treated as String
literals.
String str1 = "Hello";
String str2 = "Java";
String str3 = "123";
String str4 = ""; // An empty string
String str5 = " "; // A string containing a single space
String str6 = "Hello, world!";
String str7 = "Special characters: @#$%^&*()";
String str8 = "Escaped characters: nt"\";
String literals may not contain unescaped newline or linefeed characters.
However, the Java compiler will evaluate compile-time expressions, so the
following String expression results in a string with three lines of text:
Example:
String text = "This is a String literal\n"
+ "which spans not one and not two\n"
+ "but three lines of text.\n";
b) Create a java program to sort the given names into ascending order. [L6,CO5] [5M]
import java.io.*;
class Ascending {
public static void main(String[] args)
{
// storing input in variable
int n = 4;
// create string array called names
String names[]
= { "Rahul", "Ajay", "Gourav", "Riya" };
String temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {

// to compare one string with other strings


if (names[i].compareTo(names[j]) > 0) {
// swapping
temp = names[i];
names[i] = names[j];
names[j] = temp;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
}
}
}
// print output array
System.out.println(
"The names in alphabetical order are: ");
for (int i = 0; i < n; i++) {
System.out.println(names[i]);
}
}
}
Output
The names in alphabetical order are:
Ajay
Gourav
Rahul
Riya
5 What is Multithreading? Illustrate the ways to create multiple threads [L3,CO6] [10M]
in java.
Multithreading definition:
Multithreading in Java is a process of executing multiple threads
simultaneously.A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are used to achieve
multitasking.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides
the run() method available in the Thread class. A thread begins its life inside
run() method. We create an object of our new class and call start() method to
start the execution of a thread. Start() invokes the run() method on the Thread
object.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and
override run() method. Then we instantiate a Thread object and call start()
method on this object.
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
6 a) Discuss about life cycle of thread and its priority with neat diagram. [L2,CO6] [5M]
Lifecycle of a Thread in Java

FIGURE for flow of execution of a thread in java

A thread in java goes through five states in the span of its creation to its
termination:
1. New state: As the name suggests, the new state resembles the state when a
thread in java is just created.
Active state: A thread moves from the new state to the active state when the
thread invokes the start() method. The thread in the active state can be in a
runnable state or a running state
2Runnable state: After the creation of thread in java, when the thread is ready to
run, it is moved from the new state to the runnable state. During the runnable
state, the thread may be running or may be ready to run at any given instant of
time. In the runnable state, there is a queue where the threads lie.
3. Running state: A thread is moved from the runnable state to the running state
by the thread scheduler for its execution. By the running state, we mean that the
thread gets the CPU for its execution. Always a fixed duration of execution time is
allocated to a thread in java.
4. Waiting or blocked state: Whenever a thread in java goes to an inactive state
for some time (period i.e. not permanently), then we say that the tread is present in

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
the waiting or blocked state. Whenever the main thread calls the join () method (to
attach itself with other thread(s)), then the main method or main thread goes into
the waiting state. After invoking the join () method, the main thread waits for its
child thread to be executed first.
5. Terminated state: When the thread completes its instruction cycle (completes
execution), the thread goes into the termination state. A thread may also go into
the termination state due to some error. When the thread is not handled correctly
or when some other execution(s) is raised by the thread then the thread is
terminated as abnormal termination.
b) What is thread synchronization? Discuss with an example. [L2,CO6] [5M]
thread synchronization definition:
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.
Java Synchronized Blocks
A synchronized block in Java is synchronized on some object. All synchronized
blocks synchronize on the same object and can only have one thread executed
inside them at a time. All other threads attempting to enter the synchronized
block are blocked until the thread inside the synchronized block exits the block.
General Form of Synchronized Block
// Only one thread can execute at a time.
// sync_object is a reference to an object
// whose lock associates with the monitor.
// The code is said to be synchronized on
// the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of
multiple processes. It ensures that the shared resources are safe and in order.
2. Thread Synchronization in Java
Thread Synchronization is used to coordinate and ordering of the execution of
the threads in a multi-threaded program. There are two types of thread
synchronization are mentioned below:
 Mutual Exclusive
 Cooperation (Inter-thread communication in Java)
Example of Synchronization
// A Java program to demonstrate working of
// synchronized.

import java.io.*;

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
import java.util.*;

A Class used to send a message

class Sender {

public void send(String msg)

System.out.println("Sending\t" + msg);

try {

Thread.sleep(1000);

catch (Exception e) {

System.out.println("Thread interrupted.");

System.out.println("\n" + msg + "Sent");

class ThreadedSend extends Thread {

private String msg;

Sender sender;

ThreadedSend(String m, Sender obj)

msg = m;

sender = obj;

public void run()

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
synchronized (sender)
sender.send(msg);
}
}
}

// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}

Output
Sending Hi
Hi Sent
Sending Bye
Bye Sent
7 a) Create java program for main thread-creation of new threads. [L6,CO6] [5M]
import java.util.*;
public class MainThreadJoin {
public static void main(String[] args) {
System.out.println("Start of main thread");

// create and start a new thread


Thread otherThread = new Thread(new OtherThread());
otherThread.start();

10. try {
11. otherThread.join();
12. } catch (InterruptedException e) {
13. e.printStackTrace();
14. }

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
15.
16. System.out.println("End of main thread");
17. }
18.
19. private static class OtherThread implements Runnable {
20. public void run() {
21. System.out.println("Start of other thread");
22.
23. // do some work in the other thread
24. try {
25. Thread.sleep(5000); // simulate some work
26. } catch (InterruptedException e) {
27. e.printStackTrace();
28. }
29.
30. System.out.println("End of other thread");
31. }
32. }
33. }
Output:
Start of main thread
Start of other thread
End of other thread
End of main thread

b) Illustrate about Deadlock and race situations. [L3,CO6] [5M]


 Synchronized keyword is used to make the class or method thread-safe
which means only one thread can have the lock of the synchronized
method and use it, other threads have to wait till the lock releases and
anyone of them acquire that lock.
 It is important to use if our program is running in a multi-threaded
environment where two or more threads execute simultaneously. But
sometimes it also causes a problem which is called Deadlock.
 A condition in which the critical section (a part of the program where
shared memory is accessed) is concurrently executed by two or more
threads. It leads to incorrect behaviour of a program.
 In layman terms, a race condition can be defined as, a condition in which
two or more threads compete together to get certain shared resources.
For example, if thread A is reading data from the linked list and another thread B
is trying to delete the same data. This process leads to a race condition that may
result in run time error.

There are two types of race conditions:

1. Read-modify-write
2. Check-then-act

The read-modify-write patterns signify that more than one thread first read the
variable, then alter the given value and write it back to that variable. Let's have a

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
look at the following code snippet.

public class number


{
protected long number = 0;
public void add(long value)
{
this.number = this.number + value;
}
}
8 a) Define JDBC. Explain importance of JDBC. [L2,CO6] [5M]
JDBC Defination and importance:
 JDBC stands for Java Database Connectivity.
 JDBC was developed by JavaSoft of Sun Microsystems.
 JDBC is a standard Java API for database-independent connectivity
between the Java programming language and a wide range of databases
 It defines interfaces and classes for writing database applications in Java
by making database connections. Using JDBC you can send SQL, PL/SQL
statements to almost any relational database.
 JDBC is a Java API for executing SQL statements and supports basic SQL
functionality. It provides RDBMS access by allowing you to embed SQL
inside Java code. Since nearly all relational database management systems
(RDBMSs) support SQL, and because Java itself runs on most platforms,
JDBC makes it possible to write a single database application that can run
on different platforms and interact with different DBMSs.
 Java Database Connectivity is similar to Open Database Connectivity
(ODBC) which is used for accessing and managing database, but the
difference is that JDBC is designed specifically for Java programs,
whereas ODBC is not depended upon any language.
Why Should We Use JDBC?
Before JDBC, ODBC API was the database API to connect and execute the query
with the database. But ODBC API uses ODBC driver that is written in C language
(i.e. platform dependent and unsecured). That is why Java has defined its own API
(JDBC API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform
the following activities:

1. Connect to the database


2. Execute queries and update statements to the database

Retrieve the result received from the database.


b) Explain the different types of JDBC drivers in detail. [L2,CO6] [5M]
JDBC Driver:
JDBC Driver is a software component that enables java application to interact
with the database. There are 4 types of JDBC drivers:
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge drive
converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your database
instead of the JDBC-ODBC Bridge.
Advantages:
 easy to use.
 can be easily connected to any database.
Disadvantages:
 Performance degraded because JDBC method call is converted into the
ODBC function calls.
The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls in
calls of the database API. It is not written entirely in java.

Advantage:
 performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.

Advantage:
 No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is know
driver. It is fully written in Java language.

Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
Disadvantage:
 Drivers depend on the Database.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Identify JDBC environment setup and establishing JDBC database
9 [L3,CO6] [10M]
connections.
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step 1 – Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections
Java Database Connectivity

Let us discuss these steps in brief before implementing by writing suitable code
to illustrate connectivity steps for JDBC.
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using
it in the program. Registration is to be done once in your program. You can
register a driver in one of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of
using new or create objects. The following example uses Class.forName() to
load the Oracle driver as shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
DriverManager is a Java inbuilt class with a static member register. Here we call
the constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)

 user: Username from which your SQL command prompt can be accessed.
 password: password from which the SQL command prompt can be
accessed.
 con: It is a reference to the Connection interface.
 Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used, @localhost is the IP
Address where a database is stored, 1521 is the port number and xe is the service
provider. All 3 parameters above are of String type and are to be declared by the
programmer before calling the function. Use of this can be referred to form the
final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The
JDBCStatement, CallableStatement, and PreparedStatement interfaces define the
methods that enable you to send SQL commands and receive data from your
database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();

Note: Here, con is a reference to Connection interface used in previous step .


Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an
SQL Query. Now we know we can have multiple types of queries. Some of them
are as follows:
 The query for updating/inserting a table in a database.
 The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute
queries of retrieving values from the database. This method returns the object of
ResultSet that can be used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to
execute queries of updating/inserting.
Step 6: Closing the connections
So finally we have sent the data to the specified location and now we are on the
verge of completing our task. By closing the connection, objects of Statement
and ResultSet will be closed automatically. The close() method of the
Connection interface is used to close the connection. It is shown below as
follows:
con.close();
10 Discuss about JDBC architecture and explain in detail. [L2,CO6] [10M]
Architecture of JDBC
OBJECT OREINTED PROGRAMING THROUGH JAVA
Course Code: 23CS0508 R23

Description:
1. Application: It is a java applet or a servlet that communicates with a data
source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important interfaces defined in
JDBC API are as follows: Driver interface , ResultSet Interface , RowSet
Interface , PreparedStatement interface, Connection inteface, and cClasses
defined in JDBC API are as follows: DriverManager class, Types class, Blob
class, clob class.
3. DriverManager: It plays an important role in the JDBC architecture. It uses
some database-specific drivers to effectively connect enterprise applications
to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need
a JDBC driver that intelligently communicates with the respective data
source.
Types of JDBC Architecture(2-tier and 3-tier)
The JDBC architecture consists of two-tier and three-tier processing models to
access a database. They are as described below:
1. Two-tier model:

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

A java application communicates directly to the data source. The JDBC


driver enables the communication between the application and the data
source. When a user sends a query to the data source, the answers for those
queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which
a user is connected. This is known as a client/server configuration, where
the user’s machine acts as a client, and the machine has the data source
running acts as the server.

2. Three-tier model:

In this, the user’s queries are sent to middle-tier services, from which the
commands are again sent to the data source. The results are sent back to the
middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
11 List and explain five steps in JDBC connection establishment with example [L2,CO6] [10M]
program.
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step 1 – Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections
Java Database Connectivity

import java.io.*;
import java.sql.*;

class Exampleprogram {
public static void main(String[] args) throws Exception
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSet rs

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db

System.out.println(name); // Print result on console


st.close(); // close statement
con.close(); // close connection
System.out.println("Connection Closed....");
}
}

Output:

12 a) Create a java program for displaying text and image using java FX GUI. [L6,CO6] [5M]
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class ImageExample extends Application {


@Override
public void start(Stage stage) throws FileNotFoundException {
//Creating an image
Image image = new Image(new FileInputStream("path of the image"));

//Setting the image view


ImageView imageView = new ImageView(image);

//Setting the position of the image


imageView.setX(50);
imageView.setY(25);

//setting the fit height and width of the image view


imageView.setFitHeight(455);
imageView.setFitWidth(500);

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);

//Creating a Group object


Group root = new Group(imageView);

//Creating a scene object


Scene scene = new Scene(root, 600, 500);

//Setting title to the Stage


stage.setTitle("Loading an image");

//Adding scene to the stage


stage.setScene(scene);

//Displaying the contents of the stage


stage.show();
}
public static void main(String args[]) {
launch(args);
}
}

Compile and execute the saved java file from the command prompt using the
following commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls
ImageExample.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls
ImageExample
b) Explain about various mouse events with example. [L2,CO6] [5M]
Handling Mouse Event
Mouse event is fired when the mouse button is pressed, released, clicked, moved
or dragged on the node.
Following table shows the user actions and associated event handling activities -

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23
Programming Example
package myjavafxapplication;
import javafx.application. Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input. MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape: Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class MyJavaFXApplication extends Application {
@Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(50,50,100,100);
rect.setArcWidth(20);
rect.setArcHeight(20);
rect.setFill(Color.BLUE);
Text text = new Text (20,20,"Click on the rectangle to change its color");
//Handling the mouse event
rect.setOnMouseClicked(e->{
rect.setFill(Color.RED);
});
Group root = new Group (rect,text);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Mouse Event Demo");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output

OBJECT OREINTED PROGRAMING THROUGH JAVA


Course Code: 23CS0508 R23

OBJECT OREINTED PROGRAMING THROUGH JAVA

You might also like