r23 Oops Qb With Answers
r23 Oops Qb With Answers
UNIT I
Simple
Object-Oriented
Distributed
Compiled and Interpreted
Robust
Secure
Architecture-Neutral
Portable
High Performance
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.
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. }
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]
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;
Backslash Literals:
Java supports some special backslash character literals known as backslash literals.
They are used in formatted output. For example:
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);
}
}
class PrivateMethodExample {
private void display() {
System.out.println("Private Method");
}
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 DefaultMethodExample {
void display() { // Default access modifier
System.out.println("Default Method");
}
}
7 a) List and explain about different data types with examples [L2,C [5M]
O1]
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.
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.
Example
Syntax:
<datatype> variableName = (<datatype>) value;
Types of Type Casting
There are two types of Type Casting in java:
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;
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;
Output
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:
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:-
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:-
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:-
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:-
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:-
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:-
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:
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;
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”);
}
}
Control flow:
Program:
//To find biggest from three numbers
import java.util.*;
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;
}
}
}
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:
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:
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:-
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:-
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:-
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.");
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.
// 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;
}
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;
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.
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
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 18;
// 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);
}
}
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.
Code Example
class Student {
String name;
int age;
A variable declared as final cannot have its value reassigned after it has been
initialized. It is essentially used to create constants.
Rules:
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);
}
}
A method declared as final cannot be overridden by subclasses. This ensures that the
implementation of the method remains unchanged.
Rules:
Example:
class Parent {
final void display() {
System.out.println("This is a final method in the Parent class.");
}
}
A class declared as final cannot be extended. This is useful when you want to prevent
inheritance for security or design reasons.
Rules:
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
// }
1. Public
class PublicExample {
public int value = 10;
class PrivateExample {
private int value = 20;
package package1;
// In another package
package package2;
import package1.ProtectedExample;
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);
}
}
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
}
}
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;
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
}
}
// statements
}
method2()
{
// statements
UNIT III
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");
}
}
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:
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;
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");
}
}
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]
// Accessing an element
System.out.println(matrix[1][2]); // Output: 6
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)
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;
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
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
2. remove() Method
The remove() method removes an element at a specific index or by value.
Example:
import java.util.Vector;
// Main class
public class MultiLevelInheritance {
public static void main(String[] args) {
// Creating an object of the Dog class
Dog dog = new Dog();
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:
void sound() {
System.out.println("Animal makes a sound.");
}
}
void display() {
System.out.println("Dog's name is " + super.name); // Access parent class
member
}
}
// Child class
class Car extends Vehicle {
// Second Interface
interface Bird {
void fly();
}
// Concrete method
void sleep() {
@Override
void draw() {
System.out.println("Drawing a " + color + " circle.");
}
}
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.
// Child interface
interface Mammal extends Animal {
void walk();
}
@Override
public void walk() {
System.out.println("Dog walks on four legs.");
}
}
@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.");
}
}
// Abstract method
int multiply(int a, int b);
}
@Override
public void sleep() {
@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();
4. Extending Interfaces
interface Flyable {
void fly();
}
interface Swimable {
void swim();
}
@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.
Examples
1. Interface Example
interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
@Override
public void sleep() {
System.out.println("Dog sleeps in the kennel.");
}
}
Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
// Default method
default void honk() {
System.out.println("Vehicle is honking!");
}
}
Output
Car has started.
Car horn: Beep Beep!
Bike has started.
Vehicle is honking!
UNIT IV
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.
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);
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.
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;
}
OUTPUT-1 :
Number is positive
exception.MyException
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
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException 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)
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
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.
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;
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:
// 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
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
import java.io.*;
class Sender {
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
catch (Exception e) {
System.out.println("Thread interrupted.");
Sender sender;
msg = m;
sender = obj;
// 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);
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");
10. try {
11. otherThread.join();
12. } catch (InterruptedException e) {
13. e.printStackTrace();
14. }
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
We can use JDBC API to handle database using Java program and can perform
the following activities:
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.
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.
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()
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();
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:
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.
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
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;
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 -