Oops Course Material r23
Oops Course Material r23
UNIT-1
TEN MARKS QUESTIONS:
4. Explain the working principle of java virtual machine (JVM) and how you can say 2
that java is architectural neutral.
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.
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.
String s1=s2+s3;
- Subtraction 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
● 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
● Logical Operators:
This is used to construct compound conditions.
Operator Operation Example
● Boolean operators:
These operators act on Boolean variables and produce Boolean type result.
● Bitwise operators:
These operators act on individual bits of a number and produce the appropriate result.
Operators Operation Example x=10, y=11
& (Bitwise and Gives 1 if both bits are 1. Otherwise false System.out.print(x&y);//returns
Operator ) returns 00001010
<<(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
● 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.
2nd ++ , --
3rd *, /, %
4th +, -
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.
● 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.
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:
● 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:
4. Explain the working principle of java virtual machine (JVM) and how you can say that java
is architectural neutral.
● 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
// Switch expression
switch (numb) {
// Case statements
case 10:
System.out.println("TEN");
case 30:
System.out.println("THIRTY");
break;
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 {
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.
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++){
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{
float marks;
marks=sc.nextFloat();
System.out.println("A Grade");
System.out.println("B Grade");
System.out.println("C Grade");
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 conversion takes place when two data types are automatically converted. This happens when:
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;
Output:
Int value 100
Long value 100
Float value 100.0
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.
char ch = 'c';
int num = 88
ch = num;
Error:
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:
While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).
Example:
class Test
//d%256
b = (byte) d;
System.out.println("d = " + d + " b= " + b);
}
Output:
i = 257 b = 1
d = 323.142 b = 67
A) Source Code:
import java.io.*;
import java.util.Scanner;
class Arithmatic{
float a,b;
int ch=0;
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){
ch=sc.nextInt();
if(ch==1){
a=sc.nextInt();
b=sc.nextInt();
System.out.println("sum = "+(a+b));
if(ch==2){
a=sc.nextInt();
b=sc.nextInt();
System.out.println("difference = "+(a-b));
}
if(ch==3){
a=sc.nextInt();
b=sc.nextInt();
System.out.println("product = "+(a*b));
if(ch==4){
a=sc.nextInt();
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
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;
2.What is byte code? Explain why java is called as true object oriented language.
3. List primitive data types along with their memory requirements in Java.
Logical type -
4. What is string? List two string handling functions with their use.
1. int length()
Example:
System.out.println(str.length());
2. charAt(int where )
Example:
char ch;
ch = "abc".charAt(1);
Example:
System.out.println(buf);
4. String toString()
Example:
System.out.println(str.toString());
5. byte[ ] getBytes( )
6. char[ ] toCharArray( )
Use: convert all the characters in a String object into a character array.
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";
s1.equals(s3));
s1.equals(s4));
s1.equalsIgnoreCase(s4));
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);
Output:
Result = 626.7784146484375
7. What is encapsulation.
System.out.println("--Before swap--");
first = second;
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
BIT BANK
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM
a) Object-oriented
b) Use of pointers
c) Portable
b) identifier
c) keyword
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
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
a) .txt
b) .js
c) .class
d) .java
Ans;8
UNIT-2
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);
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;
}
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);
}
}
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
}
The class named Outer has one instance variable named outer_x, one instance method named test( ),
and defines one inner class called Inner.
7. Ravi does not want to share his mail id . Which type of programming construct will you
prefer . Explain.
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);
}
}
import java.io.*;
import java.util.Scanner;
class Demo1{
public float radius;
Demo1(){}
Demo1(float r){
this.radius=r;
void create(){
void calculate(){
Double area=3.1415*radius*radius;
System.out.println("Area = "+area);
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
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.
Constructors Methods
A constructor can not have any return A method can have a return type.
type.
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.
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 static void main(String args[]){
display();
BIT BANK
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
a. Virtual function
b. const function
c. Static function
d. Friend function
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.
a. student class{ };
b. class student{ student(int a){} };
c. class teacher{ public: teacher(int a){ } };
d. None of the mentioned
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
a) At run time
b) At compile time
c) At coding time
d) At execution time
a) At run time
b) At compile time
c) At coding time
d) At execution time
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
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.
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.
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. 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 {
.....
.....
}
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.
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;
float sub1,sub2,sub3;
return ((sub1+sub2+sub3)/300)*100;
}
}
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:
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
Method Overloading:
class MethodOverloadingEx {
Output
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding:
Example:
import java.io.*;
class Animal {
void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}
class MethodOverridingEx {
d1.eat();
a1.eat();
● 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 {
.....
.....
}
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;
float bonus=3000*6;
{
Executive obj=new Executive();
Output:
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:
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
{
System.out.println("The method of the class Commerce invoked.");
//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
System.out.println("I am grandfather.");
System.out.println("I am father.");
}
//inherits Father properties
System.out.println("I am son.");
System.out.println("I am a 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){
super.calculate(s);
System.out.println("Perimeter Of Square = "+(4*s));
}
}
class Sita{
}
OutPut:
class GFG {
System.out.println();
}
}
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);
final class A{
//code
//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.
Syntax of an interface:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
Creating an interface
Example:
void on();
void off();
void play();
void stop();
interface VideoPlayer{
void on();
void off();
void play();
void stop();
● Whatever the variables we write in the interface, they are by default belongs to:
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.
//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:
}
}
● We can create an interface reference variable. It can refer to any object that implements
the interface.
Extending interfaces
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:
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
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
Class Interface
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 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
It is used to increase the readability of the program Provides a specific implementation of the method
already in the parent class
Parameters must be different in case of overloading Parameters must be same in case of overriding
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
class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
public Tester(){
message = "Hello World!";
}
public Tester(String message){
this.message = message;
}
Output
Hello World!
Welcome
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.
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.
● It cannot be instantiated.
● 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.
● 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.
BIT BANK
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
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
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
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
UNIT-4
1. Rama wants to create an user defined exception to check the voter eligibility. Help 6
rama in it.
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.
1. Define exception. What will be the output if the exception is thrown in a program. 2
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
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 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:
● 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.
● 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.
● 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;
● 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.
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;
● 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.
● 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:
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
Access specifiers make us to understand how to access the data within the package and across the
package
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';
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
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';
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(24);
● 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
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{
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++){
for(i=(i+1);i<amount.length;i++){
}
}
Output :
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.
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:
● 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.
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.");
}
}
}
Output
Exception in thread "main" java.lang.ArithmeticException:
Not Eligible for voting
at JavaTester.checkAge(JavaTester.java:4)
at JavaTester.main(JavaTester.java:10)
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;
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
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.
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.
Methods:
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
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
7. Which of these is used to perform all input & output operations in Java?
a) streams
b) Variables
c) classes
d) Methods
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
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
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
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
4. Discuss about the similarities and differences between javafx and swing 4
applications.
6. Illustrate about different methods for extracting characters from string with an 6
example.
4. Write the import statements to create a text node in javafx and set its colour to blue. 6
8. Define event. 1
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;
@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");
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.
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
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;
@Override
root.addRow(0, first_name,tf1);
root.addRow(1, last_name,tf2);
root.addRow(2, Submit);
primaryStage.setScene(scene);
primaryStage.show();
launch(args);
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.
and feel
Development Swing APIs are being used to JavaFX scripts and fast UI
components
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;
c.setCenterX(135.0f);
c.setCenterY(125.0f);
c.setRadius(25.0f);
primaryStage.setTitle("Key Events");
primaryStage.setScene(scene);
primaryStage.show();
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
switch(event.getCode()){
c.setCenterY(c.getCenterY()-5);
break;
c.setCenterY(c.getCenterY()+5);
break;
c.setCenterY(c.getCenterY());
break;
case RIGHT: c.setCenterX(c.getCenterX()+5);
c.setCenterY(c.getCenterY());
break;
} }
});
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);
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)
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;
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();
Output:
Character array: [H, e, l, l, o]
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())
● 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:
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();
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 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)
else
System.out.println("insertion failed");
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
○ 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.
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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
going to withdraw...
going to deposit...
deposit completed...
withdraw completed
The diagram shown below represents various states of a thread at any instant in time.
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.
1. 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.
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().
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following
methods:
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
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
● 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 −
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
There are several methods in the ResultSet interface that involve moving the cursor, including −
● 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.
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
ActionEvent()
Creates a new ActionEvent with an event type of ACTION.
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.
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)
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.
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