0% found this document useful (0 votes)
27 views

Oops Course Material r23

Uploaded by

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

Oops Course Material r23

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Question Bank(R23) - III SEM


(23PC0504) OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT-1
TEN MARKS QUESTIONS:

QNo Question BTL

1. What are the different available operators in java. 1

2.. List out and explain the features of java programming. 1

3. Explain the key attributes of object oriented programming. 2

4. Explain the working principle of java virtual machine (JVM) and how you can say 2
that java is architectural neutral.

5. Differentiate break and continue with an example. 4

6. Sita wants to develop a program to find the average marks of her friends. Which 5
type of variable do you prefer to store the total number of students and why?

7. Sree wants to develop a java program to find her grade. Help sree by suggesting a 3
programming construct and develop it.

8. Differentiate between implicit and explicit type conversion with an example. 4

9. 5
Raju and ravi evaluate the following expressions

● i)x=10;
● x+=(x++)+(++x)+x;

In the above expression Raju got the x value as 45 and Ravi got the x value as 42.
Decide whose answer is correct.

● ii)int a=10,b=2,x=0;
● x=a+b*a+10/2*a;
● print x;
In the above expression Raju got the x value as 170 and Ravi got the x value as 80.
Decide whose answer is correct considering the precedence of operators and
associativity.

10. Develop a java program to implement arithmetic operations on two integers. 6

TWO MARKS QUESTIONS:

1. State any four features of java.[1]


2. What is byte code. Why java is called as true object oriented programming language.[2]
3. Evaluate the result while comparing two strings using == and equals() method.[5]
4. List any four string handling functions.[1]
5. What is the role of JVM.[[4]
6. Implement the concept of automatic type promotion in expressions with an example.[3]
7. Explain the term encapsulation.[2]
8. Explain the term inheritance.[2]
9. Explain the term polymorphism.[2]
10. Create a java program to swap two numbers.[6]

TEN MARKS QUESTIONS

1. What are the different available operators in java.


OPERATORS
● An operator is a symbol which tells the compiler to perform a particular operation on operands.
Ex: a + b. a and b are operands ‘+’ is an operator meant for addition operation.
● Categories of operators:
· Arithmetic operators
· Assignment operator
· Unary operators
· Relational operators
· Logical operators or short circuit operators
· Boolean operators
· Bitwise operators
· Ternary or conditional operator
· Member operator
· Instance of operator
· New operator
· Cast operator.
● Arithmetic operators:
Operator Operation example

+ Addition, string 12+10;


concatenation
String s2=”one”,s3=”two”;

String s1=s2+s3;
- Subtraction Int x=4,y=3,z; z=y-x;

* Multiplication Int x=4,y=3,z; z=y*x;

/ Division Int x=4,y=3,z; z=y/x;

% Modulus operator Int x=4,y=3,z; z=y%x;

(gives remainder)

● Assignment operator:
This is used to store a value or variable or an expression into a variable.
Ex: int x=3, y=5, z;
z= x; z=x/3+y;
● Unary operators:
­Operator Operation Example

- Unary minus(negates given Int x=5;


value).
System.out.print(-x));

++ Increments a variable value by Int x=5;


1.
System.out.print(x++);

-- decrements a variable value by Int x=5;


1.
System.out.print(x--);

● Preincrement operator allows incrementation first and then other operations are performed.
Ex: int x=10;
System.out.print(++x);// gives result 11 because incrementation first happens & then
print operation happens.
● Postincrement operator allows other operations to be performed first and then incrementation
happens.
Ex: int x=10;
System.out.print(x++);// gives result 10 because print operation happens
first incrementation then happens.

● Predecrement operator allows decrementation first and then other operations are performed.
Ex: int x=10;
System.out.print(--x);// gives result 9 because decrementation first happens & then
print operation happens.
● Postdecrement operator allows other operations to be performed first and then decrementation
happens.
Ex: int x=10;
System.out.print(x--);// gives result 10 because print operation happens
first decrementation then happens.
● Relational Operators:
These are used to perform comparison between elements.
Operator Operation example

>(greater than) Evaluates to true if element greater System.out.print(2>3);


than other. Otherwise false

>=(greater than or Evaluates to true if element greater System.out.print(2>=3);


equal to) than or equal to other. Otherwise
false

<(lesser than) Evaluates to true if element lesser System.out.print(2<3);


than other element. Otherwise false.

<=(lesser than or Evaluates to true if element lesser System.out.print(2<=3);


equal to) than or equal to other element
.otherwise false.

==(equal to) Evaluates to true if both elements System.out.print(2==3);


are equal. otherwise false.

!= (not equal to) Evaluates to true if both elements System.out.print(2!=3);


are equal. otherwise false.

● Logical Operators:
This is used to construct compound conditions.
Operator Operation Example

&&(and Evaluates to true if each simple System.out.print(a>b


operator) condition evaluates to true && b<c);
otherwise false return.

||(or operator) Evaluates to true if any one of System.out.print(a>b||


simple conditions evaluates to b<c);
true otherwise false return.
!(not operator) Evaluates to true if condition System.out.print(!(a>
evaluates to false otherwise true b));
returns.

● Boolean operators:
These operators act on Boolean variables and produce Boolean type result.

Operators Operation Example(a=true b=false)

&(Boolean and operator) Returns true if both variables true. System.out.print(a&b)//returns


Otherwise false returns. false

|(Boolean or operator) Returns true if any variable is true. System.out.print(a|b)//returns


Otherwise false returns. true

!(Boolean not operator) Converts true to false and vice-versa. System.out.print(!(a|b))//returns


false

● Bitwise operators:
These operators act on individual bits of a number and produce the appropriate result.
Operators Operation Example x=10, y=11

~(Bitwise Gives complement of a given number (~x)=-11


Complement
Operator)

& (Bitwise and Gives 1 if both bits are 1. Otherwise false System.out.print(x&y);//returns
Operator ) returns 00001010

|(Bitwise or Gives 1 if any of the bits are 1. Otherwise System.out.print(x|y);//returns


Operator) false returns. 00010100

^(Bitwise xor Gives 1 if odd number of 1s present in System.out.print(x^y);//returns


Operator) input. Otherwise false returns. 00000001

<<(Bitwise left Shifts bits to the left with the specified System.out.print(x<<2);//returns
shift operator) number of times. 00101000
>>(Bitwise right Shifts bits to the right with the specified System.out.print(x>>2);//returns
shift operator) number of times. 00000010

>>>(Bitwise Shifts bits to the right with the specified


zero fill right number of times and fill left side empty
shift operator) places with zeroes.

● Ternary Operator or Conditional Operator


This acts an an alternative for if else statement.
Syntax: variable =expression1? expression2:expression3;
Example: max = (a>b)? a :b;
If exp1 evaluates to true exp2 will be executed. Otherwise exp3 will be executed.

● Member operator (.)


This is used in 3ways.
Ø Used when refer to subpackage and class of a package.
Example: import javax.swing.JOptionPane;
Ø Used when refer to variable of a class or object.
Example: System.out
Ø Used when refer to method of a class or object.
Example: Math.sqrt(23);

● instanceof Operator
This is used to test if an object belongs to a (class or interface) or not.
Syntax: Boolean variable= object instanceof class;
Example: Boolean x= custobj instanceof customer;

● New operator
new operator is often used to create objects to classes.
Syntax: classname obj=new classname();
Example: customer custobj=new customer();

● Cast operator
Cast operator is used to convert one data type into another data type.
Syntax: datatype target-var=(target-datatype)variable;
Example: int x;
float y=24.5678;
x=(int)y;

● Priority of operators
In an expression some of the operators will execute first and some operators will execute next.

To determine which operators execute first priority will be assigned to operators.

The priority is as follows.


Priority Operators
1st () , []

2nd ++ , --

3rd *, /, %

4th +, -

5th Relational operators

6th Boolean and bitwise operators

7th Logical operators

8th Ternary operator

9th Assignment operator

2. List out and explain the features of java programming.


● Simple
● Secure
● Portable
● Robust
● Multithreaded
● Architecture-neutral
● Interpreted
● High performance
● Distributed
● Dynamic

Simple

● Java was designed to be easy for the professional programmer to learn and use effectively.
● If you already understand the basic concepts of object-oriented programming, learning Java will
be even easier.
● Best of all, if you are an experienced C++ programmer, moving to Java will require very little
effort.
● Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most
programmers have little trouble learning Java.

Object-Oriented

● Although influenced by its predecessors, Java was not designed to be source-code compatible
with any other language.
● Java manages to strike a balance between the purist’s “everything is an object” paradigm and the
pragmatist’s “stay out of my way” model.
● The object model in Java is simple and easy to extend, while primitive types, such as integers, are
kept as high-performance nonobjects.

Robust

● The ability to create robust programs was given a high priority in the design of Java.
● To gain reliability, Java restricts you in a few key areas to force you to find your mistakes early in
program development.
● Because Java is a strictly typed language, it checks your code at compile time. However, it also
checks your code at run time.
● To better understand how Java is robust, consider two of the main reasons for program failure:
memory management mistakes and mishandled exceptional conditions (that is, run-time errors).
● Memory management can be a difficult, tedious task in traditional programming environments.
● For example, in C/C++, the programmer will often manually allocate and free all dynamic
memory.
● This sometimes leads to problems, because programmers will either forget to free memory that
has been previously allocated or, worse, try to free some memory that another part of their code is
still using
● Java virtually eliminates these problems by managing memory allocation and deallocation for
you.
● Java helps in this area by providing object-oriented exception handling. In a well-written Java
program, all run-time errors can—and should—be managed by your program.

Multithreaded

● Java was designed to meet the real-world requirement of creating interactive, networked
programs.
● Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.
● Java’s easy-to-use approach to multithreading allows you to think about the specific behavior of
your program, not the multitasking subsystem.

Architecture-Neutral

· A central issue for the Java designers was that of code longevity and portability. At the time of
Java’s creation, one of the main problems facing programmers was that no guarantee existed that if
you wrote a program today, it would run tomorrow—even on the same machine. Operating system
upgrades, processor upgrades, and changes in core system resources can all combine to make a
program malfunction. The Java designers made several hard decisions in the Java language and the
Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run anywhere,
any time, forever.” To a great extent, this goal was accomplished.

Interpreted and High Performance

● As described earlier, Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode.
● This code can be executed on any system that implements the Java Virtual Machine.
● The Java bytecode was carefully designed so that it would be easy to translate directly into native
machine code for very high performance by using a just-in-time compiler.
● Java run-time systems that provide this feature lose none of the benefits of the
platform-independent code.
Distributed

● Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols.
● In fact, accessing a resource using a URL is not much different from accessing a file.
● Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke
methods across a network.

Dynamic

● Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time.
● This makes it possible to dynamically link code in a safe and expedient manner.

3. Explain the key attributes of object oriented programming.

The oops concepts or key attributes of oop are encapsulation, inheritance, and polymorphism.

Encapsulation:

● Encapsulation is the mechanism of hiding the internal details and allowing a simple
interface which ensures that the object can be used without having to know its internal
details.
● Example: A swipe machine encapsulates/hides internal circuitry from all users and
provides simple interface for access by every user.
● In java, encapsulation is achieved by binding data and methods in a single entity called
class and hiding data behind methods and allowing the interface with the public methods
of class.
● The following program demonstrates the concept of encapsulation.+

● In the above program data and methods are encapsulated in a class called Customer and
data is hidden from user by declaring them to private and interface is allowed to setter and
getter methods.

Inheritance:

● Inheritance is a mechanism by which we can define generalized characteristics and


behavior and also create specialized ones. The specialized ones automatically inherit all
the properties of generalized ones.
● Inheritance can be achieved in java with the extends keyword.

● For example in the above diagram, Vehicle is a generalized class with its own
characteristics and behavior, and two-wheeler, four-wheeler classes are specialized ones
which inherit all the properties of generalized ones like ID, Name, LicenseNumber.

Polymorphism:

● The ability of an object/operation to behave differently in different situations is called


polymorphism.
In the above program the same move() operation is behaving differently in different situations.

4. Explain the working principle of java virtual machine (JVM) and how you can say that java
is architectural neutral.

Java’s Magic: The Bytecode

● The key that allows Java to solve both the security and the portability problems just described is
that the output of a Java compiler is not executable code. Rather, it is bytecode.
● Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time
system, which is called the Java Virtual Machine (JVM).
● In essence, the original JVM was designed as an interpreter for bytecode.
● The fact that a Java program is executed by the JVM helps solve the major problems associated
with web-based programs.
● Translating a Java program into bytecode makes it much easier to run a program in a wide
variety of environments because only the JVM needs to be implemented for each platform.
● Once the run-time package exists for a given system, any Java program can run on it.
● If a Java program were compiled to native code, then different versions of the same program
would have to exist for each type of CPU connected to the Internet.
● Thus, the execution of bytecode by the JVM is the easiest way to create truly portable programs.
● A Java program executed by the JVM also helps to make it secure.
● In general, when a program is compiled to an intermediate form and then interpreted by a virtual
machine, it runs slower than it would run if compiled to executable code. However, with Java, the
differential between the two is not so great.
● The HotSpot technology was introduced not long after Java’s initial release.
● HotSpot provides a Just-In-Time (JIT) compiler for bytecode. When a JIT compiler is part of the
JVM, selected portions of bytecode are compiled into executable code in real time, on a
piece-by-piece, demand basis.
● It is not practical to compile an entire Java program into executable code all at once, because Java
performs various run-time checks that can be done only at run time. Instead, a JIT compiler
compiles code as it is needed, during execution.

Architecture-Neutral
· A central issue for the Java designers was that of code longevity and portability. At the time of
Java’s creation, one of the main problems facing programmers was that no guarantee existed that if
you wrote a program today, it would run tomorrow—even on the same machine. Operating system
upgrades, processor upgrades, and changes in core system resources can all combine to make a
program malfunction. The Java designers made several hard decisions in the Java language and the
Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run anywhere,
any time, forever.” To a great extent, this goal was accomplished

5. Differentiate between break and continue with an example.


Break:
Break keyword is often used inside loops control structures and switch statements. It is used to terminate
loops and switch statements in java. When the break keyword is encountered within a loop, the loop is
immediately terminated and the program control goes to the next statement following the loop. When the
break keyword is used in a nested loop, only the inner loop will get terminated. Even it is used with if
statement to terminated when a certain condition is met.
The break keyword has special usage inside the switch statement. Every case in the switch statement is
followed by a break keyword, such that whenever the program control jumps to the next case, it wouldn’t
execute subsequent cases.
Syntax:
break keyword along with a semicolon
break;
Flow chart of Break statement
Case 1: Break keyword inside loop
public class GFG {

// Main driver code


public static void main(String[] args)
{
// For loop for iteration
for (int i = 3; i <= 50; i += 3) {
if (i == 39) {
// Using Break keyword to suspend
// loop when i become 39
break;
}

// Printing elements showcasing break usage


System.out.print(i + " ");
}
}
}
In the above code when the value of ‘i’ becomes 39, the break keyword plays its role and terminate the
for a loop. All values of ‘i’ before 39, are displayed in the result.

Case 2: Break inside switch


public class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring a variable for switch expression
int numb = 20;

// Switch expression
switch (numb) {

// Case statements
case 10:
System.out.println("TEN");

// Break keyword to suspend the switch case


// if given condition is fulfilled
break;
case 20:
System.out.println("TWENTY");
break;

case 30:
System.out.println("THIRTY");
break;

// Default case statement


default:
System.out.println("INFINITE");
}
}
}
In the above code, The break keyword is used at the bottom of every switch case to terminate each
statement sequence and prevent the mixing of switch-case statements.

Continue:
Continue statement is often used inside in programming languages inside loops
control structures. Inside the loop, when a continue statement is encountered
the control directly jumps to the beginning of the loop for the next iteration
instead of executing the statements of the current iteration. The continue
statement is used when we want to skip a particular condition and continue the
rest execution. Java continue statement is used for all type of loops
Syntax: continue keyword along with a semicolon
continue;
Flow Chart of Continue Statement
import java.util.*;
public class GFG {

// Main driver method


public static void main(String args[])
{
// For loop for iteration
for (int i = 0; i <= 15; i++) {

// Check condition for continue


if (i == 10 || i == 12) {

// Using continue statement to skip the


// execution of loop when i==10 or i==12
continue;
}
// Printing elements to show continue statement
System.out.print(i + " ");
}
}
}
Output :
0 1 2 3 4 5 6 7 8 9 11 13 14 15
In the above code When the value of ‘i’ becomes 10 or 12, the continue statement plays its role and skip
their execution but for other values of’ ‘i’ the loop will run smoothly.

6. Sita wants to develop a program to find the average marks of her friends. Which type of
variable do you prefer to store the total number of students and why?

A) I prefer to use final keyword to store the total number of students as the total number of
students is static and will not change and their marks to calculate Average marks . To store the
Names of the students I will use an array of type String and to store the marks of the students I
will use an array of type integer. I prefer to store the names of the students in a one dimensional
array and marks in a two dimensional array as to divide and store marks of each student
separately . As we know that a multidimensional array is defined as Array of Arrays it stores data
in the form of rows and in this program .

Final Attributes:
When a variable is declared with the final keyword, its value can’t be changed, essentially, a
constant. We must initialize a final variable at declaration itself. According to java naming rules,
the final variable name should be capital letters. When the user tries to modify the value of a final
variable it generates an error.

Ex: final int N=25;

Source Code:
import java.io.*;
import java.util.Scanner;

class Average{
final int N=25;
public static void main(String args[]){

int total=0;
sc.nextLine();
String name[]=new String[N];
int marks[][]=new int[N][5];
for(int i=0;i<marks.length;i++){

System.out.print("Name of student "+(i+1)+" : ");


name[i]=sc.nextLine();
System.out.println("Enter Marks :");
for(int j=0;j<marks[i].length;j++){

System.out.print("subject "+(j+1)+" : ");


marks[i][j]=sc.nextInt();
sc.nextLine();
}
}
for(int i=0;i<marks.length;i++){
System.out.print("Name : "+name[i]+" | ");
total=0;
for(int j=0;j<marks[i].length;j++){

total=total+marks[i][j];

}
System.out.println("Average : "+total/5);
}

}
}

Output:
Number of Students : 2
Name of student 1 : Ram
Enter Marks :
subject 1 : 89
subject 2 : 90
subject 3 : 88
subject 4 : 87
subject 5 : 85
Name of student 2 : Ravi
Enter Marks :
subject 1 : 87
subject 2 : 85
subject 3 : 89
subject 4 : 90
subject 5 : 91
Name : Ram | Average : 87
Name : Ravi | Average : 88

7. Sree wants to develop a java program to find her grade. Help sree by suggesting a W
programming construct and develop it.

Source Code :

import java.io.*;

import java.util.Scanner;

class Grade{

public static void main(String args[]){


Scanner sc=new Scanner(System.in);

float marks;

System.out.print("Enter Marks : ");

marks=sc.nextFloat();

if(marks>=85 && marks<100){

System.out.println("A Grade");

else if (marks>=70 && marks<=84) {

System.out.println("B Grade");

else if(marks>=55 && marks<=69){

System.out.println("C Grade");

else if(marks>=40 && marks<=54){

System.out.println("D Grade");

else{

System.out.println("Fali ");

Output :

Enter Marks : 80

B Grade

8. Differentiate between implicit and explicit type conversion with an example. [4]
When you assign value of one data type to another, the two types might not be compatible with each
other. If the data types are compatible, then Java will perform the conversion automatically known as
Automatic Type Conversion and if not then they need to be casted or converted explicitly. For example,
assigning an int value to a long variable.

Widening or Automatic Type Conversion

Widening conversion takes place when two data types are automatically converted. This happens when:

● The two data types are compatible.


● When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no automatic conversion
is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each
other.

Example:

Class Test{
public static void main(String[] args)
{
int i = 100;

//automatic type conversion


long l = i;

//automatic type conversion


float f = l;
System.out.println("Int value "+i);
System.out.println("Long value"+l);
System.out.println("Float value "+f);
}
}

Output:
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit Conversion

If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or
narrowing.

● This is useful for incompatible data types where automatic conversion cannot be done.
● Here, target-type specifies the desired type to convert the specified value to.

char and number are not compatible with each other. Let’s see when we try to convert one into other.

//Java program to illustrate incompatible data

// type for explicit type conversion

public class Test

public static void main(String[] argv)

char ch = 'c';

int num = 88

ch = num;

Error:

How to do Explicit Conversion?

Example:
//Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i);
}
}
Output:

Double value 100.04

Long value 100

Int value 100

While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).

Example:

Java program to illustrate Conversion of int and double to byte

class Test

public static void main(String args[])


{
byte b;
int i = 257;
double d = 323.142;
System.out.println("Conversion of int to byte.");
b = (byte) i;
System.out.println("i = " + i + " b = " + b);
System.out.println("\nConversion of double to byte.");

//d%256
b = (byte) d;
System.out.println("d = " + d + " b= " + b);
}

Output:

Conversion of int to byte.

i = 257 b = 1

Conversion of double to byte.

d = 323.142 b = 67

10. Create a java program to implement arithmetic operations on two integers.

A) Source Code:

import java.io.*;
import java.util.Scanner;

class Arithmatic{

public static void main(String args[]){

float a,b;

int ch=0;

Scanner sc=new Scanner(System.in);

System.out.println("1.Addition");

System.out.println("2.Substraction");

System.out.println("3.Multiplication");

System.out.println("4.Division");

System.out.println("5.exit");

while(ch!=5){

System.out.print("Enter choice : ");

ch=sc.nextInt();

if(ch==1){

System.out.print("First num : ");

a=sc.nextInt();

System.out.print("Second num : ");

b=sc.nextInt();

System.out.println("sum = "+(a+b));

if(ch==2){

System.out.print("First num : ");

a=sc.nextInt();

System.out.print("Second num : ");

b=sc.nextInt();

System.out.println("difference = "+(a-b));

}
if(ch==3){

System.out.print("First num : ");

a=sc.nextInt();

System.out.print("Second num : ");

b=sc.nextInt();

System.out.println("product = "+(a*b));

if(ch==4){

System.out.print("First num : ");

a=sc.nextInt();

System.out.print("Second num : ");

b=sc.nextInt();

System.out.println("coefficeint = "+(a/b));

if(ch==5){

break;

Output:

1.Addition

2.Substraction

3.Multiplication

4.Division

5.exit

Enter choice : 1

First num : 2
Second num : 2

sum = 4.0

Enter choice : 2

First num : 4

Second num : 2

difference = 2.0

Enter choice : 3

First num : 5

Second num : 4

product = 20.0

Enter choice : 4

First num : 8

Second num : 2

coefficeint = 4.0

Enter choice : 5

9. a) Draw a flowchart to find the largest number among three numbers[6]

b) Evaluate the following expressions considering the precedence of operators.[5]

i)x=10;

x+=(x++)+(++x)+x;

print x;

ii)int a=10,b=2,x=0;

x=a+b*a+10/2*a;

print x;
a)

b) 1. x=10;

x+=(x++)+(++x)+x;

print x;

TWO MARKS QUESTIONS:

1.State any four features of java.

Refer Qno:7 in ten marks.

2.What is byte code? Explain why java is called as true object oriented language.

Refer Qno:7 in ten marks.

3. List primitive data types along with their memory requirements in Java.

Category Datatype No.of bytes Min-max Default value example


occupied value

Integer type byte 1byte (-27)- 0 byte b=10;


(+27-1)

short 2bytes (-215)- 0 short s=23451;


(+215-1)
int 4bytes (-231)- 0 int i=2345666;
(+231-1)

long 8bytes (-263)- 0 long l=342156789;


(+263-1)

Floating type float 4bytes (3.4e-038)- 0.0f Float f=3.45f;


(3.4e+038)

double 8bytes (3.4e-308)- 0.0d double d=3.2134d;


(3.4e+308)

Textual type char 2bytes Null char ch=’x’;


0-
65535

boolean 1bit false boolean b=true;

Logical type -

4. What is string? List two string handling functions with their use.

· A string is a set of related characters accessed as a single entity.

· Strings are treated in java as objects of String class.

· String class is defined in java.lang package.

Methods in String class

1. int length()

Use: returns the length of current String object

Example:

String str = new String(“Have a nice day”);

System.out.println(str.length());

2. charAt(int where )

Use: returns the character at the specified index.

Example:

char ch;
ch = "abc".charAt(1);

3. void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

Use: extract more than one character at a time.

Example:

String s = "This is a demo of the getChars method.";

int start = 10;

int end = 14;

char buf[] = new char[end - start];

s.getChars(start, end, buf, 0);

System.out.println(buf);

4. String toString()

Use: returns string of current object String.

Example:

String str = new String(“Have a nice Day”);

System.out.println(str.toString());

5. byte[ ] getBytes( )

Use: Performs character-to-byte conversions.

6. char[ ] toCharArray( )

Use: convert all the characters in a String object into a character array.

7. boolean equals(Object str)

boolean equalsIgnoreCase(String str)

use: used to compare two string objects considering case in 1st one and discarding case in 2nd one.

example

String s1 = "Hello";

String s2 = "Hello";

String s3 = "Good-bye";

String s4 = "HELLO";

System.out.println(s1 + " equals " + s2 + " -> " +


s1.equals(s2));

System.out.println(s1 + " equals " + s3 + " -> " +

s1.equals(s3));

System.out.println(s1 + " equals " + s4 + " -> " +

s1.equals(s4));

System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +

s1.equalsIgnoreCase(s4));

5. What is the role of JVM?

Refer Qno:5 in ten marks

6. Explain the concept of automatic type promotion in expressions.

While evaluating expressions, the intermediate value may exceed the range of operands and hence the
expression value will be promoted. Some conditions for type promotion are:

1. Java automatically promotes each byte, short, or char operand to int when evaluating an
expression.

2. If one operand is a long, float or double the whole expression is promoted to long, float or double
respectively.

Example:
//Java program to illustrate Type promotion in
Expressions
class Test
{
public static void main(String args[])
{
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

// The Expression
double result = (f * b) + (i / c) - (d * s);

//Result after all the promotions are done


System.out.println("result = " + result);
}
}

Output:
Result = 626.7784146484375

7. What is encapsulation.

Refer Qno:4 in ten marks

8. Explain the term inheritance.

Refer Qno:4 in ten marks

9. Explain the term polymorphysm.

Refer Qno:4 in ten marks


10. Create a java program to swap two numbers.

public class SwapNumbers {

public static void main(String[] args) {

float first = 1.20f, second = 2.45f;

System.out.println("--Before swap--");

System.out.println("First number = " + first);

System.out.println("Second number = " + second);

// Value of first is assigned to temporary

float temporary = first;

// Value of second is assigned to first

first = second;
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}

BIT BANK

1.Who invented Java Programming?

a) Guido van Rossum

b) James Gosling

c) Dennis Ritchie

d) Bjarne Stroustrup

2. Which statement is true about Java?

a) Java is a sequence-dependent programming language


b) Java is a code dependent programming language

c) Java is a platform-dependent programming language

d) Java is a platform-independent programming language

3. Which component is used to compile, debug and execute the java programs?

a) JRE

b) JIT

c) JDK

d) JVM

4. Which one of the following is not a Java feature?

a) Object-oriented

b) Use of pointers

c) Portable

d) Dynamic and Extensible

5. Which of these cannot be used for a variable name in Java?

a) identifier & keyword

b) identifier

c) keyword

d) none of the mentioned

6. What is the extension of java code files?

a) .js

b) .txt

c) .class

d) .java
7. Which environment variable is used to set the java path?

a) MAVEN_Path

b) JavaPATH

c) JAVA

d) JAVA_HOME

8. Which of the following is not an OOPS concept in Java?

a) Polymorphism

b) Inheritance

c) Compilation

d) Encapsulation

9. What is Truncation in Java?

a) Floating-point value assigned to a Floating type

b) Floating-point value assigned to an integer type

c) Integer value assigned to floating type

d) Integer value assigned to floating type

10. What is the extension of compiled java classes?

a) .txt

b) .js

c) .class

d) .java

11. Number of primitive data types in Java are?

Ans;8

12. What is the size of float and double in java?


32 and 64
32 and 32
64 and 64
64 and 32
13. Select the valid statement.
char[] ch = new char(5)
char[] ch = new char[5]
char[] ch = new char()
char[] ch = new char[]

14 Automatic type conversion is possible in which of the possible cases?


Byte to int
Int to long
Long to int
Short to int

15 Select the valid statement to declare and initialize an array.


int[] A = {}
int[] A = {1, 2, 3}
int[] A = (1, 2, 3)
int[][] A = {1,2,3}

UNIT-2

TEN MARKS QUESTIONS:

1. Compare constructors with and without parameters considering an example.[2]


2. Differentiate between call by value and call by reference with an example.[4]
3. Explain how method overloading achieves static polymorphism.[3]
4. Rohan takes the instance variables and parameters of the method with the same name. Is it
possible? If possible, discuss the scope of the variables.[3]
5. Create a program to calculate the factorial for a given number using recursion.[6]
6. Discuss the scope and lifetime of instance variables and methods in nested and inner classes with
an example.[2]
7. Ravi does not want to share his mail id . Which type of programming construct will you prefer .
Explain.[5]
8. Define class and object and explain why class variables are called instance variables.[1]
9. Assess how different types of parameters can be passed to a method considering an example.[4]
10. Apply the concept of constructor overloading in calculating the area of a circle.[3]

TWO MARKS QUESTIONS:

1. What are the rules in writing a constructor.[1]


2. Describe the general structure of java class with an example.[2]
3. Illustrate the concept of inner class with an example[2]
4. Differentiate between constructor and a method.[4]
5. Differentiate static and dynamic polymorphism.[4]
6. Relate the strings in c with string class in java.[5]
7. Construct a class named Student with fields roll number, marks for 5 subjects and display the
average marks for five students[3]
8. Calculate the roots of quadratic equation using parameterized constructor.[3]
9. Create a Java program to calculate the volume of a box.[6]
10. Illustrate why class variables are called instance variables.[2]
TEN MARKS QUESTIONS:
1. Compare constructors with and without parameters considering an example.
● Constructors are the special kinds of methods whose purpose is to initialize the state of the
object. ∙ It has the same name as that of the class name.
● It does not have any return type specified [not even void].
● A constructor without any parameter is called as default constructor.
● If we do not explicitly provide any constructor to a class, then system provides the default
constructor which initializes the instance variables to their respective initial values based on
variable data type. ∙ If we provide a constructor and still do not initialize some of the
instance variables then those variables are initialized by the system to their respective initial
values based on variable data type ∙ In Java whenever keyword ‘new’ is used, a new object
is created, which result in invocation of the appropriate constructor for initializing the state
of the created object. Since object is initialized only once in its life time hence constructors
can be called for object creation only with the usage of keyword ‘new’.

Types of Constructors:
1. Default Constructors
2. Parameterized Constructors
3. Copy Constructors

1. Default Constructors:
These are invoked implicitly whenever an object is created.
Syntax :
Classname objectname = new classname( ) ;
Example:
class Point
{
int x,y;
Point()
{
x=10;
y=5;
}
void show()
{
System.out.println(“x=”+x);
System.out.println(“y=”+y);
}
}
class PointDemo
{
public static void main ( String args[ ] )
{
Point p = new Point();
p.show();
}
}
2. Parameterized Constructors:
These are explicitly called with parameters being passed while creating object.
Syntax :
Classname objectname = new classname ( parameters) ;
class Point
{
int x,y;
Point(int m,int n)
{
x=m;
y=n;
}
void show()
{
System.out.println(“x=”+x);
System.out.println(“y=”+y);
}
}
class PointDemo
{
public static void main ( String args[ ] )
{
Point p = new Point(2,3);
p.show();
}
}
Copy Constructor
∙ A copy constructor is a constructor that takes an existing object of the same class as its
argument. ∙ The copy constructor makes the new object an exact copy of the argument. For
Example
A Stock class copy constructor
public Stock(Stock object2)
{
symbol = object2.symbol;
sharePrice = object2.sharePrice;
}
// Create a Stock object.
Stock company1 = new Stock(“XYZ”, 9.62);
// Create another Stock object that is a copy of the company1 object.
Stock company2 = new Stock(company1);

Example for using this keyword:

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

The output from this program is shown here:


Volume is 3000.0
Volume is 162.0

2. Differentiate between call by value and call by reference with an example.[4]

There are two corresponding ways of how the arguments are passed to methods:
1) by value --a method receives a copy of the original value; parameters of simple
types
2) by reference --a method receives the memory address of the original value, not the
value itself; parameters of class types
CALL BY VALUE:
Passing arguments of simple types takes place by value:
class Test {
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}

With by-value argument-passing what occurs to the parameter that receives the argument
has no effect outside the method:

Example:
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: “);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}}
CALL BY REFERENCE
Objects are passed to the methods by reference: a parameter obtains the same address as the
corresponding argument:
Example:
class Test {
int a, b;
Test(int i, int j) {
a = i; b = j;
}
void meth(Test o) {
o.a *= 2; o.b /= 2;
}}
As the parameter hold the same address as the argument, changes to the object inside the method do
affect the object used by the argument:
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}

3. Explain how method overloading achieves static polymorphism.


Java allows you to define several methods in a class with the same name, as long as each method has
a set of parameters that is unique. This is called method overloading.

Java has to be able to uniquely associate the invocation of a method with its definition relying on
the number and types of arguments.
Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to implement polymorphism
Example:
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a); return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("ob.test(123.2): " + result);
}
}
● When an overloaded method is called, Java looks for a match between the arguments
used to call the method and the method’s parameters.
● This process is done at compile time hence it achieves static polymorphism.
When no exact match can be found, Java’s automatic type conversion can help overload
resolution.

4. Rohan takes the instance variables and parameters of the method with the same
name. Is it possible? If possible, discuss the scope of the variables.

It is possible to take the instance variables and parameters of the method with the same
name. But while accessing the instance variables we have to use this key word.

this keyword:

In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this”
in Java is a keyword that refers to the current object instance. It can be used to call current
class methods and fields and to differentiate between the local and instance variables. It
reduces name conflicts.

Example:
public class Person {

// Fields Declared
String name;
int age;

// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}
public void printDetails()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println();
}

// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);

first.printDetails();
second.printDetails();
}
}

Scope of variables:

● The instance variables have global scope such that it exists throughout the class. The
parameters have local scope so that it exists up to that method or constructor.
● In the above code the instance variables and parameters have same name (name and age).
● As the parameters have local scope inside the constructor the parameters hide the instance
variables.
● So inside the constructor to access the instance variables this key word should be used .
Syntax: this. variable name
● In the statement this.name = name
this.name refers instance variables and name refers to parameter

5. Create a program to calculate the factorial for a given number using recursion.
Recursion is a basic programming technique you can use in Java, in which a method calls itself
to solve some problem. A method that uses this technique is recursive. Many programming
problems can be solved only by recursion, and some problems that can be solved by other
techniques are better solved by recursion.

One of the classic problems for introducing recursion is calculating the factorial of an integer.
The factorial of any given integer — call it n so that you sound mathematical — is the product
of all the integers from 1 to n. Thus, the factorial of 5 is 120: 5 x 4 x 3 x 2 x 1.
The recursive way to look at the factorial problem is to realize that the factorial for any given
number n is equal to n times the factorial of n–1, provided that n is greater than 1. If n is 1, the
factorial of n is 1.
Example program factorial of a given numer n using recursion:

class FactorialExample{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,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

6. Discuss the scope and lifetime of instance variables and methods in nested and inner classes
with an example
It is possible to define a class within another class; such classes are known as nested classes. The
object of the inner class can access the members of the outer class.
While the outer class cannot access the members of the inner class through an object of the inner
class. Syntax:
class A
{
class B
{
}
//other attributes and methods
}

There are two types of nested classes: static and non-static.


● A static nested class is one that has the static modifier applied.
● Because it is static, it must access the members of its enclosing class through
an object. That is, it cannot refer to members of its enclosing class directly.
Syntax:
class A
{
class B
{
}
//other attributes and methods
}
The most important type of nested class is the inner class.
● An inner class is a non-static nested class.
● It has access to all of the variables and methods of its outer class and may refer to them directly
in the same way that other non-static members of the outer class do.
The following program illustrates how to define and use an inner class.

The class named Outer has one instance variable named outer_x, one instance method named test( ),
and defines one inner class called Inner.

// Demonstrate an inner class.


class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

Output from this application is shown here:


display: outer_x = 100

7. Ravi does not want to share his mail id . Which type of programming construct will you
prefer . Explain.

I will declare mail-id variable as private member of the class.

Private:
The private access modifier is specified using the keyword private. The methods or data members
declared as private are accessible only within the class in which they are declared.
● Any other class of the same package will not be able to access these members.
● Top-level classes or interfaces can not be declared as private because
○ private means “only visible within the enclosing class”.
○ protected means “only visible within the enclosing class and any
subclasses”

import java.util.*;
class Printing {
public static void main(String[] args) {
Student ob=new Student();
Scanner sc=new Scanner(System.in);
System.out.println("Enter name");
ob.name=sc.nextLine();
System.out.println("Enter roll number");
ob.rollno=sc.nextLine();
ob.show();
}
}
class Student{
String name;
String rollno;
private String mail;
void show(){
System.out.println("Enter Mail id");
Scanner sc=new Scanner(System.in);
mail=sc.nextLine();
System.out.println("Name:"+name);
System.out.println("Roll no:"+rollno);
System.out.println("Mail id:"+mail);

}
}
Output:

Enter name
ABC
Enter roll number
123
Enter Mail id
[email protected]
Name:ABC
Roll no:123
Mail id:[email protected]
In the above code mail variable is declared as private so that it can be accessed in the class Printing only.

8. Define class and object and explain why class variables are called instance variables.
A class is a template for an object, and an object is an instance of a class. Because an object is an
instance of a class
The General Form of a Class
A class is declared by use of the class keyword.
class classname {
type instance-variable1;
type instance-variable2;
type instance-variableN;
type methodname1(parameter-list) { // body of method }
type methodname2(parameter-list) { // body of method }
type methodnameN(parameter-list) { // body of method }
}
● The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class
are called members of the class.
● Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables
● Hence the variables of class are called instance variables.
Example:
class Box
{
double width;
double height;
double depth;
}
● A class defines a new type of data. In this case, the new data type is called Box. You will
use this name to declare objects of type Box.
● To create an object
Box mybox = new Box();
mybox will be an instance of Box
● Each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class.
● Thus, every Box object will contain its own copies of the instance variables width, height,
and depth.
● To access these variables, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.
● For example, to assign the width variable of mybox the value 100, use the following
statement: mybox.width = 100;
● This statement tells the compiler to assign the copy of width that is contained within the
mybox object the value of 100.
class Box {
double width;
double height;
double depth;
} // This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol; // assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15; // compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

9. Assess how different types of parameters can be passed to a method considering an


example.
● This is the general form of a method:
type name(parameter-list)
{ // body of method
}
● Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that you create.
● If the method does not return a value, its return type must be void.
● The name of the method is specified by name. This can be any legal identifier other than
those already used by other items within the current scope.
● The parameter-list is a sequence of type and identifier pairs separated by commas.
● Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called.
● If the method has no parameters, then the parameter list will be empty.
● Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:
return value; Here, value is the value returned.
10. Apply the concept of constructor overloading in calculating the area of a circle.
A) Source Code:

import java.io.*;
import java.util.Scanner;
class Demo1{
public float radius;
Demo1(){}
Demo1(float r){

this.radius=r;

void create(){

Scanner sc=new Scanner(System.in);


float rad;
System.out.print("Radius = ");
rad=sc.nextFloat();
Demo1 obj2=new Demo1(rad);
obj2.calculate();
}

void calculate(){
Double area=3.1415*radius*radius;
System.out.println("Area = "+area);

public static void main(String args[]){

Scanner sc=new Scanner(System.in);


int ch=1;
System.out.println("1.continue ");
System.out.println("2.Exit ");
Demo1 obj1=new Demo1();
while(ch==1){

obj1.create();
System.out.print("Choice = ");
ch=sc.nextInt();
}
}
}

OUTPUT:
1.continue
2.Exit
Radius = 2
Area = 12.566
Choice = 1
Radius = 3
Area = 28.2735
Choice = 2

TWO MARKS QUESTIONS:

1. What are the rules in writing a constructor.


● Constructors are the special kinds of methods whose purpose is to initialize the state of the
object. ∙ It has the same name as that of the class name.
● It does not have any return type specified [not even void].
● A constructor without any parameter is called as default constructor.
● These are invoked implicitly whenever an object is created.
Syntax :
Classname objectname = new classname( ) ;
Example:
class Point
{
int x,y;
Point()
{
x=10;
y=5;
}
void show()
{
System.out.println(“x=”+x);
System.out.println(“y=”+y);
}
}
class PointDemo
{
public static void main ( String args[ ] )
{
Point p = new Point();
p.show();
}
}

2. Describe the general structure of java class with an example.


The exact form and nature of class is done by specifying the data that it contains and the code that
operates on that data. ∙ A class is declared by use of the class keyword.

GENERAL FORM OF CLASS:

class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}

● The data, or variables, defined within a class are called instance variables.
● The code is contained within methods.
● Collectively, the methods and variables defined within a class are called members of the class. ∙
Variables defined within a class are called instance variables because each instance of the
class(that is, each object of the class) contains its own copy of these variables.
● Thus, the data for one object is separate and unique from the data for another.

Example Program: Class


A class with three variable members:
class Box
{
double width;
double height;
double depth;
}

3. Illustrate the concept of inner class with an example.


● An inner class is a non-static nested class.
● It has access to all of the variables and methods of its outer class and may refer to them
directly in the same way that other non-static members of the outer class do.

// Demonstrate an inner class.


class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

Output from this application is shown here:


display: outer_x = 100

4. Differentiate between constructor and a method.

Constructors Methods

Constructor is used to create and initialize Method is used to execute certain


an Object . statements.
A constructor is invoked implicitly by the A method is to be invoked during
System. program code.

A constructor is invoked when new A method is invoked when it is called.


keyword is used to create an object.

A constructor can not have any return A method can have a return type.
type.

A constructor initializes an object which is A method can be invoked only on


not existent. existing object.
A constructor must have same name as A method name can not be same as
that of the class. class name.
A constructor cannot be inherited by a A method is inherited by a subclass.
subclass.

5. Differentiate static and dynamic polymorphism.

Compile Time Polymorphism: Whenever an object is bound with its functionality at the
compile time, this is known as the compile-time polymorphism. At compile-time, java knows
which method to call by checking the method signatures. So this is called compile-time
polymorphism or static or early binding. Compile-time polymorphism is achieved through
method overloading. Method Overloading says you can have more than one function with the
same name in one class having a different prototype. Function overloading is one of the ways to
achieve polymorphism but it depends on technology and which type of polymorphism we adopt.
In java, we achieve function overloading at compile time.

Run-Time Polymorphism: Whenever an object is bound with the functionality at run time, this
is known as runtime polymorphism. The runtime polymorphism can be achieved by method
overriding. Java virtual machine determines the proper method to call at the runtime, not at the
compile time. It is also called dynamic or late binding. Method overriding says the child class has
the same method as declared in the parent class. It means if the child class provides the specific
implementation of the method that has been provided by one of its parent classes then it is known
as method overriding.

6. Relate the strings in c with string class in java.


● In C strings are considered as an array of characters and it is a datatype
● In java strings are considered as objects. String is a predefined class in java which consists of
several methods that perform operations on strings.

7. Construct a class named Student with fields roll number, marks for 5 subjects and display
the average marks for five students.
class Student{
int roll[5]={1,2,3,4,5};
float s1[5]={20.0,21.5,23,23,23};
float s2[5]={20.0,21.5,23,23,23};
float s3[5]={20.0,21.5,23,23,23};
float s4[5]={20.0,21.5,23,23,23};
float s5[5]={20.0,21.5,23,23,23};

public void display(){


System.out.println(“Student1 rollnumber:”+roll[0]);
System.out.println(“His average marks:”+((s1[0]+s1[1]+s1[2]+s1[3]+s1[4])/5));
System.out.println(“Student2 rollnumber:”+roll[1]);
System.out.println(“His average marks:”+((s2[0]+s2[1]+s2[2]+s2[3]+s2[4])/5));
System.out.println(“Student1 rollnumber:”+roll[2]);
System.out.println(“His average marks:”+((s3[0]+s3[1]+s3[2]+s3[3]+s3[4])/5));
System.out.println(“Student1 rollnumber:”+roll[3]);
System.out.println(“His average marks:”+((s4[0]+s4[1]+s4[2]+s4[3]+s4[4])/5));
System.out.println(“Student1 rollnumber:”+roll[4]);
System.out.println(“His average marks:”+((s5[0]+s5[1]+s5[2]+s5[3]+s5[4])/5));

}
public static void main(String args[]){
display();

8. Calculate the roots of quadratic equation using parameterized constructor.


9. Create a Java program to calculate the volume of a box.
10. Illustrate why class variables are called instance variables.

BIT BANK

1. Which feature of OOPS derives the class from another class?


a. Inheritance
b. Data hiding
c. Encapsulation
d. Polymorphism

2. A single program of OOPS contains _______ classes?

a. Only 1
b. Only 999
c. Only 100
d.
e. Any number3. Which member function is assumed to call first when there is a case of using
function overloading or abstract class?
a. Global function
b. Local function
c. Function with lowest priority
d. Function with the highest priority

4. What is the extra feature in classes which was not in the structures?

a. Member functions
b. Data members
c. Public access specifier
d. Static Data allowed

5. Which of the following feature is also known as run-time binding or late binding?

a. Dynamic typing
b. Dynamic loading
c. Dynamic binding
d. Data hiding

6. Which among the following is not a member of the class?

a. Virtual function
b. const function
c. Static function
d. Friend function

7. What is the size of a class?

a. Sum of the size of all inherited variables along with the variables of the same class
b. The size of the class is the largest size of the variable of the same class
c. Classes in the programming languages do not have any size
d. Sum of the size of all the variables within a class.

8. Which of the following statement of a program is not right?

a. class teacher{ }; teacher s[5];


b. class teacher{ }s;
c. class teacher{ }; teacher s;
d. class teacher{ }s[];

9. Which of the following syntax is incorrect for the class definition?

a. student class{ };
b. class student{ student(int a){} };
c. class teacher{ public: teacher(int a){ } };
d. None of the mentioned

10. The object cannot be________?

a. passed by copy
b. passed as function
c. passed by value
d. passed by reference

11. Which of the following feature interacts one object with another object?

a. Message reading
b. Message passing
c. Data transfer
d. Data binding

12. When does method overloading is determined?

a) At run time

b) At compile time

c) At coding time

d) At execution time

13. When does method overriding is determined?

a) At run time

b) At compile time

c) At coding time

d) At execution time

14. When Overloading does not occur?

a) More than one method with same name but different method signature and different number or type of
parameters

b) More than one method with same name, same signature but different number of signature

c) More than one method with same name, same signature, same number of parameters but different type

d) More than one method with same name, same number of parameters and type but different
signature

15. What is it called if an object has its own lifecycle and there is no owner?

a) Aggregation

b) Composition
c) Encapsulation

d) Association

UNIT-3

QNo Question BTL

1. Justify the following statement through an example. “Multiple inheritance is not 4


supported through class in java, but it is possible by an interface.”

2. Define an abstract class. Create an abstract class 'Marks' with an abstract method 6
'getPercentage'. It is inherited by two other classes 'A' and 'B' each having a method
with the same name which returns the percentage of the students. The constructor of
student A takes the marks in three subjects as its parameters and the marks in four
subjects as its parameters for student B. Create an object for each of the two classes
and print the percentage of marks for both the students.

3. Compare method overriding and method overloading by illustrating an example. 4

4. List the different types of inheritance and explain. 1

5. Explain dynamic method dispatch and evaluate how it achieves run time 2
polymorphism.

6. Ravi creates a class which has a calculate() method to find out the area of a square. 3
Ram extends Ravi’s class and writes a method named calculate() to find out the
perimeter of a square. Sita creates an object for the subclass created by Ravi and
wants to find out both the area and perimeter of the square. Help sita how to achieve
her goal.

7. Create a java program to add two matrices. 2


8. Explain about how to inhibit method overriding and inheritance. 3

9. Define interfaces and illustrate an example demonstrating the concept. 3

10. Sita wants to develop a program to find the bill that should be paid by the customer. 3
The number of items purchased is passed to the constructor. Help sita to develop
using the constructor.

1. Differentiate between this and super keyword. 4

2. Differentiate between interface and a class. 4

3. Differentiate between method overloading and method overriding. 4

4. Is it possible to override a constructor. 3

5. Assess the use of the final keyword with inheritance. 5

6. Create a java program to demonstrate the concept of constructor overloading. 6

7. Define about multi level inheritance. 2

8. Can override a constructor possible. 3

9. Define abstract class. 1

10. Define runtime polymorphism. 3

1. Justify the following statement through an example. “Multiple inheritance is not supported
through class in java, but it is possible by an interface.”

● Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another.
● The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass
● extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

● Java supports the following four types of inheritance:


● Single Inheritance
● Multi-level Inheritance
● Hierarchical Inheritance
● Hybrid Inheritance

Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.

In the above figure, Employee is a parent class and Executive is a child class. The Executive class
inherits all the properties of the Employee class.

Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived from another class is
called multi-level inheritance. In simple words, we can say that a class that has more than one parent
class is called multi-level inheritance. Note that the classes must be at different levels. Hence, there exists
a single base class and single derived class but multiple intermediate base classes.
In the above figure, the class Marks inherits the members or methods of the class Students. The class
Sports inherits the members of the class Marks. Therefore, the Student class is the parent class of the
class Marks and the class Marks is the parent of the class Sports. Hence, the class Sports implicitly
inherits the properties of the Student along with the class Marks.

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.

In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named Student.
Hybrid Inheritance

Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types of
inheritance.

Multiple Inheritance (not supported)

Java does not support multiple inheritances due to ambiguity. For example, consider the following Java
program.

class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}

The above code gives error because the compiler cannot decide which message() method is to be
invoked. Due to this reason, Java does not support multiple inheritances at the class level but can be
achieved through an interface.

Interface

● An interface contains variables and methods like a class but the methods in an interface
are abstract by default unlike a class and variables should be final.
● Multiple inheritance by interface occurs if a class implements multiple interfaces or also
if an interface itself extends multiple interfaces.

interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}

Output
Animal is eating
Animal is travelling
● The interface AnimalEat and AnimalTravel have one abstract method each i.e. eat() and travel().
The class Animal implements both the interfaces AnimalEat and AnimalTravel.

2. Define an abstract class. Create an abstract class 'Marks' with an abstract method
'getPercentage'. It is inherited by two other classes 'A' and 'B' each having a method with
the same name which returns the percentage of the students. The constructor of student A
takes the marks in three subjects as its parameters and the marks in four subjects as its
parameters for student B. Create an object for each of the two classes and print the
percentage of marks for both the students.

A) Source Code :

import java.io.*;
import java.util.Scanner;

abstract class Marks{

abstract float getPercentage();


}

class A extends Marks{

float sub1,sub2,sub3;

A(float sub1,float sub2,float sub3){


this.sub1=sub1;
this.sub2=sub2;
this.sub3=sub3;
}
float getPercentage(){

return ((sub1+sub2+sub3)/300)*100;

}
}

class B extends Marks{

float sub1,sub2,sub3,sub4;
B(float sub1,float sub2,float sub3,float sub4){

this.sub1=sub1;
this.sub2=sub2;
this.sub3=sub3;
this.sub4=sub4;
}
float getPercentage(){

return ((sub1+sub2+sub3+sub4)/400)*100;

}
}
class Abst{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
float m1,m2,m3,m4;
System.out.println("enter marks of student A : ");
System.out.print("subject1 : ");
m1=sc.nextFloat();
System.out.print("subject2 : ");
m2=sc.nextFloat();
System.out.print("subject3 : ");
m3=sc.nextFloat();
A obj=new A(m1,m2,m3);
System.out.println("Percentage of A = "+obj.getPercentage());
System.out.println("enter marks of student B : ");
System.out.print("subject1 : ");
m1=sc.nextFloat();
System.out.print("subject2 : ");
m2=sc.nextFloat();
System.out.print("subject3 : ");
m3=sc.nextFloat();
System.out.print("subject4 : ");
m4=sc.nextFloat();
B obj1=new B(m1,m2,m3,m4);
System.out.println("Percentage of B = "+obj1.getPercentage());

}
}

Output:

enter marks of student A :


subject1 : 85
subject2 : 70
subject3 : 82
Percentage of A = 79.0
enter marks of student B :
subject1 : 82
subject2 : 44
subject3 : 66
subject4 : 89
Percentage of B = 70.25

3. Compare method overriding and method overloading by illustrating an example.

Method Overloading Method Overriding

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


polymorphism. polymorphism.

It is used to grant the specific


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

It is performed in two classes with


It occurs within the class.
inheritance relationships.

Method overloading may or may not Method overriding always needs


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

In method overloading, the return type


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

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

It gives better performance. The reason


behind this is that the binding of
Poor performance
overridden methods is being done at
runtime.

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

Argument list should be different while Argument list should be same in method
doing method overloading. overriding.

Method Overloading:

● Method Overloading is a Compile time polymorphism.


● In method overloading, more than one method shares the same method name with a different
signature in the class.
● we can not achieve the method overloading by changing only the return type of the method.
Example
import java.io.*;

class MethodOverloadingEx {

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


System.out.println(add(4, 6, 7));
}
}

Output
add() with 2 parameters
10
add() with 3 parameters
17

Method Overriding:

● Method Overriding is a Run time polymorphism


● In method overriding, the derived class provides the specific implementation of the method that is
already provided by the base class or parent class.
● In method overriding, the return type must be the same or co-variant (return type may vary in the
same direction as the derived class).

Example:

import java.io.*;

class Animal {

void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}

class Dog extends Animal {


void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}

class MethodOverridingEx {

public static void main(String args[])


{
Dog d1 = new Dog();
Animal a1 = new Animal();

d1.eat();
a1.eat();

Animal animal = new Dog();


// eat() method of animal class is overridden by
// base class eat()
animal.eat();
}
}
Output
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.

4. List the different types of inheritance and explain.

● Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another.
● The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass
● extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

● Java supports the following four types of inheritance:


● Single Inheritance
● Multi-level Inheritance
● Hierarchical Inheritance
● Hybrid Inheritance

Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.

In the above figure, Employee is a parent class and Executive is a child class. The Executive class
inherits all the properties of the Employee class.

class Employee

float salary=34534*12;

public class Executive extends Employee

float bonus=3000*6;

public static void main(String args[])

{
Executive obj=new Executive();

System.out.println("Total salary credited: "+obj.salary);

System.out.println("Bonus of six months: "+obj.bonus);

Output:

Total salary credited: 414408.0

Bonus of six months: 18000.0

Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived from another class is
called multi-level inheritance. In simple words, we can say that a class that has more than one parent
class is called multi-level inheritance. Note that the classes must be at different levels. Hence, there exists
a single base class and single derived class but multiple intermediate base classes.

In the above figure, the class Marks inherits the members or methods of the class Students. The class
Sports inherits the members of the class Marks. Therefore, the Student class is the parent class of the
class Marks and the class Marks is the parent of the class Sports. Hence, the class Sports implicitly
inherits the properties of the Student along with the class Marks.

class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}

Output:

registration number= 0987


marks= 78.0
score= 68.7

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.
In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named Student.

class Student

public void methodStudent()

System.out.println("The method of the class Student invoked.");

class Science extends Student

public void methodScience()

System.out.println("The method of the class Science invoked.");

class Commerce extends Student

public void methodCommerce()

{
System.out.println("The method of the class Commerce invoked.");

class Arts extends Student

public void methodArts()

System.out.println("The method of the class Arts invoked.");

public class HierarchicalInheritanceExample

public static void main(String args[])

Science sci = new Science();

Commerce comm = new Commerce();

Arts art = new Arts();

//all the sub classes can access the method of super class

sci.methodStudent();

comm.methodStudent();

art.methodStudent();

Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.

Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types of
inheritance.

class GrandFather

public void show()

System.out.println("I am grandfather.");

//inherits GrandFather properties

class Father extends GrandFather

public void show()

System.out.println("I am father.");

}
//inherits Father properties

class Son extends Father

public void show()

System.out.println("I am son.");

//inherits Father properties

public class Daughter extends Father

public void show()

System.out.println("I am a daughter.");

public static void main(String args[])

Daughter obj = new Daughter();

obj.show();

Output:
I am daughter.

5. Explain dynamic method dispatch and evaluate how it achieves run time polymorphism.
● Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved
at run time, rather than compile time.
● If a super class contains a method that is overridden by a subclass, then when different types of
objects are referred to through super class reference variable, different versions of the method are
executed at runtime.
● Hence it achieves runtime polymorphism.
// Example: Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method

6. Ravi creates a class which has a calculate() method to find out the area of a square. Ram
extends Ravi’s class and writes a method named calculate() to find out the perimeter of a
square. Sita creates an object for the subclass created by Ravi and wants to find out both
the area and perimeter of the square. Help sita how to achieve her goal.
A) Source Code:

import java.io.*;
import java.util.Scanner;

class Ravi{
void calculate(float s){

System.out.println("Area Of Square = "+(s*s));


}
}

class Ram extends Ravi{

void calculate(float s){

super.calculate(s);
System.out.println("Perimeter Of Square = "+(4*s));

}
}

class Sita{

public static void main(String args[]){

Scanner sc=new Scanner(System.in);


System.out.print("Enter SWide of the Square : ");
float s;
s=sc.nextFloat();
Ram obj=new Ram();
obj.calculate(s);

}
OutPut:

Enter SWide of the Square : 2


Area Of Square = 4.0
Perimeter Of Square = 8.0

7. Create a java program to add two matrices.


import java.io.*;

class GFG {

// Function to print Matrix


static void printMatrix(int M[][],int rowSize,int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");

System.out.println();
}
}

// Function to add the two matrices


// and store in matrix C
static int[][] add(int A[][], int B[][],int size)
{
int i, j;
int C[][] = new int[size][size];

for (i = 0; i < size; i++)


for (j = 0; j < size; j++)
C[i][j] = A[i][j] + B[i][j];

return C;
}

// Driver code
public static void main(String[] args)
{
int size = 4;

int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix A:");
printMatrix(A, size, size);

int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix B:");
printMatrix(B, size, size);

// Add the two matrices


int C[][] = add(A, B, size);

// Print the result


System.out.println("\nResultant Matrix:");
printMatrix(C, size, size);
}
}

8. Explain about how to inhibit method overriding and inheritance.

final keyword in used to inhibit method overriding and inheritance


● If a class is declared as final it cannot be inherited
● If a method is declared as final method cannot be overridden.
Example:

final class A{

//code

//class B extends A{ // shows error

//code

The above statement class B extends A shows error because class A is declared as final so that it
cannot be inherited.

class A{
int a=10;
final void display(){

System.out.println(a);

class B extends A{
int b=10;
void display(){

System.out.println(b);

class Sample{
public static void main(String args[]){
B ob= new B();
ob.display();
}
}

The above statement void display() in class B shows error as it cannot be overridden since
declared final in class A.

9. Define interfaces and illustrate an example demonstrating the concept.


● An interface is a construct which contains the collection of purely undefined methods or
an interface is a collection of purely abstract methods.
● Interfaces are basically used to develop user defined data types.
● With respect to interfaces we can achieve the concept of multiple inheritances.
● An interface is defined much like a class.

Syntax of an interface:

access interface name

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;}

Creating an interface

Example:

public interface MusicPlayer

// Cannot have method implementations:

void on();

void off();

void play();

void stop();

interface VideoPlayer{

void on();

void off();

void play();

void stop();

void changeContrast(int x);

void changeBrightness(int x);


}

● Whatever the variables we write in the interface, they are by default belongs to:

public static final xxx data members

● All variables must be initialized (otherwise it will be compilation error)

Implementing an interface

● Once an interface is created one or more classes can implement the interface.
● Whenever a class implements the interface, the class should over ride all the methods of
interface.
● The methods that implement an interface must be declared public.

Syntax for reusing the features of interface(s) to class:

class classname implements interface

//class body

● In the above syntax class name represents name of the class which is inheriting the
features from interface.
● ‘implements’ is a keyword which is used to inherit the features of interface to a derived
class.

Example:

class MP3Player implements MusicPlayer

public void on()

System.out.println(“the MP3 Player is ON”);

public void off()

System.out.println(“the MP3 Player is OFF”);

public void play(){


System.out.println(“the MP3 Player is playing”);

public void stop(){

System.out.println(“the MP3 Player is off”);

Example for implementing multiple interfaces:

class iPod implements MusicPlayer, VideoPlayer

public void on(){

System.out.println(“the MP3 Player is ON”);

public void off(){

System.out.println(“the MP3 Player is OFF”);

public void play(){

System.out.println(“the MP3 Player is playing”);

public void stop(){

System.out.println(“the MP3 Player is off”);

public void changeContrast(int x){

System.out.println(“Constrast Changed by” + x);

public void changeBrightness(int x){

System.out.println(“Brightnesss Changed by” + x);

}
}

● We can create an interface reference variable. It can refer to any object that implements
the interface.

Extending interfaces

Syntax inheriting ‘n’ number of interfaces to another interface:

interface <interface 0 name> extends <interface 1>,<interface 2>.........<interface n>

variable declaration cum initialization;

method declaration;

For example:

interface I1

int a=10;

void f1 ();

};

interface I2 extends I1

int b=20;

void f2 ();

● If one interface is taking the features of another interface then that inheritance is known as

Interface inheritance

Syntax-3:

class <derived class name> extends <base class name>

implements <interface 1>,<interface 2>.........<interface n>

variable declaration;
method definition or declaration;

● Whenever we use both extends and implements keywords as a part of JAVA program we
must always write extends keyword first and latter we must use implements keyword.

10. Sita wants to develop a program to find the bill that should be paid by the customer. The
number of items purchased is passed to the constructor. Help sita to develop using the
constructor.
A) Source Code:

import java.io.*;
import java.util.Scanner;

class Calculate{
int n;
Calculate(int n){

this.n=n;
}
void cal(){
float q,c;
float total=0;
int i=0;
Scanner sc1=new Scanner(System.in);
while(i<n){
System.out.print("enter cost of "+(i+1)+" item : ");
c=sc1.nextFloat();
System.out.print("enter quantity of "+(i+1)+" item : ");
q=sc1.nextFloat();
total=total+(c*q);
i++;
}
System.out.println("Total Bill = "+total);
}
}

class Bill1{
public static void main(String args[]){
int n;
Scanner sc=new Scanner(System.in);
System.out.print("Number of Items : ");
n=sc.nextInt();
Calculate obj=new Calculate(n);
obj.cal();

}
}
Output :
Number of Items : 2
enter cost of 1 item : 20
enter quantity of 1 item : 2
enter cost of 2 item : 40
enter quantity of 2 item : 2
Total Bill = 120.0

Two marks Questions

1. Differentiate between this and super keyword.

Sr. Key this super


No.

Represent this keyword mainly represents the On other hand super keyword represents
1 and current instance of a class. the current instance of a parent class.
Reference

Interaction this keyword used to call default super keyword used to call default
2 with class constructor of the same class. constructor of the parent class.
constructor

Method this keyword used to access methods of One can access the method of parent
3 accessibility the current class as it has reference of class with the help of super keyword.
current class.

Static this keyword can be referred from static On other hand super keyword can't be
context context i.e can be invoked from static referred from static context i.e can't be
instance. For instance we can write invoked from static instance. For
4
System.out.println(this.x) which will instance we cannot write
print value of x without any System.out.println(super.x) this will
compilation or runtime error. leads to compile ti

2. Differentiate between interface and a class.

Class Interface

A class can be instantiated An interface can never be instantiated


The class keyword is used to declare it The interface keyword is used

The members of a class can be declared as private, The members of an interface are always declared as
public or protected public

Contains the concrete methods i.e methods with Contains abstract method i.e methods without the
body body

The extends keyword is used to inherit a class The implements keyword is used to use an interface

Can contain final and static methods Cannot contain final or static methods

A Java class can have constructors An interface cannot have constructors

A class can extend only one class but can implement An interface can extend any number of interfaces but
any number of interfaces cannot implement any interface

3. Differentiate between method overloading and method overriding.

Method Overloading Method Overriding

It is used to increase the readability of the program Provides a specific implementation of the method
already in the parent class

It is performed within the same class It involves multiple classes

Parameters must be different in case of overloading Parameters must be same in case of overriding

Is an example of compile-time polymorphism It is an example of runtime polymorphism

Return type can be different but you must change the Return type must be same in overriding
parameters as well.

Static methods can be overloaded Overriding does not involve static methods

4. Is it possible to override a constructor.


● Method Overriding means superclass and subclass methods having the same name and
same signature.
● Constructor overriding in the sense that they should have the same name and signature.
● Though we can provide the same signature we cannot provide the same name as the
constructor name is the same as the class name.
● Hence it is not possible to override a constructor
● But constructor overloading is possible

5. Assess the use of the final keyword with inheritance.

Using final to Prevent Inheritance


When a class is declared as final then it cannot be subclassed i.e. no other class can extend it.
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
● Declaring a class as final implicitly declared all of its methods as final, too.
● It is illegal to declare a class as both abstract and final since an abstract class is incomplete by
itself and relies upon its subclasses to provide complete implementations. For more on abstract
classes, refer abstract classes in java

Using final to Prevent Overriding


When a method is declared as final then it cannot be overridden by subclasses.
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}

class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}

6. Create a java program to demonstrate the concept of constructor overloading.


public class Tester {

private String message;

public Tester(){
message = "Hello World!";
}
public Tester(String message){
this.message = message;
}

public String getMessage(){


return message ;
}

public void setMessage(String message){


this.message = message;
}

public static void main(String[] args) {


Tester tester = new Tester();
System.out.println(tester.getMessage());

Tester tester1 = new Tester("Welcome");


System.out.println(tester1.getMessage());
}
}

Output
Hello World!
Welcome

7. Define about multi level inheritance.


In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived
class also acts as the base class for other classes.. As seen in the example given below, BabyDog
class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.
8. Can override a constructor possible.
No, you cannot override a constructor in Java or most other programming languages:

● Constructors are not inherited: Subclasses do not inherit constructors.


● Constructors do not have a return type: Constructors do not have a return type, unlike methods.
● Constructor names are based on class names: The name of a constructor is based on the class
name, so constructors of a child class cannot keep the same method signature as the parent class.

However, you can overload a constructor, which means having multiple constructors in a class that differ
in the number and/or type of their parameters.

9. Define abstract class.

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

● An abstract class must be declared with an abstract keyword.

● It can have abstract and non-abstract methods.

● It cannot be instantiated.

● It can have constructors and static methods also.

● It can have final methods which will force the subclass not to change the body of the method.

A method which is declared as abstract and does not have implementation is known as an abstract
method.

Example of abstract method

abstract void printStatus();//no method body and abstract


10. Define runtime polymorphism.

● Polymorphism in Java is a concept by which we can perform a single action in different ways.
● Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms
● There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism.
● We can perform polymorphism in java by method overloading and method overriding.

Runtime Polymorphism in Java

● Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at run time.
● In this process, an overridden method is called through the reference variable of a superclass.
● The determination of the method to be called is based on the object being referred to by the
reference variable.esolved at runtime rather than compile-time.

BIT BANK

1. Which of these keywords is used to define interfaces in Java?


a) interface
b) Interface
c) intf
d) Intf

2. Which of these can be used to fully abstract a class from its implementation?
a) Objects
b) Packages
c) Interfaces
d) None of the Mentioned

3. Which of these access specifiers can be used for an interface?


a) Public
b) Protected
c) private
d) All of the mentioned
4. Which of these keywords is used by a class to use an interface defined previously?
a) import
b) Import
c) implements
d) Implements

5. Which of the following is the correct way of implementing an interface salary by class manager?
a) class manager extends salary {}
b) class manager implements salary {}
c) class manager imports salary {}
d) none of the mentioned

6. Which of this keyword must be used to inherit a class?


a) super
b) this
c) extent
d) extends

7. A class member declared protected becomes a member of subclass of which type?


a) public member
b) private member
c) protected member
d) static member

8. Which of these is correct way of inheriting class A by class B?


a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}

9. Which among the following is the language which supports classes but not polymorphism?
a) SmallTalk
b) Java
c) C++
d) Ada
10. If same message is passed to objects of several different classes and all of those can respond in a
different way, what is this feature called?
a) Inheritance
b) Overloading
c) Polymorphism
d) Overriding

11. Polymorphism is possible in C language.


a) True
b) False

12. Which among the following is not true for polymorphism?


a) It is feature of OOP
b) Ease in readability of program
c) Helps in redefining the same functionality
d) Increases overhead of function definition always

13. Which of this keyword can be used in a subclass to call the constructor of superclass?
a) super
b) this
c) extent
d) extends

14. What is the process of defining a method in a subclass having same name & type signature as a
method in its superclass?
a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned

15. Which of these keywords can be used to prevent Method overriding?


a) static
b) constant
c) protected
d) final

UNIT-4

QNo Question BTL

1. Rama wants to create an user defined exception to check the voter eligibility. Help 6
rama in it.

2. Explain what happens when an exception is thrown by the main method. 2

3. Differentiate between checked and unchecked exceptions in java. 3

4. a) Can we have an empty catch block? Justify. 4


b) Can we have multiple catch blocks? Justify.

5. Evaluate the scope of a variable or a method if it is declared as private, public and 5


protected.

6. Discuss about wrapper classes, autoboxing and unboxing. 2

7. Define exceptions. Explain about try and catch statements 1

8. Sam wants to write a close file command in his code. Suggest sam where to write 4
the command(in try, catch or finally blocks). Justify.

9. 3
Lilly wants to find the rate of an individual item purchased using the concept of
arrays. She stores the quantity of each item purchased in a quan[] array and the total
amount of individual item in an amount[] array. She manually made an error while
making the entry in the quan[] array as zero. So, it should throw a divide by zero
exception which needs to be handled. Help her in writing code by using exception
handling.

10. Differentiate between character streams and byte streams in java. 4

QNo Question BTL

1. Define exception. What will be the output if the exception is thrown in a program. 2

2. Which type of exceptions should be used in throws clause. 2

3. Explain about the throw keyword. 1


4. What is the output of the following code. 4

class exception_handling
{
public static void main(String args[])
{
try
{
System.out.print("Hello" + " " + 1 / 0);
}
catch(ArithmeticException e)
{
System.out.print("World");
}
}
}

5. Can a single catch block handle more than one type of exception. 4

6. Which class can be used to take input from a file. 2

7. Which class can be used to write input from a file. 2

8. Explain how to import packages. 2

9. Discuss about any two methods present in Random class. 2

10. Define enumeration. 2

1. Rama wants to create an user defined exception to validate the staff ids if they are present in
the database or not. Help Rama in it.
A) Source Code:

import java.io.*;
import java.util.Scanner;

class Myexception extends Exception{

public String toString(){

return "Id Not Found ";


}
}

class Ud{
public static void main(String args[]){
String sid[]={"svppcse01","svppcse02","svppcse03","svppcse04","svppcse05"};
String id;
int ch,i;
Scanner sc=new Scanner(System.in);
System.out.println("validating Staff ID's : ");
System.out.println("1.validate");
System.out.println("2.Exit");
System.out.print("Enter Choice : ");
ch=sc.nextInt();
id =sc.nextLine();
while(ch!=2){
System.out.print("Enter Id : ");
id =sc.nextLine();
try{
for(i=0;i<sid.length;i++)

if(id.equals(sid[i])){
System.out.println(id+" Found ! ");
break;
}
if(i==(sid.length-1)){
Myexception e=new Myexception();
throw e;
}
}
}
catch(Myexception e){

System.out.println(e);
}
System.out.print("Enter Choice : ");
ch=sc.nextInt();
id =sc.nextLine();

}
}

Output:

validating Staff ID's :


1.validate
2.Exit
Enter Choice : 1
Enter Id : svpcet
Id Not Found
Enter Choice : 1
Enter Id : svppcse01
svppcse01 Found !
Enter Choice : 2
2. Explain what happens when an exception is thrown by the main method.
● A Java exception is an object that describes an exceptional (that is, error) condition that
has occured in a piece of code.
● When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
● That method may choose to handle the exception itself, or pass it on. Either way, at some
point, the exception is caught and processed.
● Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code.

Consider a small code that causes a divide-by-zero error:


class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}

● When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception.
● This causes the execution of Exc0 to stop, because once an exception has been thrown, it
must be caught by an exception handler and dealt with immediately.
● In this example, we haven’t supplied any exception handlers of our own, so the exception
is caught by the default handler provided by the Java run-time system.
● Any exception that is not caught by your program will ultimately be processed by the
default handler.
● The default handler displays a string describing the exception, prints a stack trace from the
point at which the exception occurred, and terminates the program.

Here is the exception generated when this example is executed:


java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)

● The class name, Exc0; the method name, main; the filename, Exc0.java; and the line
number, 4, are all included in the simple stack trace.
● The type of exception thrown is a subclass of Exception called ArithmeticException,
which more specifically describes what type of error happened.
● The stack trace will always show the sequence of method invocations that led up to the
error.

For example, here is another version of the preceding program that introduces the same error but
in a method separate from main( ):
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}

The resulting stack trace from the default exception handler shows how the entire call stack is
displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)

The bottom of the stack is main’s line 7, which is the call to subroutine( ), which caused the
exception at line 4. The call stack is quite useful for debugging, because it pinpoints the precise
sequence of steps that led to the error.

3. Differentiate between checked and unchecked exceptions in java.

Checked Exceptions in Java

● A checked exception (also called a logical exception) in Java is something that has gone wrong in
your code and is potentially recoverable.
● For example, if there’s a client error when calling another API, we could retry from that exception
and see if the API is back up and running the second time.
● A checked exception is caught at compile time so if something throws a checked exception the
compiler will enforce and we can write a code to handle the exception.

The code below shows the FileInputStream method from the java.io package. This method throws a
checked exception and the compiler is forcing us to handle it. You can do this in one of two ways.
import java.io.File;
import java.io.FileInputStream;

public class CheckedException {


public void readFile() {
String fileName = "file does not exist";
File file = new File(fileName);
FileInputStream stream = new FileInputStream(file);
}
}

1. Using try and catch block


import java.io.File;
import java.io.FileInputStream; import java.io.FileNotFoundException;

public class CheckedException {


public void readFile() {
String fileName = "file does not exist";
File file = new File(fileName);
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
2. Using throws
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class CheckedException {


public void readFile() throws FileNotFoundException {
String fileName = "file does not exist";
File file = new File(fileName);
FileInputStream stream = new FileInputStream(file);
}
}
We use the keyword throws to throw the checked exception up the stack to the calling method to handle

Unchecked Exceptions in Java

● An unchecked exception (also known as an runtime exception) in Java is something that has gone
wrong with the program and is unrecoverable
● The most common Java unchecked exception is the NullPointerException which is when you are
trying to access a variable or object that doesn’t exist.

The difference between a checked and unchecked exception is that a checked exception is caught at
compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception
must be handled either by re-throwing or with a try catch block, a runtime isn’t required to be handled.
An unchecked exception is a programming error and are fatal, whereas a checked exception is an
exception condition within your codes logic and can be recovered or retried from.

Unchecked Exception Examples

BindException

Systems are built from lots of small micro services doing their own thing all talking to each other,
generally over HTTP, this exception is popping up more and more. We have to find a free port as only
one system can use a single port at any one time and it’s on a first come, first serve basis. Most web
applications default to port 8080 so the easiest option is to pick another one.

IndexOutOfBoundsException

This is a very common Java unchecked exception when dealing with arrays. We have tried to access an
index in an array that does not exist. If an array has 10 items and you ask for item 11 you will get this
exception.

import java.util.ArrayList;
import java.util.List;

public class IndexOutOfBounds {


public static void main(String[] args) {
List<String> lst = new ArrayList<>();
lst.add("item-1");
lst.add("item-2");
lst.add("item-3");
var result = lst.get(lst.size());
}
}
The above piece of Java code is a common way to get an IndexOutOfBoundsException. The reason this
trips people up is because the size of the array is 3 - makes sense; there are 3 items - but arrays are
0-based so the last item in the array is at index 2. To access the last item, it is always the size -1.

Difference Between Checked and Unchecked Exceptions in Java

● A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it
states, at runtime.
● A checked exception must be handled either by re-throwing or with a try catch block, whereas an
unchecked isn’t required to be handled.
● A runtime exception is a programming error and is fatal whereas a checked exception is an
exception condition within your code’s logic and can be recovered or re-tried from.

4. a) Can we have an empty catch block? Justify.

b) Can we have multiple catch blocks? Justify.


a)Yes, we can have an empty catch block. But this is a bad practice to implement in Java.

● The try block has the code which is capable of producing exceptions which will be handled in the
catch block.
● If anything is wrong in the try block, for example, divide by zero, file not found, etc.
● It will generate an exception that is caught by the catch block.
● The catch block catches and handles the exception.
● If the catch block is empty then we will have no idea what went wrong within our code

Example:

public class EmptyCatchBlockTest {


public static void main(String[] args) {
try {
int a = 4, b = 0;
int c = a/b;
} catch(ArithmeticException ae) {
// An empty catch block
}
}
}
In the above code, the catch block catches the exception but doesn’t print anything in the console as the
catch block is empty.This makes the user think that there is no exception in the code. So it's a good
practice to print corresponding exception messages in the catch block.

b)Yes, we can define one try block with multiple catch blocks in Java.
● Every try should and must be associated with at least one catch block.
● Whenever an exception object is identified in a try block and if there are multiple catch
blocks then the priority for the catch block would be given based on the order in which
catch blocks are have been defined.
● Highest priority would be always given to first catch block. If the first catch block cannot
handle the identified exception object then it considers the immediate next catch block.

Example:
class TryWithMultipleCatch {
public static void main(String args[]) {
try{
int a[]=new int[5];
a[3]=10/0;
System.out.println("First print statement in try block");
} catch(ArithmeticException e) {
System.out.println("Warning: ArithmeticException");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Warning: ArrayIndexOutOfBoundsException");
} catch(Exception e) {
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block

5. Evaluate the scope of a variable or a method if it is declared as private, public and


protected
● In order to use the data from one package to another package or within the package, we
have to use the concept of access specifiers.
● In JAVA we have four types of access specifiers. They are
■ Private
■ Default (not a keyword)
■ protected and
■ public

Access specifiers make us to understand how to access the data within the package and across the
package

Syntax for declaring a variable along with access specifiers.


[Access specifiers] [Static] [Final] data type v1 [=val1], v2 [=val2] ...vn [=valn];
For example:
public static final int a=10;
protected int d;
int x; [If we are not using any access specifier it is by default treated as default access specifier].
private int e;
package sp;
public class Sbc
{
private int N_PRI=10;
int N_DEF=20;
protected int N_PRO=30;
public int N_PUB=40;
public Sbc()
{
System.out.println ("VALUE OF N_PRIVATE = "+N_PRI);
System.out.println ("VALUE OF N_DEFAULT = "+N_DEF);
System.out.println ("VALUE OF N_PROTECTED = "+N_PRO);
System.out.println ("VALUE OF N_PUBLIC = "+N_PUB);
}
}
// Sdc.java
// javac -d . Sdc.java
package sp;
public class Sdc extends Sbc //(is-a relation & within only)
{
public Sdc()
{
// System.out.println ("VALUE OF N_PRIVATE = "+N_PRI);
System.out.println ("VALUE OF N_DEFAULT = "+N_DEF);
System.out.println ("VALUE OF N_PROTECTED = "+N_PRO);
System.out.println ("VALUE OF N_PUBLIC = "+N_PUB);
}
}
// Sic.java
// javac -d . Sic.java
package sp;
public class Sic
{
Sbc so=new Sbc(); // (has-a relation & within only)
public Sic()
{
// System.out.println ("VALUE OF N_PRIVATE = "+so.N_PRI);
System.out.println ("VALUE OF N_DEFAULT = "+so.N_DEF);
System.out.println ("VALUE OF N_PROTECTED = "+so.N_PRO);
System.out.println ("VALUE OF N_PUBLIC = "+so.N_PUB);
}
}
// Odc.java
// javac -d . Odc.java
package op;
public class Odc extends sp.Sbc // (is-a relation & across)
{
public Odc ()
{
// System.out.println ("VALUE OF N_PRIVATE = "+N_PRI);
// System.out.println ("VALUE OF N_DEFAULT = "+N_DEF);
System.out.println ("VALUE OF N_PROTECTED = "+N_PRO);
System.out.println ("VALUE OF N_PUBLIC = "+N_PUB);
}
}
// Oic.java
// javac -d . Oic.java
package op;
public class Oic
{
sp.Sbc so=new sp.Sbc (); // (has-a relation & across)
public Oic ()
{
// System.out.println ("VALUE OF N_PRIVATE = "+so.N_PRI);
// System.out.println ("VALUE OF N_DEFAULT = "+so.N_DEF);
// System.out.println ("VALUE OF N_PROTECTED = "+so.N_PRO);
System.out.println ("VALUE OF N_PUBLIC = "+so.N_PUB);
}
};
// ASDemo.java
// javac ASDemo.java
import sp.Sbc;
import sp.Sdc;
import sp.Sic;
class ASDemo
{
public static void main (String [] args)
{
// import approach
System.out.println ("WITH RESPECT TO SAME PACKAGE BASE CLASS");
Sbc so1=new Sbc();
System.out.println ("WITH RESPECT TO SAME PACKAGE DERIVED CLASS");
Sdc so2=new Sdc();
System.out.println ("WITH RESPECT TO SAME PACKAGE INDEPENDENT CLASS");
Sic so3=new Sic();
//fully qualified name approach
System.out.println ("WITH RESPECT TO OTHER PACKAGE DERIVED CLASS");
op.Odc oo1=new op.Odc();
System.out.println ("WITH RESPECT TO OTHER PACKAGE INDEPENDENT CLASS");
op.Oic oo2=new op.Oic();
}
}
6. Discuss about wrapper classes autoboxing and unboxing.
Wrapper classes in java
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.
There are certain needs for using the Wrapper class in Java as mentioned below:
1. They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value.
2. The classes in java.util package handles only objects and hence wrapper classes help in this
case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.

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.
5. Serialization can allow only object data.

1. Autoboxing

The automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.
Example:
import java.util.ArrayList;
class Autoboxing {
public static void main(String[] args)
{
char ch = 'a';

// Autoboxing- primitive to Character object


// conversion
Character a = ch;

ArrayList<Integer> arrayList
= new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arrayList.add(25);

// printing the values from object


System.out.println(arrayList.get(0));
}
}
Output: 25

2. Unboxing

It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its
corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to
long, Double to double, etc.
Example:
import java.util.ArrayList;

class Unboxing {
public static void main(String[] args)
{
Character ch = 'a';

// unboxing - Character object to primitive


// conversion
char a = ch;

ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(24);

// unboxing because get method returns an Integer


// object
int num = arrayList.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}
Output:24

7. Define exceptions. Explain about try and catch statements


Definition:
● An exception is a run time error that occurs during the execution of a program that disrupts the
normal flow of instructions.
● Exception may occur for the following reasons.
● Run out of memory
● Resource allocation Error
● Inability to find a file
● Problems in Network connectivity.

Exception handling in java:


● When an exception occurs, the program throws an exception
● The exception object that is thrown contains information about the exception, including its type
and the state of the program when the error occurred.
● The runtime environment attempts to find the exception handler.
● The exception handler can attempt to recover from the error or, if it determines that the error is
unrecoverable, provide a gentle exit from the program.
● Java exception handling is managed via 5 keywords: try, catch, throw, throws and finally.
○ try – a block surrounding program statements to monitor for exceptions
○ catch – together with try, catches specific kinds of exceptions and handles them in some
way
○ finally – specifies any code that absolutely must be executed whether or not an exception
occurs
○ throw – used to throw a specific exception from the program
○ throws – specifies which exceptions a given method can throw
General form:
try { ... }
catch(Exception1 ex1) { ... }
catch(Exception2 ex2) { ... }
...
finally { ... }
where:
1) try { ... } is the block of code to monitor for exceptions
2) catch(Exception ex) { ... } is exception handler for the exception Exception
3) finally { ... } is the block of code to execute before the try block ends.
Exception Hierarchy

● All exceptions are sub-classes of the build-in class Throwable. Throwable contains two
immediate sub-classes:
1) Exception – exceptional conditions that programs should catch. The class includes:
a) RuntimeException – defined automatically for user programs to include: division by
zero, invalid array indexing, etc.
b) use-defined exception classes
2) Error – Exceptions of type Error are related to errors that are beyond user control such as
those occur in the JVM itself. Example:Stack overflow error; user programs are not supposed to
catch them

Syntax for exceptional handling:


● In order to handle the exceptions in java we must use the following keywords. They are try,
catch, finally, throws and throw.
try
{
Block of statements which are to be monitored by JVM at run time (or problematic errors);
}
catch (Type_of_exception1 object1)
{

Handler for exception type 1


}
catch (Type_of_exception2 object2)
{
Handler for exception type 2
}
.
.
.
catch (Type_of_exception3 object3)
{
Handler for exception type 3
}
finally
{
Block of statements which releases the resources;
}
Try block:
● This is the block in which we write the block of statements which are to be monitored by JVM at
run time i.e., try block must contain those statements which causes problems at run time.
● If any exception is taking place the control will be jumped automatically to appropriate catch
block.
● If any exception is taking place in try block execution will be terminated and the rest of the
statements in try block will not be executed at all and the control goes to catch block.
● For every try block we must have at least one catch block.
Catch block:
● This is used for providing user friendly messages by catching system error messages.
● In the catch we must declare an object of the appropriate exception class and it will be used to
print the appropriate message.
● If we write ‘n’ number of catch’s as a part of JAVA program then only one catch will be
executing at any point.
● After executing appropriate catch block even if we use return statement in the catch block the
control never goes to try block.

Example:
class DivByZero
{
public static void main(String args[])
{
try
{
System.out.println(3/0);
System.out.println(“Please print me.”);
} catch (ArithmeticException exc) {
//Division by zero is an ArithmeticException
System.out.println(exc);
}
System.out.println(“After exception.”);
}
}
finally
{
System.out.println ("I AM FROM FINALLY...");
}
}
}

8.Sam wants to write a close file command in his code. Suggest sam where to write the command(in
try, catch or finally blocks). Justify.

import java.io.*;
class ShowFile {
public static void main(String[] args)
{
int i;
FileInputStream fin = null;
// First, confirm that a file name has been
specified. if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// The following code opens a file, reads characters until EOF
// is encountered, and then closes the file via a finally
block. try {
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException exc) { System.out.println("File Not Found.");
} catch(IOException exc) { System.out.println("An I/O Error Occurred");
} finally {
// Close file in all
cases. try {
if(fin != null) fin.close();

} catch(IOException exc) {
System.out.println("Error Closing
File");
}
}
}
}

9. Lilly wants to find the rate of an individual item purchased using the concept of arrays. She
stores the quantity of each item purchased in a quan[] array and the total amount of individual
item in an amount[] array. She manually made an error while making the entry in the quan[] array
as zero. So, it should throw a divide by zero exception which needs to be handled. Help her in
writing code by using exception handling.
A) Source Code:

import java.io.*;
import java.util.Scanner;

class Ud1{

public static void main(String args[]){

int amount[]={200,240,150,180,160};
int qua[]={4,6,3,0,8};
int i=0;
System.out.println("Finding cost of individual Items : ");
try{

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

System.out.println("cost of item "+(i+1)+"= "+(amount[i]/qua[i]));


}
}
catch(ArithmeticException e){

System.out.println("Entered invalid quanttity 0 ");


}

for(i=(i+1);i<amount.length;i++){

System.out.println("cost of item "+(i+1)+"= "+(amount[i]/qua[i]));


}

}
}

Output :

Finding cost of individual Items :


cost of item 1= 50
cost of item 2= 40
cost of item 3= 50
Entered invalid quanttity 0
cost of item 5= 20

10. Differentiate between character stream and byte stream classes.

In Java the streams are used for input and output operations by allowing data to be read from or written to
a source or destination.

Java offers two types of streams:


1. character streams
2. byte streams.

These streams can be different in how they are handling data and the type of data they are handling.

1. Character Streams:
Character streams are designed to address character based records, which includes textual records
inclusive of letters, digits, symbols, and other characters. These streams are represented by way of
training that quit with the phrase "Reader" or "Writer" of their names, inclusive of FileReader,
BufferedReader, FileWriter, and BufferedWriter.

Character streams offer a convenient manner to read and write textual content-primarily based
information due to the fact they mechanically manage character encoding and decoding. They convert the
individual statistics to and from the underlying byte circulation the usage of a particular individual
encoding, such as UTF-eight or ASCII.It makes person streams suitable for operating with textual
content files, analyzing and writing strings, and processing human-readable statistics.

2. Byte Streams:
Byte streams are designed to deal with raw binary data, which includes all kinds of data, including
characters, pictues, audio, and video. These streams are represented through cclasses that cease with the
word "InputStream" or "OutputStream" of their names,along with FileInputStream,BufferedInputStream,
FileOutputStream and BufferedOutputStream.

Byte streams offer a low-stage interface for studying and writing character bytes or blocks of bytes. They
are normally used for coping with non-textual statistics, studying and writing files of their binary form,
and running with network sockets. Byte streams don't perform any individual encoding or deciphering.
They treat the data as a sequence of bytes and don't interpret it as characters.
Example code for Character Stream:
​ import java.io.CharArrayReader;
​ import java.io.IOException;

​ public class CharacterStreamExample
​ {
​ public static void main(String[] args) {
​ // Creates an array of characters
​ char[] array = {'H','e','l','l','o'};
​ try {
​ CharArrayReader reader=new CharArrayReader(array);
​ System.out.print("The characters read from the reader:");
​ int charRead;
​ while ((charRead=reader.read())!=-1) {
​ System.out.print((char)charRead+",");
​ }
​ reader.close();
​ } catch (IOException ex)
​ {
​ ex.printStackTrace();
​ }
​ }
​ }
Output:

The characters read from the reader:H,e,l,l,o,

Example code for Byte Stream:


​ import java.io.ByteArrayInputStream;

​ public class ByteStreamExample
​ {
​ public static void main(String[] args)
​ {
​ // Creates the array of bytes
​ byte[] array = {10,20,30,40};
​ try {
​ ByteArrayInputStream input=new ByteArrayInputStream(array);
​ System.out.println("The bytes read from the input stream:");
​ for (int i=0;i<array.length;i++)
​ {
​ // Reads the bytes
​ int data=input.read();
​ System.out.print(data+",");
​ }
​ input.close();
​ } catch (Exception ex)
​ {
​ ex.getStackTrace();
​ }
​ }
​ }

TWO MARKS QUESTIONS


1. Define exception. What will be the output if the exception is thrown in a program.

● When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
● That method may choose to handle the exception itself, or pass it on. Either way, at some
point, the exception is caught and processed.
● Otherwise it will be handled by the default handler provided by the java run time system
● The program execution will be stopped and displays a runtime error showing the stack
trace and type of exception.

2. Which type of exceptions should be used in throws clause.


Only checked exceptions should be used in throws clause. throws is a keyword in Java which is
used in the signature of 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.

class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}

3. Explain about throw keyword.


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:
throw Instance
Example:
throw new ArithmeticException("/ by zero");

public class JavaTester{


public void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
obj.checkAge(13);
System.out.println("End Of Program");
}
}

Output
Exception in thread "main" java.lang.ArithmeticException:
Not Eligible for voting
at JavaTester.checkAge(JavaTester.java:4)
at JavaTester.main(JavaTester.java:10)

4. What is the output of the following code.

class exception_handling
{
public static void main(String args[])
{
try
{
System.out.print("Hello" + " " + 1 / 0);
}
catch(ArithmeticException e)
{
System.out.print("World");
}
}
}
Output:
Hello world

5. Can a single catch block handle more than one type of exception.
Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating
each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces
code duplication and increases efficiency
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}

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 (NumberFormatException | ArithmeticException ex)
{
System.out.println("Exception encountered " + ex);
}
}
}

6. Which class can be used to take input from a file.


Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream
class.
import java.io.FileReader;

public class FileReaderExample {

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

FileReader fr=new FileReader("D:\\testout.txt");

int i;

while((i=fr.read())!=-1)
System.out.print((char)i);

fr.close();

7. Which class can be used to write output to a file.


Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance
fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single
arrays, characters, and strings.
import java.io.*;

public class BufferedWriterExample {

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

FileWriter writer = new FileWriter("D:\\testout.txt");

BufferedWriter buffer = new BufferedWriter(writer);

buffer.write("Welcome to javaTpoint.");

buffer.close();

System.out.println("Success");

8. Explain how to import a package.

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the
current package.

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is
no need to import. But you need to use fully qualified name every time when you are accessing the class
or interface.

9. Discuss about any two methods present in random class.


Random class is used to generate pseudo-random numbers in java. An instance of this class is
thread-safe. The instance of this class is however cryptographically insecure. This class provides various
method calls to generate different random data types such as float, double, int.

Methods:

java.util.Random.doubles(): Returns an effectively unlimited stream of pseudo random double values,


each between zero (inclusive) and one (exclusive)
Syntax:
public DoubleStream doubles()
Returns:
a stream of pseudorandom double values

java.util.Random.ints(): Returns an effectively unlimited stream of pseudo random int values


Syntax:
public IntStream ints()
Returns:
a stream of pseudorandom int values

10. Define enumeration.

An enum is a special "class" that represents a group of constants (unchangeable variables, like final
variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the constants with
a comma.

Example:

enum Level {
LOW,
MEDIUM,
HIGH

You can access enum constants with the dot syntax:

Level myVar = Level.MEDIUM;


BIT BANK

1. When does Exceptions in Java arises in code sequence?


a) Run Time
b) Compilation Time
c) Can Occur Any Time
d) None of the mentioned

2. Which of these keywords is not a part of exception handling?


a) try
b) finally
c) thrown
d) catch

3. Which of these keywords must be used to monitor for exceptions?


a) try
b) finally
c) throw
d) catch

4. Which of these keywords must be used to handle the exception thrown by try block in some rational
manner?
a) try
b) finally
c) throw
d) catch

5. Which of these keywords is used to manually throw an exception?


a) try
b) finally
c) throw
d) catch

6. What does AWT stands for?


a) All Window Tools
b) All Writing Tools
c) Abstract Window Toolkit
d) Abstract Writing Toolkit

7. Which of these is used to perform all input & output operations in Java?
a) streams
b) Variables
c) classes
d) Methods

8. Which of these is a type of stream in Java?


a) Integer stream
b) Short stream
c) Byte stream
d) Long stream

9. Which of these classes are used by Byte streams for input and output operation?
a) InputStream
b) InputOutputStream
c) Reader
d) All of the mentioned

10. Which of these class is used to read from byte array?


a) InputStream
b) BufferedInputStream
c) ArrayInputStream
d) ByteArrayInputStream

11. Which of these class contains the methods used to write in a file?
a) FileStream
b) FileInputStream
c) BUfferedOutputStream
d) FileBufferStream

12. Which of these exception is thrown in cases when the file specified for writing is not found?
a) IOException
b) FileException
c) FileNotFoundException
d) FileInputException

13. Which of these methods are used to read in from file?


a) get()
b) read()
c) scan()
d) readFileInput()

14. Which of these values is returned by read() method is end of file (EOF) is encountered?
a) 0
b) 1
c) -1
d) Null

15. Which of these exception is thrown by close() and read() methods?


a) IOException
b) FileException
c) FileNotFoundException
d) FileInputOutputException

UNIT-5
QNo Question BTL

1. Ravi wants to create a login window for his website using javafx. Which layout will 3
you prefer? Justify and create the application for Ravi.

2. Discuss about any three layout panes available in javafx with an example. 2

3. Explain about the structure of javafx applications. 1

4. Discuss about the similarities and differences between javafx and swing 4
applications.

5. Illustrate an example regarding mouse events. 6

6. Illustrate about different methods for extracting characters from string with an 6
example.

7. Discuss the steps involved in establishing JDBC database connection 3

8. Discuss about Interthread communication in java. 2

9. Discuss about lifecycle and states of thread in java. 2

10. Discuss about the methods present in result set Interface 2

QNo Question BTL

1. Define scene graph. 2

2. Discuss about usage of threads 2

3. What are the main important components of javafx. 2

4. Write the import statements to create a text node in javafx and set its colour to blue. 6

5. Explain how to create a new thread. 2

6. Draw jdbc architecture. 2

7. Explain when the Action event handler should be used. 4

8. Define event. 1

9. Discuss about how to compare two strings. 4

10. Explain how to add nodes to a Group object. 2

1. Ravi wants to create a login window for his website using javafx. Which layout will you prefer?
Justify and create the application for Ravi.
I suggest GridPane to implement a login window as it is an easy way to arrange nodes in rows and
columns.
Source code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.control.Label;

public class JavaFXApplication6 extends Application {

@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Submit");
TextField tf1=new TextField();
TextField tf2=new TextField();
Label l1=new Label("User name");
Label l2=new Label("Password");

GridPane root = new GridPane();


root.addRow(0,l1,tf1 );
root.addRow(1,l2,tf2);
root.addRow(2,btn);

Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

Output:
2. Discuss about any three layout panes available in javafx with an example.

JavaFX provides several predefined layouts such as HBox, VBox, Border Pane, Stack Pane, Text Flow,
Anchor Pane, Title Pane, Grid Pane, Flow Panel, etc.

Creating a Layout
To create a layout, you need to −

● Create node.
● Instantiate the respective class of the required layout.
● Set the properties of the layout.
● Add all the created nodes to the layout.

HBox
HBox layout pane arranges the nodes in a single row. It is represented by javafx.scene.layout.HBox class.
We just need to instantiate HBox class in order to create HBox layout.
Constructors

The HBox class contains two constructors that are given below.

new HBox() : create HBox layout with 0 spacing

new Hbox(Double spacing) : create HBox layout with a spacing value

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
} }
Output:
VBox:
Vbox Layout Pane arranges the nodes in a single vertical column. It is represented by
javafx.scene.layout.VBox class which provides all the methods to deal with the styling and the distance
among the nodes. This class needs to be instantiated in order to implement VBox layout in our
application.
Constructors
VBox() : creates layout with 0 spacing
Vbox(Double spacing) : creates layout with a spacing value of double type
Vbox(Double spacing, Node? children) : creates a layout with the specified spacing among the specified
child nodes
Vbox(Node? children) : creates a layout with the specified nodes having 0 spacing among them

Example

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
VBox root = new VBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Output:
Grid Pane
GridPane Layout pane allows us to add the multiple nodes in multiple rows and columns. It is seen as a
flexible grid of rows and columns where nodes can be placed in any cell of the grid. It is represented by
javafx.scence.layout.GridPane class.

Constructors

The class contains only one constructor that is given below.

public GridPane(): creates a gridpane with 0 hgap/vgap.

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.control.TextField;

import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

public class Label_Test extends Application {

@Override

public void start(Stage primaryStage) throws Exception {

Label first_name=new Label("First Name");

Label last_name=new Label("Last Name");

TextField tf1=new TextField();

TextField tf2=new TextField();

Button Submit=new Button ("Submit");

GridPane root=new GridPane();

Scene scene = new Scene(root,400,200);

root.addRow(0, first_name,tf1);

root.addRow(1, last_name,tf2);
root.addRow(2, Submit);

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

3. Explain about the structure of javafx applications.

JavaFX Application Structure


In general, a JavaFX application will have three major components namely Stage, Scene and Nodes
Stage
● A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage
class of the package javafx.stage.
● The primary stage is created by the platform itself.
● The created stage object is passed as an argument to the start() method of the Application class
● A stage has two parameters determining its position namely Width and Height. It is divided as
Content Area and Decorations (Title Bar and Borders).
There are five types of stages available −
● Decorated
● Undecorated
● Transparent
● Unified
● Utility
● Call the show() method to display the contents of a stage.
Scene
● A scene represents the physical contents of a JavaFX application.
● It contains all the contents of a scene graph.
● The class Scene of the package javafx.scene represents the scene object. At an instance, the scene
object is added to only one stage.
● You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by
passing its dimensions (height and width) along with the root node to its constructor.
Scene Graph and Nodes
● A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In
contrast, a node is a visual/graphical object of a scene graph.
A node may include −
● Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
● UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
● Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
● Media elements such as Audio, Video and Image Objects.
● The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super
class of all the nodes.
● node is of three types −
● Root Node − The first Scene Graph is known as the Root node.
● Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes.
The abstract class named Parent of the package javafx.scene is the base class of all the
parent nodes, and those parent nodes will be of the following types −
○ Group − A group node is a collective node that contains a list of children
nodes. Whenever the group node is rendered, all its child nodes are rendered
in order. Any transformation, effect state applied on the group will be
applied to all the child nodes.
○ Region − It is the base class of all the JavaFX Node based UI Controls, such
as Chart, Pane and Control.
○ WebView − This node manages the web engine and displays its contents.
● Leaf Node − The node without child nodes is known as the leaf node. For example,
Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
● It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the
nodes will be clipped to the scene and any alteration in the size of the scene will not affect the
layout of the scene.

4. Discuss about the similarities and differences between javafx and swing applications.

1. Swing is the standard toolkit for Java developer in creating GUI, whereas JavaFX provides
platform support for creating desktop applications.
2. Swing has a more sophisticated set of GUI components, whereas JavaFX has a decent number of
UI components available but lesser than what Swing provides.
3. Swing is a legacy library that fully features and provide pluggable UI components, whereas
JavaFX has UI components that are still evolving with a more advanced look and feel.
4. Swing can provide UI components with a decent look and feel, whereas JavaFX can provide rich
internet application having a modern UI.
5. Swing related classes can be found in the Java API guide with complete documentation, whereas
JavaFX doc is available in various format with comprehensive detailing and file support.
6. Swing, since its advent, can create UI component using standard Java component classes, whereas
Java FX initially uses a declarative language called JavaFX Script.
7. Swing has a UI component library and act as a legacy, whereas JavaFX has several components
built over Swing.
8. Swing has support for MVC, but it is A swing was renamed from Java Foundation Classes, and
sun microsystems announced it in the year 1997, whereas JavaFX was initially released in
December 2008 by Sun microsystem and now acquired by Oracle.
9. Swings are not consistent across a component, whereas JavaFX support is very friendly with
MVC.
10. Swing has various IDEs, which offer a tool for rapid development, whereas JavaFX has also
support from various IDEs as well, but it is not as mature as Swing.

Java Swing Java FX

Components Swing has a number of Less component as compared to

components to it legacy Swing APIs

User Interface Standard UI components can be Rich GUI components can be

designed with Swing created with an advanced look

and feel
Development Swing APIs are being used to JavaFX scripts and fast UI

write UI components development with screen builder

Functionality No new functionality JavaFX has a rich new toolkit,

introduction for future expected to grow in future

Category Legacy UI library fully featured Up and coming to feature-rich UI

components

MVC Support MVC support across Friendly with MVC pattern

components lack consistency

5. Illustrate an example regarding keyevents.

Program:

import javafx.application.Application;

import javafx.scene.input.KeyEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.text.Text;

import javafx.scene.control.Button;

import javafx.scene.control.TextField;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

import javafx.scene.shape.Circle;

import javafx.scene.Group;
import javafx.scene.paint.Color;

public class JavaFXApplication1 extends Application {


@Override

public void start(Stage primaryStage) {

Circle c=new Circle();

c.setCenterX(135.0f);

c.setCenterY(125.0f);

c.setRadius(25.0f);

Group root = new Group(c);

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

primaryStage.setTitle("Key Events");

primaryStage.setScene(scene);

primaryStage.show();

scene.setOnKeyPressed(new EventHandler<KeyEvent>() {

@Override

public void handle(KeyEvent event) {

switch(event.getCode()){

case UP: c.setCenterX(c.getCenterX());

c.setCenterY(c.getCenterY()-5);

break;

case DOWN: c.setCenterX(c.getCenterX());

c.setCenterY(c.getCenterY()+5);

break;

case LEFT: c.setCenterX(c.getCenterX()-5);

c.setCenterY(c.getCenterY());

break;
case RIGHT: c.setCenterX(c.getCenterX()+5);

c.setCenterY(c.getCenterY());

break;

} }

});

public static void main(String[] args) {

launch(args);

Output

6. Illustrate about different methods for extracting characters from string with an example.
Java provides several methods to extract characters from a string. These methods are useful for
manipulating and analyzing strings at the character level.

1. charAt()
2. getChars()
3. getBytes()
4. toCharArray()

charAt()
The charAt() method returns the character at a specified index in a string. The index is zero-based,
meaning the first character is at index 0.
Syntax:
public char charAt(int index)

Example:
public class CharAtExample {
public static void main(String[] args) {
String str = "Hello, World!";
char ch = str.charAt(7);

System.out.println("Character at index 7: " + ch);


}
}

Output:
Character at index 7: W
2. getChars()
The getChars() method copies characters from a specified segment of a string into a destination character
array.
Syntax:
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

● srcBegin: The starting index (inclusive).


● srcEnd: The ending index (exclusive).
● dst: The destination array.
● dstBegin: The starting index in the destination array.
Example:
public class GetCharsExample {
public static void main(String[] args) {
String str = "Hello, World!";
char[] dst = new char[5];

str.getChars(7, 12, dst, 0);

System.out.println("Extracted characters: " + new String(dst));


}
}

Output:
Extracted characters: World

3. getBytes()
The getBytes() method encodes the string into a sequence of bytes using the platform's default charset
and returns the resulting byte array.
Syntax:
public byte[] getBytes()

Example:
import java.util.Arrays;

public class GetBytesExample {


public static void main(String[] args) {
String str = "Hello";
byte[] byteArray = str.getBytes();

System.out.println("Byte array: " + Arrays.toString(byteArray));


}
}

Output:
Byte array: [72, 101, 108, 108, 111]

4. toCharArray()
The toCharArray() method converts the string to a new character array.
Syntax:
public char[] toCharArray()

Example:
public class ToCharArrayExample {
public static void main(String[] args) {
String str = "Hello";
char[] charArray = str.toCharArray();

System.out.println("Character array: " + Arrays.toString(charArray));


}
}

Output:
Character array: [H, e, l, l, o]

7. Discuss the steps involved in establishing JDBC database connection


JDBC is a standard API specification developed in order to move data from the front end to the back end.
This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we
use in Java) or channel between your Java program and databases i.e it establishes a link between the two
so that a programmer can send data from Java code and store it in the database for future use.

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

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.

Pseudo Code:

int m = st.executeUpdate(sql);

if (m==1)

System.out.println("inserted successfully : "+sql);

else

System.out.println("insertion failed");

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

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

class GFG {
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
= 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....");
}
}

8. Discuss about Interthread communication in java.

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate


with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its


critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:

○ wait()
○ notify()
○ notifyAll()

1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.

public final void wait()throws InterruptedException

2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.

Syntax:

​ public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

​ public final void notifyAll()


​ class Customer{
​ int amount=10000;

​ synchronized void withdraw(int amount){
​ System.out.println("going to withdraw...");

​ if(this.amount<amount){
​ System.out.println("Less balance; waiting for deposit...");
​ try{wait();}catch(Exception e){}
​ }
​ this.amount-=amount;
​ System.out.println("withdraw completed...");
​ }

​ synchronized void deposit(int amount){
​ System.out.println("going to deposit...");
​ this.amount+=amount;
​ System.out.println("deposit completed... ");
​ notify();
​ }
​ }

​ class Test{
​ public static void main(String args[]){
​ final Customer c=new Customer();
​ new Thread(){
​ public void run(){c.withdraw(15000);}
​ }.start();
​ new Thread(){
​ public void run(){c.deposit(10000);}
​ }.start();

​ }}
Output:

going to withdraw...

Less balance; waiting for deposit...

going to deposit...

deposit completed...

withdraw completed

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

9. Discuss about lifecycle and states of thread in java


A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of
the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State

The diagram shown below represents various states of a thread at any instant in time.

Life Cycle of a Thread


There are multiple states of the thread in a lifecycle as mentioned below:

1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state. When a thread lies in the new state, its code is
yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
thread might actually be running or it might be ready to run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each
and every thread runs for a short while and then pauses and relinquishes the CPU to another
thread so that other threads can get a chance to run. When this happens, all such threads that
are ready to run, waiting for the CPU and the currently running thread lie in a runnable state.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently
the lock is acquired by the other thread. The thread will move from the blocked state to
runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join() method.
It will move to the runnable state when other thread will notify or that thread will be
terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is
received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed
waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:

● Because it exits normally. This happens when the code of the thread has been
entirely executed by the program.
● Because there occurred some unusual erroneous event, like a segmentation fault or
an unhandled exception.

Implementing the Thread States in Java


In Java, to get the current state of the thread, use Thread.getState() method to get the current state of the
thread. Java provides java.lang.Thread.State class that defines the ENUM constants for the state of a
thread, as a summary of which is given below:

1. New

Thread state for a thread that has not yet started.

public static final Thread.State NEW

2. Runnable

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine
but it may be waiting for other resources from the operating system such as a processor.

public static final Thread.State RUNNABLE


3. Blocked

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a
monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling
Object.wait().

public static final Thread.State BLOCKED

4. Waiting

Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following
methods:

● Object.wait with no timeout


● Thread.join with no timeout
● LockSupport.park

public static final Thread.State WAITING

5. Timed Waiting

Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due
to calling one of the following methods with a specified positive waiting time:

● Thread.sleep
● Object.wait with timeout
● Thread.join with timeout
● LockSupport.parkNanos
● LockSupport.parkUntil

public static final Thread.State TIMED_WAITING

6. Terminated

Thread state for a terminated thread. The thread has completed execution.

Declaration: public static final Thread.State TERMINATED

10. Discuss about the methods present in result set Interface

● The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result
set. The java.sql.ResultSet interface represents the result set of a database query.
● A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.

The methods of the ResultSet interface can be broken down into three categories −

● Navigational methods − Used to move the cursor around.


● Get methods − Used to view the data in the columns of the current row being pointed by the
cursor.
● Update methods − Used to update the data in the columns of the current row. The updates can
then be updated in the underlying database as well.

Type of ResultSet

The possible RSType are given below. If you do not specify any ResultSet type, you will automatically
get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the


result set.

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and


backward, and the result set is not
sensitive to changes made by others to
the database that occur after the result set
was created.

ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and


backward, and the result set is sensitive
to changes made by others to the
database that occur after the result set
was created.
Navigating a Result Set

There are several methods in the ResultSet interface that involve moving the cursor, including −

S.N. Methods & Description

1 public void beforeFirst() throws SQLException


Moves the cursor just before the first row.

2 public void afterLast() throws SQLException


Moves the cursor just after the last row.

3 public boolean first() throws SQLException


Moves the cursor to the first row.

4 public void last() throws SQLException


Moves the cursor to the last row.

5 public boolean absolute(int row) throws SQLException


Moves the cursor to the specified row.

6 public boolean relative(int row) throws SQLException


Moves the cursor the given number of rows forward or backward, from where it is
currently pointing.

7 public boolean previous() throws SQLException


Moves the cursor to the previous row. This method returns false if the previous row
is off the result set.

8 public boolean next() throws SQLException


Moves the cursor to the next row. This method returns false if there are no more
rows in the result set.

9 public int getRow() throws SQLException


Returns the row number that the cursor is pointing to.
10 public void moveToInsertRow() throws SQLException
Moves the cursor to a special row in the result set that can be used to insert a new
row into the database. The current cursor location is remembered.

11 public void moveToCurrentRow() throws SQLException


Moves the cursor back to the current row if the cursor is currently at the insert row;
otherwise, this method does nothing

TWO MARKS QUESTIONS

1. Define scene graph.


Scene Graph and Nodes
● A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In
contrast, a node is a visual/graphical object of a scene graph.
A node may include −
● Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
● UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
● Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
● Media elements such as Audio, Video and Image Objects.
● The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super
class of all the nodes.
● node is of three types −
● Root Node − The first Scene Graph is known as the Root node.
● Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes.
The abstract class named Parent of the package javafx.scene is the base class of all the
parent nodes, and those parent nodes will be of the following types −
○ Group − A group node is a collective node that contains a list of children
nodes. Whenever the group node is rendered, all its child nodes are rendered
in order. Any transformation, effect state applied on the group will be
applied to all the child nodes.
○ Region − It is the base class of all the JavaFX Node based UI Controls, such
as Chart, Pane and Control.
○ WebView − This node manages the web engine and displays its contents.
● Leaf Node − The node without child nodes is known as the leaf node. For example,
Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
● It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the
nodes will be clipped to the scene and any alteration in the size of the scene will not affect the
layout of the scene.

2. Discuss about usage of threads


Threads are a vital feature of the Java platform that allow for concurrent execution, which improves
performance and makes Java applications more responsive:

● Divides tasks Threads allow a program to perform multiple tasks simultaneously, which can be
more efficient than performing tasks one after the other.
● Handles operationsThreads are essential for efficiently handling network communication and
I/O operations.
● Performs background tasks Threads can perform complicated tasks in the background without
interrupting the main program.

3. What are the main important components of javafx.


● Any JavaFX application will have three major components namely Stage, Scene and Nodes

4. Create a text node in javafx and set its color to blue.

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.text.Text;

import javafx.stage.Stage;

import javafx.scene.Group;

import javafx.scene.paint.Color;
5. Explain how to create a new thread

There are two ways to create a thread.


● It can be created by extending the Thread class and overriding its run() method:

public class Main extends Thread {


public void run() {
System.out.println("This code is running in a thread");
}
}

● Another way to create a thread is to implement the Runnable interface:


Implement Syntax
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}

6. Draw JDBC Architecture

7. Explain when the Action event handler should be used.


The ActionEvent is generated when button is clicked or the item of a list is double clicked.
Constructors

ActionEvent()
Creates a new ActionEvent with an event type of ACTION.

ActionEvent(Object source, EventTarget target)


Construct a new ActionEvent with the specified event source and target.

8. Define an event?

● Whenever a user interacts with the application (nodes), an event is said to have occurred.
● For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
● Types of Event: The events can be broadly classified into the following two categories −
○ Foreground Events − Those events which require the direct interaction of a user. They are
generated as consequences of a person interacting with the graphical components in a
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page, etc.
○ Background Events − Those events that don't require the interaction of end-user are
known as background events. The operating system interruptions, hardware or software
failure, timer expiry, operation completion are the example of background events.

9. Discuss how to compare two strings.

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

1) By Using equals() Method


The String class equals() method compares the original content of the string. It compares values of string
for equality.

​ String s1="Sachin";
​ String s2="Sachin";
​ String s3=new String("Sachin");
​ String s4="Saurav";
​ System.out.println(s1.equals(s2));//true
​ System.out.println(s1.equals(s3));//true
​ System.out.println(s1.equals(s4));//false

2) By Using == operator
The == operator compares references not values.

​ String s1="Sachin";
​ String s2="Sachin";
​ String s3=new String("Sachin");
​ System.out.println(s1==s2);//true (because both refer to same instance)
​ System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)

3) By Using compareTo() method


The String class compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

○ s1 == s2 : The method returns 0.


○ s1 > s2 : The method returns a positive value.
○ s1 < s2 : The method returns a negative value.

10. Explain how to add nodes to a group object.


● There are two ways to add nodes to a group object
1. The getChildren() method of the Group class gives you an object of the ObservableList class
which holds the nodes. We can retrieve this object and add nodes to it as shown below.

//Retrieving the observable list object


ObservableList list = root.getChildren();

//Setting the text object as a node


list.add(NodeObject);

2. We can also add Node objects to the group, just by passing them to the Group class and to its
constructor at the time of instantiation, as shown below.

Group root = new Group(NodeObject);

BIT BANK

1. Which of these packages contains all the classes and methods required for event handling in Java.
a) javafx.scene
b) javafx.awt
c) javafx.event
d) javafx.scene.event

2. Button class related to which package.


a) javafx.scene.control
b) javafx.stage.control
c) javafx.application.control
d) javafx.scene.event

3. Circle class related to which package.


a) javafx.scene.control
b) javafx.stage.control
c) javafx.application.control
d) javafx.scene.shape

4. To apply color to a node which package should be imported.


a) javafx.scene.control
b) javafx.stage.paint
c) javafx.application.control
d) javafx.scene.shape

5. Which method is used to display the contents on the stage.


a) display()
b) show()
c) shown
d) None

6. Which type of objects can be taken as root node.


a) Group
b) Region
c) Web View
d) All

7. Which of these methods are used to register an event filter?


a) addEvent()
b) addEventFilter()
c) addEventListener()
d) None

8. Which of these methods is used to align a node


a) getAlignment()
b) AlignCenter()
c) setAlignment()
d) All

9. Which of these classes is the super class of all the events?


a) EventObject
b) EventClass
c) ActionEvent
d) ItemEvent

10. Which of these events will be notified if the mouse is dragged?


a) ActionEvent
b) DragEvent
c) AdjustmentEvent
d) WindowEvent

11. Which of these events will be notified if the button is clicked?


a) ActionEvent
b) MouseEvent
c) AdjustmentEvent
d) WindowEvent

12. Which of these events will be notified if the window is hidden ?


a) ActionEvent
b) MouseEvent
c) AdjustmentEvent
d) WindowEvent

13. Which of these events will be notified if the key is released .


a) ActionEvent
b) MouseEvent
c) AdjustmentEvent
d) KeyEvent

14. Which of these events are present in javafx.


a) ActionEvent
b) MouseEvent
c) DragEvent
d) All

14. Which method is called by launch().


a) start()
b) paint()
c) scene()
d) None

You might also like