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

II B.Sc IV SEM JAVA

The document outlines the syllabus for a second-year B.Sc course on Object-Oriented Programming using Java, covering various units including Java basics, OOP principles, exception handling, multithreading, applets, and JDBC. It details the features of Java, its architecture, naming conventions, data types, and provides examples of Java programs. The content is structured into units that progressively build on Java programming concepts and applications.

Uploaded by

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

II B.Sc IV SEM JAVA

The document outlines the syllabus for a second-year B.Sc course on Object-Oriented Programming using Java, covering various units including Java basics, OOP principles, exception handling, multithreading, applets, and JDBC. It details the features of Java, its architecture, naming conventions, data types, and provides examples of Java programs. The content is structured into units that progressively build on Java programming concepts and applications.

Uploaded by

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

II B.Sc(M.S.C.S/M.P.C.

S)

II YEAR B.SC IV SEM

OBJECT ORIENTED PROGRAMMING USING JAVA

UNIT-I

Introduction to Java: Features of Java, The Java virtual Machine, Parts of


Java. NamingConventions and Data Types: Naming Conventions in Java,
Data Types in Java, Literals,Type Casting. Operators in Java: Operators,
Priority of Operators. Control Statements inJava: if... else Statement, do...
while Statement, while Loop, for Loop, switch Statement,break Statement,
continue Statement, return Statement. Input and Output: Accepting
Inputfrom the Keyboard, Reading Inputwith Java.util.Scanner Class,
Displaying OutputwithSystem.out.printf(), Displaying Formatted Output
with String.format(). Arrays: Types
ofArrays,ThreeDimensionalArrays(3Darray),arrayname.length,CommandLi
neArguments.
UNIT-II
Strings: Creating Strings, String Class Methods, String Comparison,
Immutability of Strings.Introduction to OOPs:Problemsin Procedure
Oriented Approach,Features of Object-Oriented Programming System
(OOPS). Classes and Objects: Object Creation, Initializingthe Instance
Variables, Access Specifiers, Constructors. Methods in Java: Method
Headeror Method Prototype, Method Body, Understanding Methods, Static
Methods, Static Block,The keyword ‘this’, Instance Methods, Passing
Primitive Data Types to Methods,
PassingObjectstoMethods,PassingArraystoMethods,Recursion,FactoryMeth
ods.Inheritance:Inheritance,Thekeyword‘super’,TheProtectedSpecifier,Typ
esofInheritance.
UNIT–III
Polymorphism:Polymorphism with Variables,Polymorphism using
Methods,Polymorphism with Static Methods, Polymorphism with Private
Methods, Polymorphismwith Final Methods, final Class. Abstract Classes:
Abstract Method and Abstract Class.Interfaces: Interface, Multiple
Inheritance using Interfaces. Packages: Package, DifferentTypes of
Packages, The JAR Files, Interfaces in a Package, Creating Sub Package in
aPackage, Access Specifiers in Java, Creating API Document Exception
Handling: Errors inJava Program, Exceptions, throws Clause, throw Clause,
Types of Exceptions, Re – throwinganException
UNIT–IV
Threads: Single Tasking, Multi Tasking, Uses of Threads, Creating a Thread
and Running it,Terminating the Thread, Single Tasking Using a Thread,
Multi Tasking Using Threads,Multiple Threads Actingon
SingleObject,Thread Class Methods,Deadlock ofThreads,
Thread Communication, Thread Priorities, thread Group, Daemon Threads,
Applications ofThreads,ThreadLifeCycle
UNIT–V
Applets: Creating an Applet, Uses of Applets, <APPLET> tag, A Simple
Applet, An Applet with Swing Components, Animation in Applets, A Simple
Game with an Applet, AppletParameters

JAGAN’S DEGREE COLLEGE Page 1


II B.Sc(M.S.C.S/M.P.C.S)

Java Database Connectivity: Database Servers, Database Clients, JDBC


(Java DatabaseConnectivity),Working with Oracle Database,Registering the
Driver,Connecting to a Database, Preparing SQL Statements, Using jdbc–
odbc Bridge Driver to Connect to Oracle Database,Stored Procedures and
Callable Statements,Types of Result Sets

UNIT-I

INTRODUCTION TO JAVA

1. Introduction to JAVA:-
Java is a programming language created by James Gosling from Sun
Microsystems (Sun) in 1991. The target of Java is to write a program once and then run this
program on multiple operating systems. The first publicly available version of Java (Java 1.0)
was released in 1995.

Java is used for:

• Mobile applications (specially Android apps)


• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection

2. Features of JAVA:-

The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. The features of Java are also known as java
buzzwords.
1. Java is a platform independent language
Compiler (javac) converts source code (.java file) to the byte code (.class file). As mentioned
above, JVM executes the byte code produced by compiler. This byte code can run on any
platform such as Windows, Linux, and Mac OS etc. This means a program that is compiled on
windows can run on Linux and vice-versa.
Each operating system has different JVM; however the output they produce after execution of
byte code is same across all operating systems. That is why we call java as platform
independent language.
2. Java is an Object Oriented language
Object oriented programming is a way of organizing programs as collection of objects, each of
which represents an instance of a class.
4 main concepts of Object Oriented programming are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
3. Simple
Java is considered as one of simple language because it does not have complex features like
Operator overloading, multiple inheritance, pointers and explicit memory allocation.

JAGAN’S DEGREE COLLEGE Page 2


II B.Sc(M.S.C.S/M.P.C.S)

4. Robust Language
Robust means reliable. Java programming language is developed in a way that puts a lot of
emphasis on early checking for possible errors, that’s why java compiler is able to detect errors
that are not easy to detect in other programming languages.

5. Secure
We don’t have pointers and we cannot access out of bound arrays in java. That’s why several
security flaws like stack corruption or buffer overflow is impossible to exploit in Java.
6. Java is distributed
The java programs can be distributed on more than one system that is connected to each other
using internet connection. Objects on one JVM (java virtual machine) can execute procedures
on a remote JVM.
7. Multithreading
Java supports multithreading. Multithreading is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilization of CPU.
8. Portable
As discussed above, java code that is written on one machine can run on another machine. The
platform independent byte code can be carried to any platform for execution that makes java
code portable.

3. Java Virtual Machine (JVM) & its Architecture:-


Java Virtual Machine (JVM) is an engine that provides runtime environment to drive the
Java Code or applications. It converts Java byte code into machines language. JVM is a part of
Java Run Environment (JRE). In other programming languages, the compiler produces
machine code for a particular system. However, Java compiler produces code for a Virtual
Machine known as Java Virtual Machine. Java applications are called WORA (Write Once
Run Anywhere).
Here is how JVM works
First, Java code is complied into byte code. This byte code gets interpreted on different
machines
Between host system and Java source, Byte code is an intermediary language.
JVM is responsible for allocating memory space.

JVM Architecture: - JVM contains class loader, memory area, execution engine etc. the
following diagram illustrates the JVM Architecture.

JAGAN’S DEGREE COLLEGE Page 3


II B.Sc(M.S.C.S/M.P.C.S)

1) Class Loader
The class loader is a subsystem used for loading class files. It performs three major functions
viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the code
for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the heap. This memory
is common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created. A new frame is created whenever a
method is invoked, and it is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently
executing. In Java, each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native library. It is
written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution
engine never carries any information about the tested product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code which is
running in a JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the
Execution Engine.

4. Basic Structure of Java Program(or) parts of Java:-


Every programming language follows certain program structure which is followed
by the by the programmer.

JAGAN’S DEGREE COLLEGE Page 4


II B.Sc(M.S.C.S/M.P.C.S)

• Documentation Section:-
We can write a comment in this section. Comments are beneficial for the programmer
because they help them understand the code. These are optional, but because they are
useful to understand the operation of the program, so we must write comments within
the program.

• Package Statement Section: -


We can create a package with any name. A package is a group of classes that
are defined by a name. That is, if we want to declare many classes within one element,
then you can declare it within a package. It is an optional part of the program.
It is declared as:-
package package_name;
• Import Statement section:-
This line indicates that if we want to use a class of another package, then you can do
this by importing it directly into our program.
Example:
import calc.add;
• Interface statement section:-
Interfaces are like a class that includes a group of method declarations. It's an optional
section and can be used when programmers want to implement multiple inheritances
within a program.
Syntax: - interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

• Class dentition:-
A Java program may contain several class definitions. Classes are the main and
essential elements of any Java program.
• Main Method Class:-
Every Java stand-alone program requires the main method as the starting point of the
program. This is an essential part of a Java program. There may be many classes in a
Java program, and only one class defines the main method. Methods contain data type
declaration and executable statements.

JAGAN’S DEGREE COLLEGE Page 5


II B.Sc(M.S.C.S/M.P.C.S)

Ex: A Simple Java Program to Print "Hello Java":-


class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

5. Naming conventions in java:


Since Java is a case sensitive programming language, it recognizes capital and small
letters as different. So the programmer should take care of upper and lower case while writing
a program in java. But how to know where to use which case either upper or lower. For this
purpose certain conventions are followed by java soft people while naming the variables,
classes and methods etc.
These naming conventions should be followed by every programmer in his programs
for maintaining uniformity and also for clarity of distinction between different elements of a
program. These rules also reduce the possibility of any spelling mistakes while writing the
names of variables, classes etc in the programs.

❖ package:
➢ A package represents a subdirectory that contains a group of classes and
interfaces
➢ Names of packages in java are written in small letters as
➢ Eg: java.awt
javax.swing
❖ class or interface:
➢ A class is a model for creating objects. A Class specifies the properties and
actions of objects
➢ An interface is also similar to a class.
➢ Each word of class names and interface names start with a capital letter
➢ Eg: String
DataInputStream
ActionListener
❖ Methods:
➢ A class and an interface contain methods and variables
➢ The first word of a method name is in small letter then from second word
onwards each new word starts with a capital letter
➢ Eg: println()
readLine()
getNumberInstance()
❖ Variables:
➢ The naming convention for variable names is same as that for methods.
➢ The first word of a variable name is in small letter then from second
word onwards each new word starts with a capital letter
➢ Eg: age
empName
employee_Net_Sal
❖ constants:

JAGAN’S DEGREE COLLEGE Page 6


II B.Sc(M.S.C.S/M.P.C.S)

➢ constants represents fixed values that cannot be altered.for eg, PI is


a constant whose value is 22/7or 3.14159, which is fixed
➢ such constants should be written by using all capital letters

➢ Eg: PI
MAX_VALUE
FONT_BOLD
❖ Keyword:
➢ All keywords should be written by using all small letters as follows:
➢ Eg: public
void
static

6. Data Types in Java:


Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

❖ Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.
There are 8 types of primitive data types:

• boolean data type


• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type

JAGAN’S DEGREE COLLEGE Page 7


II B.Sc(M.S.C.S/M.P.C.S)

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes
1. Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions. The Boolean data type
specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false

2. Byte Data Type


Its minimum value is -128 and maximum value is 127. Its default value is 0. The byte
data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of
"int" data type.
Example: byte a = 10, byte b = -20

3. Short Data Type


Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0. The short data type can also be
used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.
Example: short s = 10000, short r = -5000

4. Int Data Type


Its value-range lies between - 2,147,483,648 to 2,147,483,647 . Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
Example: int a = 100000, int b = -200000

5. Long Data Type


Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default
value is 0. The long data type is used when you need a range of values more than those provided
by int.
Example: long a = 100000L, long b = -200000L

6. Float Data Type


The float data type is a single-precision 32-bit floating point.Its value
range is unlimited. It is recommended to use a float (instead of double) if you need to save

JAGAN’S DEGREE COLLEGE Page 8


II B.Sc(M.S.C.S/M.P.C.S)

memory in large arrays of floating point numbers. The float data type should never be used for
precise values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f

7. Double Data Type


The double data type is a double-precision 64-bit floating
point. Its value range is unlimited. The double data type is generally used for decimal values
just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example: double d1 = 12.3

8. Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.
Example: char letter A = 'A'

7. Java Literals:
Literal: Any constant value which can be assigned to the variable is called
literal/constant.
In simple words, Literals in Java is a synthetic representation of boolean,
numeric, character, or string data. It is a medium of expressing particular values in the
program, such as an integer variable named ‘’/count is assigned an integer value in the
following statement.
/ / Here 100 is a constant/literal.
int x = 100;
❖ Integral literals:
For Integral data types (byte, short, int, long), we can specify literals in 4 ways:-
• Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
• Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
• Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9, and
characters are a-f. We can use both uppercase and lowercase characters as we know
that java is a case-sensitive programming language, but here java is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
• Binary literals: From 1.7 onward, we can specify literal value even in binary form
also, allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
int x = 0b1111;
Example:

• Java

JAGAN’S DEGREE COLLEGE Page 9


II B.Sc(M.S.C.S/M.P.C.S)

// Java program to illustrate the


// application of Integer literals

publicclassTest {
publicstaticvoidmain(String[] args)
{
// decimal-form literal
inta = 101;
// octal-form literal
intb = 0100;
// Hexa-decimal form literal
intc = 0xFace;
// Binary literal
intd = 0b1111;

System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}

Output
101
64
64206
15

❖ Floating-Point literal:
For Floating-point data types, we can specify literals in only decimal form, and we cant
specify in octal and Hexadecimal forms.
• Decimal literals(Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;
• Java

// Java program to illustrate the


// application of floating-point literals

publicclassTest {
publicstaticvoidmain(String[] args)
{
// decimal-form literal
floata = 101.230;
// It also acts as decimal literal
floatb = 0123.222;
// Hexa-decimal form (error)
floatc = 0x123.222;

JAGAN’S DEGREE COLLEGE Page 10


II B.Sc(M.S.C.S/M.P.C.S)

System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}

Output
101.230
123.222
Error: malformed floating point literal

❖ Char literals:
For char data types, we can specify literals in 4 ways:
• Single quote: We can specify literal to a char data type as a single character within
the single quote.
char ch = 'a';
• Char literal as Integral literal: we can specify char literal as integral literal, which
represents the Unicode value of the character, and that integral literal can be specified
either in Decimal, Octal, and Hexadecimal forms. But the allowed range is 0 to 65535.
char ch = 062;
• Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';
Example:
• Java

// Java program to illustrate the


// application of char literals

publicclassTest {
publicstaticvoidmain(String[] args)
{
// single character literl within single quote
charch = 'a';
// It is an Integer literal with octal form
charb = 0789;
// Unicode representation
charc = '\u0061';

System.out.println(ch);
System.out.println(b);
System.out.println(c);

// Escape character literal


System.out.println("\" is a symbol");
}
}

Output
a

JAGAN’S DEGREE COLLEGE Page 11


II B.Sc(M.S.C.S/M.P.C.S)

error:Integer number too large


a
" is a symbol

❖ String literals:
Any sequence of characters within double quotes is treated as String literals.
String s = "Hello";
String literals may not contain unescaped newline or linefeed characters. However, the Java
compiler will evaluate compile-time expressions, so the following String expression results
in a string with three lines of text:
Example:
String text = "This is a String literal\n"
+ "which spans not one and not two\n"
+ "but three lines of text.\n";
• Java

// Java program to illustrate the


// application of String literals

publicclassTest {
publicstaticvoidmain(String[] args)
{
String s = "Hello";

// If we assign without "" then it treats


// as a variable and causes compiler error
String s1 = Hello;

System.out.println(s);
System.out.println(s1);
}
}

Output
Hello
error: cannot find symbol
symbol: variable Hello
location: class Test

8. Type Casting in java:

In Java, type casting is a method or process that converts a data type into another
data type in both ways manually and automatically. The automatic conversion is done by the
compiler and manual conversion performed by the programmer. Type casting is when you
assign a value of one primitive data type to another type.

In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type size


byte ->short ->char ->int ->long ->float ->double

JAGAN’S DEGREE COLLEGE Page 12


II B.Sc(M.S.C.S/M.P.C.S)

• Narrowing Casting (manually) - converting a larger type to a smaller size type


double ->float ->long ->int ->char ->short ->byte

❖ Widening Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. Widening casting is done automatically when passing a smaller size type
to a larger size type: It takes place when:

• Both data types must be compatible with each other.


• The target type must be larger than the source type.
Example:
For example, the conversion between numeric data type to char or Boolean is
not done automatically. Also, the char and Boolean data types are not compatible with
each other. Let's see an example.
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
❖ Narrowing Casting
Converting a higher data type into a lower one is called narrowing type casting.
It is also known as explicit conversion or casting up. It is done manually by the programmer.
If we do not perform casting then the compiler reports a compile-time error. Narrowing casting
must be done manually by placing the type in parentheses in front of the value:

Example
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into
int type.

NarrowingTypeCastingExample.java

public class NarrowingTypeCastingExample


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

JAGAN’S DEGREE COLLEGE Page 13


II B.Sc(M.S.C.S/M.P.C.S)

double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

9. Operators in JAVA:
An operator is a symbol that performs an operation. If an operator acts on a single variable,
then it is called as unary operator. If an operator acts on two variables then it is called binary
operator. If an operator acts on three variables then it is called ternary operator. The following
are the operators available in Java
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators

1. Arithmetic operator:
Arithmetic operators are used to perform arithmetic calculations. The
following are the Arithmetic operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division

2. Relational operators:
Relational operators are used to compare two values and to give either true or
false. These are used to form simple conditions. All the relational operators are applied on any
type of data. The following are the relational operators.
Operator Meaning
< Less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

JAGAN’S DEGREE COLLEGE Page 14


II B.Sc(M.S.C.S/M.P.C.S)

3. Logical operators:
These operators are used to combine two or more conditions and give the result either
true or false. These conditions are called compound conditions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

➢ Logical AND (&&) Operator:


This operator gives true if all the conditions are true otherwise it gives false. The truth
table for && operator is as follows
Condition 1 Condition 2 Condition 1 &&Condition 2
True True True
True False False
False True False
False False False
➢ Logical OR (||) Operator:
This operator gives false if all conditions are false otherwise it gives true. The truth table for
|| operator is as follows:
Condition 1 Condition 2 Condition 1 ||condition 2
True True True
True False True
False True True
False False False
➢ Logical not (!) operator:
This operator negates (opposite) the result of a condition. It means if the condition is true
then it gives false. If the condition is false then it returns true.
The truth table for (!) Operator is as follows :
conditon !(condition)
True False
False True
Eg: Let a=15, b=20 then
Expression Result
a==15||b==20 True
a>15&&b>=20 False
a<=15&&b<=20 True
!(a==15) False
4. Assignment Operators:
The Assignment operators are used to assign a value to a variable. An assignment
operator always consists of a variable on left hand side and expression constant/variable on
right hand side. There is two types of assignment operators. They are:
1. Simple assignment operator
2. Compound assignment operator
1.Simple assignment operator:
The equal sign “=“is used as simple assignment operator. The general format of this
operator is as follows:
Variable= {Expression or Constant};

JAGAN’S DEGREE COLLEGE Page 15


II B.Sc(M.S.C.S/M.P.C.S)

In the above syntax the value of Expression/constant/variable is assigned to the


variable on the left hand side of ‘=’sign.
Eg: x=35; y=a+b*c; z=y;
a=b=50;
2. Compound assignment operator:
The general form of compound assignment operator is as follows:
Variable compound operator={Expression or constant};
In the above syntax the operator can be either +=, -=,*=,/= ,(or) %=
Operator Example Meaning
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
5. Increment and Decrement operator:
❖ Increment operator(++):
➢ Pre increment:
If the ‘++’ operator preceeds the operand then it is called “pre increment.” In this
method the pre increment operator increments the value of variable fist and then the new value
is used in the expression.
Eg:c=++a; means a=a+1;
c=a;
➢ Post increment:
If the ‘++’ operator succeeds the operand then it is called “pre increment.” In this method the
old value of the variable is used in expression and then it is incremented.
Eg:c=a++; means c=a;
a=a+1;
❖ Decrement operator:
The decrement operator is a unary operator. It is used to decrease the value of an operand by
1. The operand must be a variable. The decrement operator “-“ has different meaning
depending on the position it is used. It means this operator is used in two ways. They are
➢ Pre decrement:
If the ‘--‘operator precedes the operand then it is called “pre decrement.” In this method the
pre decrement operator decrements the value of variable first and then the new value is used in
the expression.
Eg: c=--a; means a=a-1;
C=a;
➢ Post decrement:
If the ‘--‘ operator succeeds the operand then it is called post decrement. In this method the old
value of the variable is used in expression and then it is decremented.
Eg: c=a--; means c=a; a=a-1;
Initial values Expression Final values
A B A B
3 7 a=++b 8 8
3 7 a=b++ 7 8
3 7 a=--b 6 6
3 7 a=b-- 7 6

6. Conditional operator:

JAGAN’S DEGREE COLLEGE Page 16


II B.Sc(M.S.C.S/M.P.C.S)

This operator performs the condition based on execution. This operator operates on three
operands. Hence it is also known as ternary operator. This operator simplifies the “if…else”
control statement. The general form of conditional operator is as follows:
Syntax:
Var=(condition)? Statement 1:statement 2
In above syntax, if the condition is true statement 1 is executed and
evaluated first. If it is false, statement 2 is executed.
Ex: x=( a > b) ? a : b;

10: Priority of Operators:


Java has well-defined rules for evaluating expressions, including operator
precedence, operator associativity, and order of operand evaluation. We describe each of
these three rules.
❖ Operator precedence:
Operator precedence specifies the manner in which operands are grouped with operators. For
example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 because
the multiplication operator has a higher precedence than the addition operator. You can use
parentheses to override the default operator precedence rules.
❖ Operator associativity:
When an expression has two operators with the same precedence, the operators and operands
are grouped according to their associativity. For example 72 / 2 / 3 is treated as (72 / 2) / 3 since
the division operator is left-to-right associate. You can use parentheses to override the default
operator associativity rules.
Most Java operators are left-to-right associative. One notable exception is the assigment
operator, which is right-to-left associative. As a result, the expression x = y = z = 17 is treated
as x = (y = (z = 17)), leaving all three variables with the value 17. Recall that an assignment
statement evaluates to the value of its right-hand side. Associativity it not relevant for some
operators. For example, x <= y <= z and x++-- are invalid expressions in Java.

Precedence and associativity of the operators:

Operators Associativity Type


* / % Left to right multiplicative
+ - Left to right Additive
<<= >>= Left to right Relational
== != Left to right equality

class OperatorPrecedence {
public static void main (String[] args) {
int result = 0;
result = 5 + 2 * 3 - 1;
System.out.println("5 + 2 * 3 - 1 = " +result);

result = 5 + 4 / 2 + 6;
System.out.println("5 + 4 / 2 + 6 = " +result);

result = 3 + 6 / 2 * 3 - 1 + 2;
System.out.println("3 + 6 / 2 * 3 - 1 + 2 = " +result);

JAGAN’S DEGREE COLLEGE Page 17


II B.Sc(M.S.C.S/M.P.C.S)

result = 6 / 2 * 3 * 2 / 3;
System.out.println("6 / 2 * 3 * 2 / 3 = " +result);

}
}

Output:
5 + 2 * 3 - 1 = 10
5 + 4 / 2 + 6 = 13
3 + 6 / 2 * 3 - 1 + 2 = 13
6/2*3*2/3= 6

11. Control statements in JAVA:


A control statement works as a determiner for deciding the next task of the
other statements whether to execute or not. An ‘If’ statement decides whether to execute a
statement or which statement has to execute first between the two. In Java, the control
statements are divided into three categories which are selection statements, iteration
statements, and jump statements. A program can execute from top to bottom but if we use a
control statement. We can set order for executing a program based on values and logic.

• Decision Making in Java


o Simple if Statement
o if…else Statement
o Nested if statement
o if...else if…else statement
o Switch statement
• Looping Statements in Java
o While
o Do…while
o For
• Branching Statements in Java
o Break
o Continue
o return

1. Decision Making Statements in Java


Decision making statements are statements which decides what to execute and
when. They are similar to decision making in real time. Control flow statements control the
flow of a program’s execution. Here flow of execution will be based on state of a program. We
have 4 decision making statements available in Java.

• Simple if Statement:
Simple if statement is the basic of decision-making statements in Java. It decides if
certain amount of code should be executed based on the condition.
Syntax:
if (condition) {
Statement 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false
JAGAN’S DEGREE COLLEGE Page 18
II B.Sc(M.S.C.S/M.P.C.S)

Example:
classifTest
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}

Output:
After if statement

• if…else Statement
In if…else statement, if condition is true then statements in if block will be executed but if
it comes out as false then else block will be executed.
Syntax:
if (condition) {
Statement 1; //if condition becomes true then this will be executed
}
else{
Statement 2;
}
Example:
class ifelseTest
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}
Output:
i is less than 10
After if else statement

• Nested if statement:
Nested if statement is if inside an if block. It is same as normal if…else statement but
they are written inside another if…else statement.

Syntax:
if (condition1) {
Statement 1; //executed when condition1 is true

JAGAN’S DEGREE COLLEGE Page 19


II B.Sc(M.S.C.S/M.P.C.S)

if (condition2) {
Statement 2; //executed when condition2 is true
}
else {
Statement 3; //executed when condition2 is false
}
}

Example:
class nestedifTest
{
public static void main(String args[])
{
int x = 25;

if (x > 10)
{
if (x%2==0)
System.out.println("i is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else
{
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
}
}
Output:
i is greater than 10 and odd number
After nested if statement

• Switch statement:
Java switch statement compares the value and executes one of the case blocks based on the
condition. It is same as if…else if ladder.

Let us understand it through one example.


class switchDemo{
public static void main(String args[]){
int i=2;
switch(i){
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");

JAGAN’S DEGREE COLLEGE Page 20


II B.Sc(M.S.C.S/M.P.C.S)

break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}

2.Looping Statements in Java


Looping statements are the statements which executes a block of code repeatedly until some
condition me et to the criteria. Loops can be considered as repeating if statements. There are 3
types of loops available in Java.

• While Loop:-
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true
then executes the body of loop. This is repeated until the condition becomes false. Condition
in while loop must be given as a Boolean expression. If int or string is used instead, compile
will give the error.
Syntax:
while (condition)
{
statement1;
}
Example:
class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Output:
1
3
5
7
9

JAGAN’S DEGREE COLLEGE Page 21


II B.Sc(M.S.C.S/M.P.C.S)

• Do…while:
Do…while works same as while loop. It has only one difference that in do…while, condition
is checked after the execution of the loop body. That is why this loop is considered as exit
control loop. In do…while loop, body of loop will be executed at least once before checking
the condition
Syntax:
do{
statement1;
}while(condition);

Example:
class dowhileLoopTest
{
public static void main(String args[])
{
int j = 10;

do
{
System.out.println(j);
j = j+1;
} while (j <= 10)
}
}
Output:
10

• For loop:-
It is the most common and widely used loop in Java. It is the easiest way to construct
a loop structure in code as initialization of a variable; a condition and increment/decrement are
declared only in a single line of code. It is easy to debug structure in Java.
Syntax:
for (initialization; condition; increment/decrement)
{
statement;
}
Example:
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:
1
2
3
4

JAGAN’S DEGREE COLLEGE Page 22


II B.Sc(M.S.C.S/M.P.C.S)

3. Branching Statements in Java


Branching statements jump from one statement to another and transfer the execution flow.
There are 3 branching statements in Java.

• Break statement:-
Break statement is used to terminate the execution and bypass the remaining code in loop. It is
mostly used in loop to stop the execution and comes out of loop. When there are nested loops
then break will terminate the innermost loop.
Example:
class breakTest
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4.
if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}
Output:
0
1
2
3
4
After loop

• Continue statement:
Continue statement works same as break but the difference is it only comes out
of loop for that iteration and continue to execute the code for next iterations. So it only bypasses
the current iteration.
Example:
class continueTest
{
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue; // only even numbers will be printed
System.out.print(j + " ");
}
}

JAGAN’S DEGREE COLLEGE Page 23


II B.Sc(M.S.C.S/M.P.C.S)

}
Output:
02468

❖ Return statement:

In Java programming, the return statement is used for returning a value


when the execution of the block is completed. The return statement inside a loop will
cause the loop to break and further statements will be ignored by the compiler.

• Returning a Value from a Method:


In Java, every method is declared with a return type such as int, float, double,
string, etc.These return types required a return statement at the end of the
method. A return keyword is used for returning the resulted value.
Ex: class Return1
{

int display()
{
return 10;
}
public static void main(String[] args)
{
Return1 e =new Return1();
System.out.println(e.display());
}

}
Output:
10

12. Input and Output in Java:


Javabrings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all the types of objects, data-types, characters, files
etc to fully execute the I/O operations.

Before exploring various input and output streams let’s look at 3 standard or
default streams that Java has to provide which are also most common in use:

JAGAN’S DEGREE COLLEGE Page 24


II B.Sc(M.S.C.S/M.P.C.S)

1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
print():This method in Java is used to display a text on the console. This text is passed as
the parameter to this method in the form of String. This method prints the text on the console
and the cursor remains at the end of the text at the console. The next printing takes place from
just here.
Syntax: System.out.print(parameter);

println(): This method in Java is also used to display a text on the console. It prints the
text on the console and the cursor moves to the start of the next line at the console. The next
printing takes place from the next line.
Syntax: System.out.println(parameter);

3.System. Err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:
• print()
• println()
• printf()

Types of Streams:
Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input from a
source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.

JAGAN’S DEGREE COLLEGE Page 25


II B.Sc(M.S.C.S/M.P.C.S)

2. Output Stream: These streams are used to write data as outputs into an array or file or any
output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.

• To accept data from the keyboard i.e. system.in, we need to connect it to an


InputStreamReader object
1.InputStreamReader obj=newInputStreamReader(System.in)
Connect InputStreamReader to buffer reader which is another input type of stream to read data
properly coming from the stream
BufferedReader br=new BufferedReader(obj);
Here obj is an InputStreamReader object the above two steps can be combined and rewritten
in a single statement as
BufferedReader br=newBufferedReader(new InputStreamReader(system.in));
Now we can read the data coming from keyboard using read() and readLine() method available
in BufferedReader class.

• Accepting a single character from keyboard:


Now follow these steps inorder to accept a single character from the keyboard
Create a BufferedReader class object (br) then read a single charcter from the keyboard using
read() method as
char ch=br.read();
Here the read() method reads a single character from the keyboard but it
returns its ASCII number which is an integer number can’t be stored into character type
variable ch, we should convert it into char type by writing (char) before the method as:
char ch =(char) br.read();

JAGAN’S DEGREE COLLEGE Page 26


II B.Sc(M.S.C.S/M.P.C.S)

ex: import java.io.*;


class Accept
{
public static void main(String args[ ]) throws IOException
{
//create BufferedReader object to accept data from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
//ask for char and read it
System.out.print(“Enter a character:”);
char ch=(char)br.read();
//display the character
System.out.println(“you entered:”+ch);
}
Output:
Enter a character:R
You entered=R

• Accepting a string from the keyboard:


Now follow these steps in order to accept a string from the keyboard. Create a
BufferedReader class object(br) then read a string from the keyboard using readLine() method
as
String str=br.readLine();
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//ask for string and read it
System.out.print(“Enter a name:”);
String name=br.readLine();
//display the string
System.out.println(“you entered”+name)
}
Output:
Enter a name =Venkatesh
You entered=Venkatesh

• Accepting an integer value from the keyboard:


Now let us follow these steps to accept an integer from the keyboard First we should accept
the integer number from the keyboard as string using readLine () method as
String str=br.readLine();

JAGAN’S DEGREE COLLEGE Page 27


II B.Sc(M.S.C.S/M.P.C.S)

Now the number is in str in the form of a String. This should be converted into an int by using
parseInt() Method of integer class as:
int n=Integer.ParseInt(str);
The above two statements are combined and written as
int n=Integer.ParseInt(br.readLine());
Accepting a float value from the keyboard:
Just like an integer value we can also accept a float value in the following way
float n=Float.ParseFloat(br.readLine());
Accepting a double value from the keyboard:
We can accept a double value from the keyboard with the help of the following statement
double n=Double.ParseDouble(br.readLine());
Similarly we can write different statements to accept many other datatypes from the keyboard
as follows:
To accept a byte value: - byte n=Byte.ParseByte(br.readLine ());
To accept a short value: - short n=short.Parseshort(br.readLine());
To accept a long value: - long n=Long.Parselong(br.readLine());
//accepting a different datatytpes of numbers from keyboard
Import java.io.*;
class Accept
{
public static void main(String args[]) throws IOException
//create BufferedReader object to accept data from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Reading different types of numbers
System.out.print(“Enter an int value:”);
int a=Integer.ParseInt(br.readLine());
Sysytem.out.println(“Enter a float value:”);
float b=Float.ParseFloat(br.readLine());
//display the data
System.out.println(“you entered integer is:”+a);
System.out.println(“you entered float is:”+b);
}
}
Output:
Enter an int value:768
You entered integer is:768
Enter a float value:7.8
You entered float value is:7.8

• Reading input with java.util.Scanner class:


We can use scanner class of java util package to read input from the keyboard or
text file when the scanner class receives input it breaks the input the input into several pieces
called tokens these tokens can be retrieved from the scanner object using the following methods
Next(): to read a string

JAGAN’S DEGREE COLLEGE Page 28


II B.Sc(M.S.C.S/M.P.C.S)

NextByte():to read a byte value


nextInt():to read an ineger value
nextFloat():to read a float value
nextLong():to read a long value
nextDouble():to read a double value
To read input from keyboard we can use scanner class as:
Scanner sc=new Scanner(System.in);
//scanner to scan the input from keyboard
import java.util.Scanner;
class Ex3
{
public static void main(String args[])
{
System.out.print(“Enter id name sal:”);
Scanner S=new Scanner(System.in);
Int id=sc.nextInt();
string name=sc.next();
float sal=sc.nextFloat();
System.out.println(“id=”+id);
System.out.println(“name=”+name);
System.out.println(“sal=”+sal);
}}
Output:
Enter id name sa=: 100 Venkatesh 10000.50
Id=100
Name=venkatesh
Sal=10000.50

13. Arrays in java:


An array is a group of like-typed variables that are referred to by a common name.Arrays in
Java work differently than they do in C/C++. Following are some important point about Java
arrays.
• In Java all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
Array can contain primitives data types as well as objects of a class depending on the definition
of array. In case of primitive’s data types, the actual values are stored in contiguous memory
locations.

JAGAN’S DEGREE COLLEGE Page 29


II B.Sc(M.S.C.S/M.P.C.S)

Creating, Initializing, and Accessing an Array


Arrays are classified into three types:
1. One Dimensional arrays
2. Two Dimensional arrays

1. One Dimensional array:


A variable name having list of items using only one subscript is called One
Dimensional arrays. Arrays must be declared and created in the computer memory before they
are used. Creation of an array involves three types
a) Declaring an array
b) Creating memory location
c) Putting values into the memory locations/Initialization of arrays

• Declaration of an array:
In java arrays can be declared in two ways
Syntax 1: Type ArrayName [ ];
Syntax 2: Type [ ] ArrayName;
Eg: int num[ ];
float[ ]avg;

• Creating memory locations:


After declaring an array we need to allocate memory to it. Java allows us to create
arrays using new operator
Syntax: ArrayName=new type [size];
Eg: num =new int [5];
The variable num refers to an array of 5 integers. The conceptual view for the above example
is
num[0]
num[1]
num[2]
num[3]
num[4]

We can combine declaration and creation into one step


Eg: int num [ ]=new int[5];

Statement Result

int num[] Num


num=new int[5]; Points to no where

JAGAN’S DEGREE COLLEGE Page 30


II B.Sc(M.S.C.S/M.P.C.S)

Num

num[0]
num[1]
num[2]
num[3]
num[4]

• Initialization of arrays: The final step is to insert values into the array. This process
is called initialization. This is done using an array subscript or index
Eg: num [2]=35;

Array index starts from 0 and hence with “size-1”.we can initialize arrays when
they are declared
Syntax: Type ArrayName [ ]={list of values};
Eg: int num [ ]={35, 40,25,19};

➢ Array length:All arrays store the allocated sizes in a variable named “ length”.we can
apply the length of the array num using “num.length”
Eg: int l=num.length;

2. Two Dimensional arrays:


A variable name having list of items using two subscripts is called “two
dimensional arrays”. Two dimensional arrays are in the form of rows and columns. The
declaration and creation of two dimensional arrays is follows:
Syntax 1: type ArrayName [ ] [ ];
ArrayName=newtype[size1][size2];
Syntax2: type ArrayName[ ][ ]=new type[size1][size2];
Here size 1 specifies number of rows and size2 specifies number of columns
Eg: int a[ ][ ]=new int[3][4];
The conceptual view for the above example is
0 1 2 3
a[0]
a[1]
a[2]

This example creates an array that can store 12 integer numbers in 3 rows and 4
columns
➢ Initialization:
The initialization of two dimensional arrays is as follows:
Eg: int a[ ] [ ] ={{6, 9, 4},{3,4,8}};
Camas is required after each brace that closes of a row, except in the case of last row.
We can refer to a value stored in the third row and the second column in the array as a[2][1]

JAGAN’S DEGREE COLLEGE Page 31


II B.Sc(M.S.C.S/M.P.C.S)

2. Three Dimensional Arrays:

Three-dimensional array is the collection of two-dimensional arrays in Java programming


language. Three-dimensional array is also called the multidimensional array.

➢ Declaration of the three dimensional Array

Syntax data_type[][][] arrayname;----1


or
data_type arrayname [][][] ;----2

we can choose any one method


Explanation of Three dimensional Array declaration
Syntax:int [][][]array;

➢ Forming of three dimension array


Syntax :data_type[][][]array_name=new data_type;
Example:int array[][][]=new int[2][3][3];

➢ How to initialize a 3d array in Java


➢ Method 1

Syntax array_name[index_1][index_2][index_3]=value;
Example arr[0][0][0]=45; //initialize first elements of 3 d array
we can initialize every index, like this
➢ Method 2
Ex: int[][][] arr{
{
{34,67,43},
{576,697,423},
{576,697,423}
},
{
{39,47,33},
{376,987,453},
{57,69,42}
},

Example program :

class threedarrayex{
public static void main(String args[])
{
int[][][]marks; //declaration of array
marks=new int[2][2][2];//initiation of array
//initiate elements

JAGAN’S DEGREE COLLEGE Page 32


II B.Sc(M.S.C.S/M.P.C.S)

marks[0][0][0]=25;
marks[0][0][1]=15;
marks[0][1][0]=20;
marks[0][1][1]=05;
marks[1][0][0]=10;
marks[1][0][1]=13;
marks[1][1][0]=12;
marks[1][1][1]=30;
//Display elements from array
System.out.println(marks[0][0][0]);
System.out.println(marks[0][0][1]);
System.out.println(marks[0][1][0]);
System.out.println(marks[0][1][1]);
System.out.println(marks[1][0][0]);
System.out.println(marks[1][0][1]);
System.out.println(marks[1][1][0]);
System.out.println(marks[1][1][1]);
}
}

When the above code is compiled and executed, it will produce the following results

25
15
20
5
10
13
12
30

14. Command Line Arguments:


Command line Arguments are parameters that are supplied to the application program
at the time of invoking it for execution. We can write java programs that can receive and use
the arguments provided in the command line . We write the main method like the following:
public static void main( String args[])
In the above statement, args[] is declared as an array of strings. Any arguments provided in
the command line ( at the time of execution) are passed to the array args[] as its elements. We
can simply access the array elements and use them in the program as we wish.

EX:
Class Comlinetest
{
public static void main(String args[])
{
int count, i=o;
String string;
JAGAN’S DEGREE COLLEGE Page 33
II B.Sc(M.S.C.S/M.P.C.S)

count=args.length;
System.out.println(“ Number of arguments=”+count);
While( i< count)
{
String= args[i];
i=i+1;
System.out.println(i + “ : “ + “Java is” + string+ “!”);
}
}
}

Compile the above program with the command line as follows:


Javac Comlinetest.java
Java Comlinetest simple oop secure robust portable dynamic
Number of arguments:6
The index I is incremented using a while loop until all the arguments are accessed.
The number of arguments is obtained by statement.
Count= args.length;
The output of the program would be as follows:

Output:
Number of arguments=6
1 : Java is simple!
2 : Java is oop!
3 : Java is secure!
4: Java is robust!
5 : Java is portable!
6 : Java is portable!
7 : java is dynamic!
UNIT-II
STRINGS
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java,
string is an immutable object which means it is constant and cannot be changed once it has
been created.

1. Creating a String:-
There are two ways to create string in Java:
• String literal
String s = “GeeksforGeeks”;
• Using new keyword
String s = new String (“GeeksforGeeks”);

➢ String literal

In java, Strings can be created like this: Assigning a String literal to a String
instance:
String str1 ="Welcome";
String str2 ="Welcome";

JAGAN’S DEGREE COLLEGE Page 34


II B.Sc(M.S.C.S/M.P.C.S)

What if we want to have two different object with the same string? For that we would
need to create strings using new keyword.

➢ Using New Keyword

As we saw above that when we tried to assign the same string object to two
different literals, compiler only created one object and made both of the literals to point the
same object. To overcome that approach we can create strings like this:

String str1 =newString("Welcome");


String str2 =newString("Welcome");
In this case compiler would create two different object in memory having the same string.

2. String class methods:


String class provides number of methods to perform various operations on string objects
the following of the most commonly used string methods.

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 String substring(intbeginIndex) returns substring for given begin index.

4 String substring(intbeginIndex, returns substring for given begin index and end
intendIndex) index.

5 boolean contains(CharSequence s) returns true or false after matching the sequence


of char value.

6 boolean equals(Object another) checks the equality of string with the given object.

7 booleanisEmpty() checks if string is empty.

8 String toLowerCase() returns a string in lowercase.

9 String toUpperCase() returns a string in uppercase.

10 String trim() removes beginning and ending spaces of this


string.

Ex:
public class Testmethodofstringclass
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin

JAGAN’S DEGREE COLLEGE Page 35


II B.Sc(M.S.C.S/M.P.C.S)

System.out.println(s);//Sachin(no change in original)


}}

Compile by: javac Testmethodofstringclass.java


Run by: java Testmethodofstringclass
SACHIN
sachin
Sachin

3. Compare two Strings in Java:


String is a sequence of characters. In Java, objects of String are immutable which means they
are constant and cannot be changed once created.

1. Using user-defined function : Define a function to compare values with following


conditions :
1. if (string1 > string2) it returns a positive value.
2. if both the strings are equal lexicographically
i.e.(string1 == string2) it returns 0.
3. if (string1 < string2) it returns a negative value.
2. Using String.equals() :In Java, string equals() method compares the two given strings
based on the data/content of the string. If all the contents of both the strings are same
then it returns true. If any character does not match, then it returns false.
Syntax:
str1.equals(str2);
Here str1 and str2 both are the strings which are to be compared.

Ex Program:

public class GFG {


public static void main(String args[])
{
String string1 = new String("Geeksforgeeks");
String string2 = new String("Practice");
String string3 = new String("Geeks");
String string4 = new String("Geeks");
String string5 = new String("geeks");

// Comparing for String 1 != String 2


System.out.println("Comparing " + string1 + " and " + string2
+ " : " + string1.equals(string2));

// Comparing for String 3 = String 4


System.out.println("Comparing " + string3 + " and " + string4
+ " : " + string3.equals(string4));

// Comparing for String 4 != String 5

JAGAN’S DEGREE COLLEGE Page 36


II B.Sc(M.S.C.S/M.P.C.S)

System.out.println("Comparing " + string4 + " and " + string5


+ " : " + string4.equals(string5));

// Comparing for String 1 != String 4


System.out.println("Comparing " + string1 + " and " + string4
+ " : " + string1.equals(string4));
}
}
Output:
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : false
Comparing Geeksforgeeks and Geeks : false

4. Immutable String in Java:

In java, string objects are immutable. Immutable simply means unmodifiable or


unchangeable.Once string object is created its data or state can't be changed but a new string
object is created. Let's try to understand the immutability concept by the example given below:

Ex: class Testimmutablestring


{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}

Output:Sachin

Here Sachin is not changed but a new object is created with sachintendulkar. That
is why string is known as immutable.

But if we explicitely assign it to the reference variable, it will refer to "Sachin


Tendulkar" object.For example:

Ex: class Testimmutablestring1


{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

JAGAN’S DEGREE COLLEGE Page 37


II B.Sc(M.S.C.S/M.P.C.S)

Output:Sachin Tendulkar

5.Procedure Oriented Programming (POP) (problems in POP)


High level language such as C, COBOL,PASCALetc is commonly known as
POP languages. In procedure oriented programming the problem is viewed as sequence of
things to be done, such as reading, calculating and printing. In procedural Oriented
Programming the problem can be decomposes into small tasks knows as Functions. In
Procedure Oriented Programming the primary focus is on function. The diagrammatic
representation of multi-function programming is as follows

Advantages:
• Its relative simplicity, and ease of implementation of compilers and
interpreters
• The ability to re-use the same code at different places in the program without
copying it.
• An easier way to keep track of program flow.
• The ability to be strongly modular or structured.
• Needs only less memory.
Disadvantages:
• Data is exposed to whole program, so no security for data.
• Difficult to relate with real world objects.
• Difficult to create new data types reduces extensibility.
• Importance is given to the operation on data rather than the data.

In POP global data may be accessed by all the functions. In a large program, it is very
difficult to identify what data is used by which function. This is one of the biggest drawbacks
in procedure-oriented programming. To solve the disadvantages encountered (find) in POP,
developers develop a new concept Object Oriented Programming (OOPS).

6. Features of Object Oriented Programming:

Object-Oriented approach was introduced to overcome the drawbacks of Procedural


approach. OOP treats data as an important element in the program development. Data cannot
be moved freely around the system. It binds data more closely to the functions and protect from
accidental modification from the outside functions.
OOPs decompose a problem into a number of entities called “Objects”. The
Organization of data and functions in Object Oriented Programming as shown below.

Organization of OOPS

JAGAN’S DEGREE COLLEGE Page 38


II B.Sc(M.S.C.S/M.P.C.S)

Basic concepts of OOPs (or) Basic Features of OOPs (or) Key concepts of OOPs (or) OOP
Characteristics:-
Object oriented Programming is an approach that provides the way of modularizing
programs by creating partition memory for both data and functions. The following are the basic
elements of OOPs.
1. Objects:
• Objects are the basic run time entities in an object oriented programming.
• Memory will allocates only for objects not for classes.
• Objects are the variables of class.
• Each object contains data and functions. By using functions, we can manipulate data.
2. Classes:
• Classes are the basic building blocks of oops.
• Classes combined both data and function.
• Classes create new user defined data types.
• A class is a data type and object is a variable of class type.
• Once a class has been defined we can create number of objects belonging to that class.
3. Data abstraction:
• Data abstraction means removing unnecessary data. i.e., representing the essential
features without including background details.
• By the feature of data abstraction, it is possible to create user defined datatypes.
4. Data encapsulation:
• The process of combining both data and functions into a single unit is known as data
encapsulation.
• Class is the example for data encapsulation. The Data is not accessible by outside class.
• By using encapsulation, we can accomplish data hiding.
5. Inheritance:
• Inheritance is a process of creating a new class from existing class. The new class
contains both the features new class and old class.
• Inheritance is very useful to add additional features to an existing class without
modifying it.

6. Polymorphism: -

JAGAN’S DEGREE COLLEGE Page 39


II B.Sc(M.S.C.S/M.P.C.S)

• Polymorphism means the ability to take more than one form with a single name.
• “Polymorphism” comes from the ‘Greek’ word. “Poly” means “many” and “morphism”
means “forms”. i.e., many forms.

7. Dynamic Binding:- Binding Refers to the linking of procedure called to the code to be
executed in response to that call. Dynamic binding means that the code associated with the
given procedure call is not known until runtime. It is achieved with virtual functions and
inheritance in c++.
8. Message Passing:- A message for an object is a request for executing a procedure or a
function. A message for an object will invoke a function that generates the desired results.
Message passing involve specifying the name of object, name of the function and information
to be send.
Ex:-Emp.salary(sno);
Here Emp is an object, salary is a message and sno is an information.

7. Classes and objects:

❖ class:
A class is a collection of related objects that share a common properties and methods. Classes
are used to pack a group of data items and functions in java. The data items are called “fields”
and functions are called “methods”.
❖ Defining a Class:
classes are defined using the keyword “class”once a class is defined we can create any number
of objects belong into that class. In java these variable called “instance of classes”.
Syntax:
classclassname
{
Fields Declaration/variable Declaration
Method Declaration
}

❖ Fields Declaration/variable Declaration: The variables which are declared inside a


class are called “fields”. These variables are also called instance variables they are
created when ever an object of the class is instantiated.
Eg:
class Rectangle
{
int length;
int width;
}

JAGAN’S DEGREE COLLEGE Page 40


II B.Sc(M.S.C.S/M.P.C.S)

The class rectangle contains two integer type instance variables no memory
space is reserved for these instance variables

❖ Methods Declaration: Methods are necessary for manipulating the data contain that
class. Methods are declared and defined inside the body of the class immediately after
the declaration of instance of variable
syntax: return_typemethod_name(parameters list)
{
Method body
}

Method declarations have 4 basic parts


1. The name of the method
2. The type of the value that the method returns
3. A list of parameters
4. The body of the method

Eg: class Rectangle


{
intlength,width;
voidgetData(intx,int y)
{
length=x;
width=y;
}
}

❖ Objects:
❖ Objects:

An object is a block of memory that contains space to store all the instance variable

❖ Creating objects:
• Creating an object is also referred as instantiating an object
• In java objects are created using the operator new
• The new operator creates an object of the specified class and returns a reference to the
object
syntax 1:
classnameobj;
obj= new className();
syntax 2:
classnameobj=new classname();
Eg: Rectangle r;
r= new Rectangle();

❖ Accessing class members:


We cannot access the instance variables and methods directly from outside the class.
To access them from outside the class we must use the concerned object and the dot (.) operator
syntax:
objectname.variable=value;

JAGAN’S DEGREE COLLEGE Page 41


II B.Sc(M.S.C.S/M.P.C.S)

objectname.methodName(parameters list);
Here object name is the name of the object method name is the name of the method
that we wish to call
Eg: class Rectangle
{
intlength,width;
voidgetData(int x, int y)
{
length=x;
width=y;
}

int Area()
{
return length*width;
}
}
classRectArea
{
public static void main(String args[])
{
int area1,area2;
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.length=12;
r1.width=10;
area1 =r1.length*r1.width;
r2.getData(20,13);
area2=r2.Area();
System.out.println(“Area1=”+area1);
System.out.println(“Area2=”+area2);
}
}
Output:
Area 1=120
Area 2=260

8. Access specifiers (or) visibility controls (or) Access modes:


Sometimes it is necessary to restrict the access to some variables and methods
from outside the class. In java it is achieved by applying access controls to instance variables and
methods. These access controls are also called visibility controls. Java supports 3 different types
of visibility controls
• 1.Public 2. Private 3. Protected
❖ public access: The members that are declared as public are visible and accessible
anywhere. The scope of the public members is global.
Eg: public intnum;
public void sum()
{
……….

JAGAN’S DEGREE COLLEGE Page 42


II B.Sc(M.S.C.S/M.P.C.S)

…..…..
}
❖ private access: The members that are declared as private are not accessible from
outside the class they are accessible only within their own class by the methods of that
class. They cannot accessible in sub class.
Eg : private intnum;
private void sum()
{
……….
………..
}
❖ protected access: The members that are declared as protected are visible to all the
classes and sub classes in the same package and also subclasses in other packages. The
non sub class in other packages cannot access the protected members.
Eg: protected intnum;
protected void sum()
{……..}
Ex1: class A
{
public void display()
{
System.out.println("SoftwareTestingHelp!!");
}
}
class Main
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}
}
Output:
SoftwareTestingHelp!!

Ex2: The below program demonstrates the usage of the Protected Access modifier in Java.

class A
{
protected void display()
{
System.out.println("SoftwareTestingHelp");
}
}

class B extends A {}
class C extends B {}

class Main{

JAGAN’S DEGREE COLLEGE Page 43


II B.Sc(M.S.C.S/M.P.C.S)

public static void main(String args[])


{
B obj = new B(); //create object of class B
obj.display(); //access class A protected method using obj
C cObj = new C(); //create object of class C
cObj.display (); //access class A protected method using cObj
}
}

Output:SoftwareTestingHelp

SoftwareTestingHelp

Ex3: The following Java program demonstrates the use of getter and setter methods for
private variables in Java.

class DataClass {
private String strname;

// getter method
public String getName() {
return this.strname;
}
// setter method
public void setName(String name) {
this.strname= name;
}
}
public class Main {
public static void main(String[] main){
DataClass d = new DataClass();

// access the private variable using the getter and setter


d.setName("Java Programming");
System.out.println(d.getName());
}
}

Output:

Java Programming

9. Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when
an instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory. It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

JAGAN’S DEGREE COLLEGE Page 44


II B.Sc(M.S.C.S/M.P.C.S)

It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.

❖ Rules for creating Java constructor


There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
❖ Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

1. Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>(){}
1. Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of ob
creation.
class Bike1
{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.
2. Example of default constructor that displays the default values
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:

JAGAN’S DEGREE COLLEGE Page 45


II B.Sc(M.S.C.S/M.P.C.S)

0 null
0 null
In the above class, we are not creating any constructor so compiler provides a
default constructor. Here 0 and null values are provided by default constructor.

2. Java Parameterized Constructor


A constructor which has a specific number of parameters is called a
parameterized constructor.The parameterized constructor is used to provide different values to
distinct objects. However, we can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
Ex: class Student4{
int id;
String name;
Student4(inti,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
} }

Output:
111 Karan
222 Aryan

10. Methods in java:


In general, a method is a way to perform some task. Similarly, the method in Java is
a collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods.
A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code again
and again. It also provides the easy modification and readability of code, just by adding or
removing a chunk of code. The method is executed only when we call or invoke it.
The most important method in Java is the main() method.

❖ Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known as method
header, as we have shown in the following figure.

JAGAN’S DEGREE COLLEGE Page 46


II B.Sc(M.S.C.S/M.P.C.S)

❖ Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
❖ Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our
application.

Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.

Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.

❖ Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
❖ Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are creating
a method for subtraction of two numbers, the method name must be subtraction(). A
method is invoked by its name.
❖ Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.
❖ Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Types of Method

There are two types of methods in Java:


• Predefined Method
• User-defined Method

❖ Predefined Method

In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as the standard library

JAGAN’S DEGREE COLLEGE Page 47


II B.Sc(M.S.C.S/M.P.C.S)

method or built-in method. We can directly use these methods just by calling them in the
program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(),
etc. When we call any of the predefined methods in our program, a series of codes related to
the corresponding method runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print()
method is defined in the java.io.PrintStream class. It prints the statement that we write inside
the method. For example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

class Demo

{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.println("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9

In the above example, we have used three predefined methods main(), print(),
and max(). We have used these methods directly without declaration because they are
predefined. The print() method is a method of PrintStream class that prints the result on the
console. The max() method is a method of the Math class that returns the greater of two
numbers.

❖ User-defined Method

The method written by the user or programmer is known as a user-defined method.


These methods are modified according to the requirement.

How to Create a User-defined Method


Let's create a user defined method that checks the number is even or odd. First, we
will define the method.

Addition.java

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

JAGAN’S DEGREE COLLEGE Page 48


II B.Sc(M.S.C.S/M.P.C.S)

int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

Output:
The sum of a and b is= 24

11. Static Method:

A method that has static keyword is known as static method. In other words, a method
that belongs to a class rather than an instance of a class is known as a static method. We can
also create a static method by using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an
object. It can access static data members and also change the value of it. It is used to create an
instance method. It is invoked by using the class name. The best example of a static method is
the main() method.

Example of static method

Display.java

public class Display


{
public static void main(String[] args)
{
show();
static void show()
{
System.out.println("It is an example of static method.");
}
}
Output:
It is an example of a static method.

JAGAN’S DEGREE COLLEGE Page 49


II B.Sc(M.S.C.S/M.P.C.S)

12. Instance Method:

The method of the class is known as an instance method. It is a non-static method


defined in the class. Before calling or invoking the instance method, it is necessary to create an
object of its class. Let's see an example of an instance method.

InstanceMethodExample.java

public class InstanceMethodExample


{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25

13. This keyword in java:

There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Example:

class Student{

JAGAN’S DEGREE COLLEGE Page 50


II B.Sc(M.S.C.S/M.P.C.S)

int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Test it Now
Output:
111 ankit 5000
112 sumit 6000

14. .Passing Primitive Data Types and objects to Methods:


❖ Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables
inside the method.Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is used inside the
method to print the full name:
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}

When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

JAGAN’S DEGREE COLLEGE Page 51


II B.Sc(M.S.C.S/M.P.C.S)

❖ Multiple Parameters
Note that when you are working with multiple parameters, the
method call must have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.

publicclassMain{
staticvoidmyMethod(Stringfname,int age){
System.out.println(fname+" is "+ age);
}

publicstaticvoidmain(String[]args){
myMethod("Liam",5);
myMethod("Jenny",8);
myMethod("Anja",31);
}
}

// Liam is 5
// Jenny is 8
// Anja is 31

15.Passing Arrays to methods in java:

A method may or may not take a fixed set of parameters. A parameter can be any
variable that we need to use to define the body of the method.
In the example of a factorial method, a parameter can be the number whose factorial we need
to find. But what if we need to pass an entire array to a method?
In the method declaration, we need to tell Java that the method must accept an array of a certain
data type to pass an array to a method. Use the data type of the array and square brackets to
denote that the parameter is an array.

//Method Declaration

public static void addTen(int[] arr)

//Method Body

}
Whenever the method is called, we need to pass the array’s name to the method. The
following example shows a complete code with a method that accepts an array and calls that
method.
public class Main
{
public static void addTen(int[] arr)// int[] denotes that the parameter is an array
{
for(int i = 0; i <arr.length; i++)

JAGAN’S DEGREE COLLEGE Page 52


II B.Sc(M.S.C.S/M.P.C.S)

{
arr[i] += 10;
}
}
public static void main(String[] args)
{
int[] arr = {1, 3, 5, 7, 9};
addTen(arr);//Simply pass the name of the array to the method
for(int i = 0; i <arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Output:
11 13 15 17 19

16. Recursion in Java

Recursion in java is a process in which a method calls itself continuously. A


method in java that calls itself is called recursive method.

Syntax:

returntype methodname(){
//code to be executed
methodname();//calling same method
}

Factorial Number example program:

public class RecursionExample3


{
static int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args)


{
System.out.println("Factorial of 5 is: "+factorial(5));
}
}

JAGAN’S DEGREE COLLEGE Page 53


II B.Sc(M.S.C.S/M.P.C.S)

Output:
Factorial of 5 is: 120

Working of above program:

factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

17.Factory methods in java:

Factory Methods Factory methods are' static methods only. "But their intension is to
create an object depending on the user choice. -Precisely, a factory method is a method that
returns an object to the class, to which it belongs. For example, getNumberlnstance () is a
factory method. Why? Because it belongs to NumberFormat class and returns an object to
NurilberFormat class. At the time of creating objects, if the u;er has several types of options
(values) to be passed -to the object, then several overloaded constructors should be Written in
the class. For example, there are 10 different types of values to be passed, then 10 constructors
are needed to accept those 10 types of options. This can be eliminated by using factory methods.
A single factory method gives provision to pass any type of value through a parameter.
Generally, the parameter is used to pass different types of values. Based on the value passed,
the object is created by the factory method. What are factory methods? A factory method is a
method that creates and returns an object to the ciass to which it belQngs. A single factory
method replaces several constructors in the class by accepting different options from the user,
while creating the -object. ' To understand how to use a factory method, let us take an example
program to calculate the area 0 a circle. - ,

Factory Method is a creational design pattern that provides an interface for creating
objects in a superclass, but allows subclasses to alter the type of objects that will be created.

The Factory Method pattern suggests that you replace direct object construction calls (using
the new operator) with calls to a special factory method. Don’t worry: the objects are still
created via the new operator, but it’s being called from within the factory method. Objects
returned by a factory method are often referred to as products.

JAGAN’S DEGREE COLLEGE Page 54


II B.Sc(M.S.C.S/M.P.C.S)

At first glance, this change may look pointless: we just moved the constructor call from one
part of the program to another. However, consider this: now you can override the factory
method in a subclass and change the class of products being created by the method.

There’s a slight limitation though: subclasses may return different types of products only if
these products have a common base class or interface. Also, the factory method in the base
class should have its return type declared as this interface.

All products must follow the same interface.

For example, both Truck and Ship classes should implement the Transport interface, which
declares a method called deliver. Each class implements this method differently: trucks deliver
cargo by land, ships deliver cargo by sea. The factory method in the RoadLogistics class returns
truck objects, whereas the factory method in the SeaLogistics class returns ships.

• Advantages of Java factory method


A few of the advantages which Java factory method offers:

1. The object that you create can be used without duplication of code.

JAGAN’S DEGREE COLLEGE Page 55


II B.Sc(M.S.C.S/M.P.C.S)

2. If you use a factory method instead of a constructor, the factory method can have
different and more descriptive names also .
3. Also, it removes the instantiation of the implementation classes from the client code.
4. This method makes the code more robust, less coupled and easy to expand.
5. Factory pattern through inheritance provides abstraction between implementation and
the client classes.

18.Inheritance in java

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the


mechanism in java by which one class is allowed to inherit the features(fields and methods)
of another class.
In Java, inheritance means creating new classes based on existing ones. A class that
inherits from another class can reuse the methods and fields of that class. In addition, you
can add new fields and methods to your current class as well.

Inheritance in Java: Why do we need it?

• Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is one
of the ways by which java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Important terminologies used in Inheritance:

• Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.

How to use inheritance in Java?

The extends keyword is used for inheritance in java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to
increased functionality.
Syntax :
class derived-class extends base-class
{

JAGAN’S DEGREE COLLEGE Page 56


II B.Sc(M.S.C.S/M.P.C.S)

//methods and fields


}

In the below example of inheritance, class Employee is a base class, class Engineer is a
derived class that extends the Employee class and class Test is a driver class to run the
program.
/ Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class

class Employee {

int salary = 60000;

// Inherited or Sub Class

class Engineer extends Employee {

int benefits = 10000;

// Driver Class

class Gfg {

public static void main(String args[])

Engineer E1 = new Engineer();

System.out.println("Salary : " + E1.salary

+ "\nBenefits : " + E1.benefits);

JAGAN’S DEGREE COLLEGE Page 57


II B.Sc(M.S.C.S/M.P.C.S)

Output
Salary : 60000
Benefits : 10000

Types of Inheritance in Java

Below are the different types of inheritance which are supported by Java.
1. Single Inheritance:
In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.

Example:
/ Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

class One {
public void print()
{
System.out.println("welcome");
}
}

class Two extends One {


public void for() { System.out.println("back"); }
}
// Driver class
public class Main {
public static void main(String[] args)
{
Two g = new Two();

JAGAN’S DEGREE COLLEGE Page 58


II B.Sc(M.S.C.S/M.P.C.S)

g.print ();
g. for();

}
}

Output:

Welcome
back

2. Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes. In the below image, class A
serves as a base class for the derived class B, which in turn serves as a base class for the
derived class C. In Java, a class cannot directly access the grandparent’s members.

Example:

// Java program to illustrate the


// concept of Multilevel inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

class One {
public void print()
{
System.out.println("Multi level");
}
}

class Two extends One {


public void print_for()

JAGAN’S DEGREE COLLEGE Page 59


II B.Sc(M.S.C.S/M.P.C.S)

{
System.out.println("Inheritance");
}
}

class Three extends Two {


public void display()
{
System.out.println("Example");
}
}

// Drived class
public class Main {
public static void main(String[] args)
{
Three g = new Three();
g.print ();
g.print_for();
g.display();
}
}
Output:

Multi level
Inheritance
Example

3. Hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the derived classes
B, C, and D.

Example:

/ Java program to illustrate the


// concept of Hierarchical inheritance

JAGAN’S DEGREE COLLEGE Page 60


II B.Sc(M.S.C.S/M.P.C.S)

class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Output:

Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance ( Through Interfaces):


In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
JAGAN’S DEGREE COLLEGE Page 61
II B.Sc(M.S.C.S/M.P.C.S)

inheritances with classes. In java, we can achieve multiple inheritances only


through Interfaces. In the image below, Class C is derived from interfaces A and B.

Example:

// Java program to illustrate the


// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface One {
public void print_gk();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_gk();
}
class child implements Three {
@Override public void print_gk()
{
System.out.println("hello");
}

public void print_for() { System.out.println("java"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
child c = new child();
c.print_gk();
c.print_for();
c.print_gk();
}
}

JAGAN’S DEGREE COLLEGE Page 62


II B.Sc(M.S.C.S/M.P.C.S)

Output:
Hello
Java

Hello
5. Hybrid Inheritance(Through Interfaces)
It is a mix of two or more of the above types of inheritance. Since java doesn’t
support multiple inheritances with classes, hybrid inheritance is also not possible with
classes. In java, we can achieve hybrid inheritance only through Interfaces.

UNIT–III

POLYMORPHISM

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

❖ Method overloading:
Method overloading means writing to two or more methods with the same name
and with the different signature is called method overloading.
To create and overloaded method we have to provide different method definition
with the same name with different parameter list. The difference may be is number of arguments or
type of arguments. That is each parameter list should be unique.
Method overloading is used when objects are required to perform similar tasks but
using different input parameters when we call a method in an object java searches for the method
name first and then the number and type of parameters to decide which method to execute this
process is known as polymorphism.
Eg:
class Arith
{
int add( int x, int y)

JAGAN’S DEGREE COLLEGE Page 63


II B.Sc(M.S.C.S/M.P.C.S)

{
return x+y;
}
float add(float x,float y)
{
return x+y;
}
}
class Test
{
public static void mainh (String args[ ])
{
Arith a=new Arith();
int m=a.add(3,4);
float n=a.add(4.5,3.6);
System.out.println(“integer addition=”+m);
System.out.println(“float addition=”+n);
}
}
Output:
Integer addition=7
Floating addition=8.1

❖ Method overriding:
Writing two or more methods in super and sub classes such that the methods have
same name, same signature is called method over riding.
Over riding is possible by defining a method in subclass that has the same name,
same parameters list and same return type as the method in the super class when that methods
defining in the subclass is invoked and executed instead of super class method.
Eg:
import java.lang.Math;
class one
{
void calc(int x)
{
System.out.println(square value=”+(x*x));
}
class two extends one
{
void calc(int x)
{
System.out.println(“square root=”+(math.sqrt(x));
}
}

JAGAN’S DEGREE COLLEGE Page 64


II B.Sc(M.S.C.S/M.P.C.S)

class Test
{
public static void main(String args[ ])
{
two t=new two();
t.calc(49);
}
}
Output:
Square root=7

1.Polymorphic Variables

A variable is called polymorphic if it refers to different values under different


conditions.

Object variables (instance variables) represent the behavior of polymorphic


variables in Java. It is because object variables of a class can refer to objects of its
class as well as objects of its subclasses.

Example: Polymorphic Variables

class ProgrammingLanguage {
public void display() {
System.out.println("I am Programming Language.");
}
}

class Java extends ProgrammingLanguage {


@Override
public void display() {
System.out.println("I am Object-Oriented Programming
Language.");
}
}

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

// declare an object variable


ProgrammingLanguage pl;

// create object of ProgrammingLanguage


pl = new ProgrammingLanguage();

JAGAN’S DEGREE COLLEGE Page 65


II B.Sc(M.S.C.S/M.P.C.S)

pl.display();

// create object of Java class


pl = new Java();
pl.display();
}
}

Output:

I am Programming Language.
I am Object-Oriented Programming Language.

In the above example, we have created an object variable pl of

the ProgrammingLanguage class. Here, pl is a polymorphic variable. This is

because,

• In statement pl = new ProgrammingLanguage(), pl refer to the object of

the ProgrammingLanguage class.

• And, in statement pl = new Java(), pl refer to the object of the Java class.

Polymorphisam with static methods? The answer is ‘Yes’. We can have two or
more static methods with the same name, but differences in input parameters. For example,
consider the following Java program.

// filename Test.java

public class Test {

public static void foo() {

System.out.println("Test.foo() called ");

JAGAN’S DEGREE COLLEGE Page 66


II B.Sc(M.S.C.S/M.P.C.S)

public static void foo(int a) {

System.out.println("Test.foo(int) called ");

public static void main(String args[])

Test.foo();

Test.foo(10);

Output

Test.foo() called
Test.foo(int) called

Can we Override static methods in java? We can declare static methods with
the same signature in the subclass, but it is not considered overriding as there won’t be any
run-time polymorphism. Hence the answer is ‘No’.
If a derived class defines a static method with the same signature as a static method
in the base class, the method in the derived class is hidden by the method in the base
class.

class Base {

public static void display() {

JAGAN’S DEGREE COLLEGE Page 67


II B.Sc(M.S.C.S/M.P.C.S)

System.out.println("Static or class method from Base");

public void print() {

System.out.println("Non-static or Instance method from Base");

class Derived extends Base {

public static void display() {

System.out.println("Static or class method from Derived");

public void print() {

System.out.println("Non-static or Instance method from Derived");

public class Test {

public static void main(String args[ ]) {

Base obj1 = new Derived();

obj1.display();

JAGAN’S DEGREE COLLEGE Page 68


II B.Sc(M.S.C.S/M.P.C.S)

obj1.print();

Output:

Static or class method from Base


Non-static or Instance method from Derived

2.Polymorphism with private methods in java


we cannot override private or static methods in Java.

Private methods in Java are not visible to any other class which limits their scope to
the class in which they are declared.

Example

Let us see what happens when we try to override a private method −

class Parent {
private void display() {
System.out.println("Super class");
}
}
public class Example extends Parent {
void display() // trying to override display() {
System.out.println("Sub class");
}
public static void main(String[] args) {
Parent obj = new Example();
obj.display();
}
}

JAGAN’S DEGREE COLLEGE Page 69


II B.Sc(M.S.C.S/M.P.C.S)

Output

The output is as follows −


Example.java:17: error: display() has private access in Parent
obj.method();
^
1 error
The program gives a compile time error showing that display() has private access in Parent
class and hence cannot be overridden in the subclass Example

3. Final Methods and Final classes:


The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It
will be constant). Final variables are nothing but constants. We cannot change the value of a
final variable once it is initialized.

A final variable that is not initialized at the time of declaration is known as blank
final variable. We must initialize the blank final variable in constructor of the class
otherwise it will throw a compilation error (Error: variable MAX_VALUE might not have been
initialized).

This is how a blank final variable is used in a class:

classDemo{
//Blank final variable
finalint MAX_VALUE;

Demo(){
//It must be initialized in constructor
MAX_VALUE=100;
}
void myMethod(){
System.out.println(MAX_VALUE);
JAGAN’S DEGREE COLLEGE Page 70
II B.Sc(M.S.C.S/M.P.C.S)

}
publicstaticvoid main(String args[]){
Demo obj=newDemo();
obj.myMethod();
}
}

Output:

100

What is the use of blank final variable?


Lets say we have a Student class which is having a field called Roll No.
Since Roll No should not be changed once the student is registered, we can declare it as a final
variable in a class but we cannot initialize roll no in advance for all the students(otherwise all
students would be having same roll no). In such case we can declare roll no variable as blank
final and we initialize this value during object creation like this:

classStudentData{
//Blank final variable
finalint ROLL_NO;

StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
publicstaticvoid main(String args[]){
StudentData obj=newStudentData(1234);
obj.myMethod();
}
}

Output:

Rollnois:1234

2.final method:
A final method cannot be overridden. Which means even though a sub class can
call the final method of parent class without any issues but it cannot override it?

Example:
class XYZ{
finalvoid demo(){
System.out.println("XYZ Class Method");

JAGAN’S DEGREE COLLEGE Page 71


II B.Sc(M.S.C.S/M.P.C.S)

}
}

class ABC extends XYZ{


void demo(){
System.out.println("ABC Class Method");
}

publicstaticvoid main(String args[]){


ABC obj=new ABC();
obj.demo();
}}

The above program would throw a compilation error, however we can use the parent
class final method in sub class without any issues. Lets have a look at this code: This program
would run fine as we are not overriding the final method. That shows that final methods are
inherited but they are not eligible for overriding.

class XYZ{
finalvoid demo(){
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ{


publicstaticvoid main(String args[]){
ABC obj=new ABC();
obj.demo();
}
}

Output:

XYZ ClassMethod

3) Final class:
In Java, the final class cannot be inherited by another class. For example,We cannot
extend a final class. Consider the below example:

finalclass XYZ{
}

class ABC extends XYZ{


void demo(){
System.out.println("My Method");
}
publicstaticvoid main(String args[]){
ABC obj=new ABC();
obj.demo();
}
}
Output:

JAGAN’S DEGREE COLLEGE Page 72


II B.Sc(M.S.C.S/M.P.C.S)

The type ABC cannot inherit the finalclass XYZ // compilation error

Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be
changed.
8) It is a good practice to name final variable in all CAPS.

4.ABSTRACT CLASSES:

Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces
(which you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

• Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).

• Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).

❖ Java Abstract Class


The abstract class in Java cannot be instantiated (we cannot create objects of
abstract classes). We use the abstract keyword to declare an abstract class. For example,

Ex:abstractclass Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();

JAGAN’S DEGREE COLLEGE Page 73


II B.Sc(M.S.C.S/M.P.C.S)

}
}

Output

This is Java programming


In the above example, we have created an abstract class named Language. The class contains
a regular method display().We have created the Main class that inherits the abstract class.
Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the abstract class
using the object obj.

❖ Abstract Methods
If the abstract class includes any abstract method, then all the child classes
inherited from the abstract superclass must provide the implementation of the abstract method.

For example,

abstractclassAnimal{
abstractvoidmakeSound();

publicvoideat(){
System.out.println("I can eat.");
}
}

classDogextendsAnimal{

// provide implementation of abstract method


publicvoidmakeSound(){
System.out.println("Bark bark");
}
}

classMain{
publicstaticvoidmain(String[] args){

// create an object of Dog class


Dog d1 = new Dog();

d1.makeSound();
d1.eat();
}
}

Output

Bark bark
I can eat.

In the above example, we have created an abstract class Animal. The class contains
an abstract method makeSound() and a non-abstract method eat().

JAGAN’S DEGREE COLLEGE Page 74


II B.Sc(M.S.C.S/M.P.C.S)

We have inherited a subclass Dog from the superclass Animal. Here, the subclass
Dog provides the implementation for the abstract method makeSound().

Key Points to Remember

• We use the abstract keyword to create abstract classes and methods.


• An abstract method doesn't have any implementation (method body).
• A class containing abstract methods should also be abstract.
• We cannot create objects of an abstract class.
• To implement features of an abstract class, we inherit subclasses from it and create
objects of the subclass.
• A subclass must override all abstract methods of an abstract class. However, if the
subclass is declared abstract, it's not mandatory to override abstract methods.

5.Interfaces in Java:-

An interface in Java is a blueprint of a class. The interface in Java is a mechanism to


achieve abstraction. There can be only abstract methods in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritance in Java. In other words, we can say
that interfaces can have abstract methods and variables. It cannot have a method body. Java
Interface also represents the IS-A relationship.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritances.
o It can be used to achieve loose coupling.

❖ Declare an interface:
An interface is declared by using the interface keyword. It provides total abstraction ,
means all the methods in an interface are declared with the empty body, and all the fields are
public, static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Eg:
// interface
interfaceAnimal{
publicvoidanimalSound();// interface method (does not have a body)
publicvoidrun();// interface method (does not have a body)
}

JAGAN’S DEGREE COLLEGE Page 75


II B.Sc(M.S.C.S/M.P.C.S)

To access the interface methods, the interface must be "implemented" by another class
with the implements keyword (instead of extends). The body of the interface method is
provided by the "implement" class:

Example program:
// Interface
interfaceAnimal{
publicvoidanimalSound();// interface method (does not have a body)
publicvoidsleep();// interface method (does not have a body)
}
// Pig "implements" the Animal interface
classPigimplementsAnimal{
publicvoidanimalSound(){
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
publicvoidsleep(){
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
classMyMainClass{
publicstaticvoidmain(String[] args){
Pig myPig =newPig();// Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
❖ Rules for creating interface:

1. Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
2. Interface methods do not have a body - the body is provided by the "implement" class
3. On implementation of an interface, we must override all of its methods
4. Interface methods are by default abstract and public
5. Interface attributes are by default public, static and final
6. An interface cannot contain a constructor (as it cannot be used to create objects)

6. Multiple inheritance in Java by interface:


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.

JAGAN’S DEGREE COLLEGE Page 76


II B.Sc(M.S.C.S/M.P.C.S)

❖ Extending Interfaces: Like classes, interfaces can be extended that is an interface can
be interfaced from other interface. A sub interface will inherits all the members from
super interface as similar to classes. This is achieved by using keyword “extends”. The
general form of defining a sub interface from super interface is as follows:
Syntax:
Interfacename2 extends name1
{
Body of sub interfacename 2
}
Eg: interface A
{
}
interface B extends A
{
}
• In the above example ”interface B” is created from “interface A”. So the properties of interface
A are inherited into interface B
• In java multiple inheritance can be implemented on interfaces that is creating a sub interface
by using more than one interface.
Eg: interface A
{
}
interface B
{
}
interface C extends A,B
{
…………
…………
}
In the above example interface C is created from interface A and interface B. So the members
of interface A and interface B are inherited into interface C

Example program:

JAGAN’S DEGREE COLLEGE Page 77


II B.Sc(M.S.C.S/M.P.C.S)

interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
public void funcB() {
System.out.println("This is funcB");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}
}
Output
This is funcA
This is funcB

❖ Implementing interfaces:
Any class can implement an interface. The class must be implemented with all the abstract
methods of that interface. Otherwise the class will become an abstract class.
Syntax:
class CName implements IName
{
Body of the class
}
• In the above syntax “implements” is a keyword “CName” represents class name,”IName”
represents interface name
• A class can implement any number of interfaces. When a class can implementing more than
one interface. The interface names are separated with comma operator
Eg:
interface area
{
final static float PI=3.144f;
public float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{
return x*y;
}
}

JAGAN’S DEGREE COLLEGE Page 78


II B.Sc(M.S.C.S/M.P.C.S)

class circle implements area


{
public float compute(float x,float y)
{
return PI*x*x;
}
}
class test
{
public static void main (String args[ ])
{
rectangle r=new rectangle();
circle c=new circle();
area a;
a=r;
System.out.println("area of rectangle="+a.compute(10,20));
a=c;
System.out.println("area of circle="+a.compute(10,0));
}
}
Output:
Area of rectangle=200.0
Area of circle=314.4

7.Exception handling in Java:


Exception: An exception is a condition that is caused by a run time error in the program. When
the java interpreter finds an error it creates an exception object and throws it. If we want to
continue the program execution we should try to catch the exception object and process it. This
process is known as exception handling
The process of exception handling is to direct and report exceptional conditions so that
appropriate action can be taken. The basic concepts of exception handling are throwing an
exception and catching it.
The general form of exception handling is as follows
There are 5 keywords used in java exception handling
1. try
2. catch
3. finally
4. throw
5. throws
❖ try and catch statements:
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.

JAGAN’S DEGREE COLLEGE Page 79


II B.Sc(M.S.C.S/M.P.C.S)

Syntax:
try
{
……
…..
The statement that generates an exception
…….
…..
}
catch(ExceptionType)
{
…….
………
The statements that Handle exception
…….
…..
}
In the above syntax the try block can have one or more statements that may
generates an exception. If any statement generates an exception the remaining statements in try
block are skipped and execution jumps to the catch block.
The catch block can have one or more statements that process the exception. The
catch statement has one argument which refers to an exception type. If the catch statement then
the statements in the catch block will be executed otherwise the exception will terminate.

Eg:
/* usage of exception*/
class Example
{
public static void main(String args[ ])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
y=a/(b+c);
System.out.println(“Y=”+y);
}
}
Output:

JAGAN’S DEGREE COLLEGE Page 80


II B.Sc(M.S.C.S/M.P.C.S)

Division by zero
Y=1
❖ Multiple catch statements:
It is possible to have more than one catch statement in the catch block. The syntax
for multiple catch statement is as follows.
syntax:
try
{
Statements;
}
catch(ExceptionType1 e)
{
Statements;
}
catch(ExceptionType2 e)
{
Statements;
}
catch(ExceptionTypen e)
{
Statements ;
}
When we try block statements generates an exception the exception object compared with
exception type in multiple catch statements. If a match is found the statements in that catch
block will be executed. If no match is found the program execution terminates immediately.
❖ finally statement:
Java supports finally statement that can be used to handle an exception
that is not caught by any of the previous catch statements. Finally statements can be used to
handle any exception generated within a try block. It may be added immediately after the try
block or after the last catch block as shown below.
Syntax 1: Syntax 2:
try try
{ {
……. ………..
…… }
} catch(ExceptionType1 e)
finally {
{ …….
…… }
…… catch(ExceptionType2 e)
} {
…….
}
finally
{
…….
……..

JAGAN’S DEGREE COLLEGE Page 81


II B.Sc(M.S.C.S/M.P.C.S)

Example:

public class MyClass {


public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Output:

Somethingwentwrong.
The 'try catch' is finished.

❖ The throw keyword:-


The throw statement allows us to create a custom error. The throw statement is used
together with an exception type. There are many exception types available in
java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Sec
urityException, etc:

The throw keyword is used to explicitly throw a single exception.When an


exception is thrown, the flow of program execution transfers from the try block to the catch
block. We use the throw keyword within a method.

Its syntax is:


throw throwableObject;

Ex:
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else

JAGAN’S DEGREE COLLEGE Page 82


II B.Sc(M.S.C.S/M.P.C.S)

System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

❖ The throws keyword:


throws is a keyword in Java which is used in the signature of method to indicate
that this method might throw one of the listed type exceptions. The caller to these methods
has to handle the exception using a try-catch block.
Syntax:
type method_name(parameter_list)throws exception_list
{
// definition of method
}

Example:
classTest
{
staticvoidcheck()throwsArithmeticException
{
System.out.println("Inside check function");
thrownewArithmeticException("demo");
}

publicstaticvoidmain(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught"+ e);
}
}
}

Output:

Inside check function


caughtjava.lang.ArithmeticException: demo

Difference between throw and throws


Throw throws

throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.

JAGAN’S DEGREE COLLEGE Page 83


II B.Sc(M.S.C.S/M.P.C.S)

throw keyword is followed by an instance of throws keyword is followed by one or more


Throwable class or one of its sub-classes. Exception class names separated by commas.

throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).

We cannot throw multiple exceptions using We can declare multiple exceptions (separated by
throw keyword. commas) using throws keyword.

❖ Finally clause

A finally keyword is used to create a block of code that follows a try block. A
finally block of code is always executed whether an exception has occurred or not. Using a
finally block, it lets you run any cleanup type statements that you want to execute, no matter
what happens in the protected code. A finally block appears at the end of catch block.

Example finally Block


In this example, we are using finally block along with try block. This program
throws an exception and due to exception, program terminates its execution but see code
written inside the finally block executed. It is because of nature of finally block that guarantees
to execute the code.

Ex
classDemo
{
publicstaticvoidmain(String[] args)
{
int a[]=newint[2];
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception caught");
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Output:
Exception caught
finally is always executed.

8. Types of Exceptions:
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these

JAGAN’S DEGREE COLLEGE Page 84


II B.Sc(M.S.C.S/M.P.C.S)

exceptions are to be handled. An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.

• A user has entered an invalid data.


• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has
run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions

❖ Built-in Exception

Exceptions that are already available in Java libraries are referred to as built-in
exception. These exceptions are able to define the error situation so that we can understand the
reason of getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.

Below is the list of important built-in exceptions in Java.

1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.
3. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
4. IOException
It is thrown when an input-output operation failed or interrupted.
5. NoSuchMethodException
It is thrown when accessing a method which is not found.
6. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
7. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.

JAGAN’S DEGREE COLLEGE Page 85


II B.Sc(M.S.C.S/M.P.C.S)

8. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or greater
than the size of the string

➢ Checked exceptions − A checked exception is an exception that is checked (notified)


by the compiler at compilation-time, these are also called as compile time exceptions.
These exceptions cannot simply be ignored, the programmer should take care of
(handle) these exceptions.

For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.

Example
import java.io.File;
import java.io.FileReader;

publicclassFilenotFound_Demo{

publicstaticvoid main(String args[]){


File file =newFile("E://file.txt");
FileReader fr =newFileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.

Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException;
must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you can
observe that the compiler notifies to handle IOException, along with FileNotFoundException.
➢ Unchecked exceptions − An unchecked exception is an exception that occurs at the
time of execution. These are also called as Runtime Exceptions. These include
programming bugs, such as logic errors or improper use of an API. Runtime exceptions
are ignored at the time of compilation.

For example, if you have declared an array of size 5 in your program, and trying to call the 6 th
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

Example
publicclassUnchecked_Demo{

publicstaticvoid main(String args[]){


int num[]={1,2,3,4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following exception.

JAGAN’S DEGREE COLLEGE Page 86


II B.Sc(M.S.C.S/M.P.C.S)

Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8

Example:Arithmeticexception

classArithmeticException_Demo
{
publicstaticvoidmain(String args[])
{
try{
inta = 30, b = 0;
intc = a/b; // cannot divide by zero
System.out.println ("Result = "+ c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
Output:

Can't divide a number by 0

❖ User-defined Exception

In Java, we can write our own exception class by extends the Exception class.
We can throw our own exception on a particular condition using the throw keyword. For
creating a user-defined exception, we should have basic knowledge of the try-catch block and
throw keyword.
Syntax:

class MyException extends Exception

To raise exception of user-defined type, we need to create an object to his exception class and
throw it using throw clause, as:

Ex:
MyException me = new MyException(“Exception details”);
throw me;

9.PACKAGES IN JAVA:

A package in Java is used to group related classes. Think of it as a folder in a file


directory. We use packages to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create our own packages)

JAGAN’S DEGREE COLLEGE Page 87


II B.Sc(M.S.C.S/M.P.C.S)

1. Built-in Packages:

The Java API is a library of prewritten classes that are free to use, included in the Java
Development Environment. These packages consist of a large number of classes which are a
part of Java API. Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).

6) java.net: Contain classes for supporting networking operations.

The library is divided into packages and classes. Meaning we can either import
a single class (along with its methods and attributes), or a whole package that contain all the
classes that belong to the specified package.
To use a class or a package from the library, we need to use the import keyword:
Syntax:-
importpackage.name.Class;// Import a single class
importpackage.name.*;// Import the whole package

Import a Class
If we find a class we want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example
importjava.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of
the java.util package.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:

Example:
Using the Scanner class to get user input:
importjava.util.Scanner;// import the Scanner class

classMyClass{
publicstaticvoidmain(String[] args){
Scanner myObj =newScanner(System.in);
String userName;

JAGAN’S DEGREE COLLEGE Page 88


II B.Sc(M.S.C.S/M.P.C.S)

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: "+ userName);


}
}

• Import a Package:
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date and time
facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign ( *). The following
example will import ALL the classes in the java.util package:

Example
importjava.util.*;

2.User-defined Packages:

To create our own package, we need to understand that Java uses a file system directory to
store them. Just like folders on our computer:
Example
└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack;

classMyPackageClass{
publicstaticvoidmain(String[] args){
System.out.println("This is my package!");
}
}
Save the file as MyPackageClass.java, and compile it:
C:\Users\Your Name>javac MyPackageClass.java
Then compile the package:
C:\Users\Your Name>javac -d . MyPackageClass.java
This forces the compiler to create the "mypack" package.
The -d keyword specifies the destination for where to save the class file. we
can use any directory name, like c:/user (windows), or, if we want to keep the package within
the same directory, we can use the dot sign ".", like in the example above.

JAGAN’S DEGREE COLLEGE Page 89


II B.Sc(M.S.C.S/M.P.C.S)

Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called
"mypack".
To run the MyPackageClass.java file, write the following:
C:\Users\Your Name>java mypack.MyPackageClass
The output will be:
This is my package!

❖ Advantages of Java Package:


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) Packages provide reusability of code.
5) To bundle classes and interfaces.
6) We can create our own Package or extend already available Package.

10. How to access package from another package?

There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }

JAGAN’S DEGREE COLLEGE Page 90


II B.Sc(M.S.C.S/M.P.C.S)

Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

1. package mypack; //save by B.java


2.
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }

Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name every time
when you are accessing the class or interface.It is generally used when two packages have same
class name e.g. java.util and java.sql packages contain Date class.

Example of package by import fully qualified name

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();

JAGAN’S DEGREE COLLEGE Page 91


II B.Sc(M.S.C.S/M.P.C.S)

7. }
8. }

Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as
well.

❖ Subpackage in java:

Package inside the package is called the subpackage. It should be created to


categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes represent
a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes in
io package, Server and ServerSocket classes in net packages and so on.

Syntax: The standard of defining package is domain.company.package

e.g. com.javatpoint.bean or org.sssit.dao.

Example of Subpackage

1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

❖ ACCESSING A ACESS SPECIFIERS IN PACKAGES:


Access Specifier:Specifies the scope of the data members, class and methods.
➢ private members of the class are available with in the class only. The scope of private
members of the class is “CLASS SCOPE”.

➢ public members of the class are available anywhere .The scope of public members of
the class is "GLOBAL SCOPE".

JAGAN’S DEGREE COLLEGE Page 92


II B.Sc(M.S.C.S/M.P.C.S)

➢ default members of the class are available with in the class, outside the class and in its
sub class of same package. It is not available outside the package. So the scope of
default members of the class is "PACKAGE SCOPE".

➢ protected members of the class are available with in the class, outside the class and in
its sub class of same package and also available to subclasses in different package also.

Class Member Access Private No Modifier Protected Public


Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package sub class No No Yes Yes
Different package non-subclass No No No Yes

UNIT–IV

THREADS in JAVA:
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate
path of execution. Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads. It uses a shared memory area. Thread is nothing but a process executed
by the computer. Executing of two or more Threads simultaneously by a single computer is
known as multi Threading.
❖ Creating Threads:
There are two methods to create Threads in java
1. Extending Thread class
2. Implementing runnable interface

1.Extending Thread class:


By extending the class java.lang.Thread, it includes the following steps
➢ Define the class that extending the Thread class
➢ Over ride the run() method by placing the code of the process
➢ Create a Thread class object
➢ Call the start() method to invoke run () method
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Some methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void suspend(): is used to suspend the thread(depricated).
5. public void resume(): is used to resume the suspended thread(depricated).
6. public void stop(): is used to stop the thread(depricated).
2. Implementing runnable interface:
➢ Define a class that implements runnable interface
➢ Implement the run () method

JAGAN’S DEGREE COLLEGE Page 93


II B.Sc(M.S.C.S/M.P.C.S)

➢ Create a Thread class object and pass newly created implementation class object as a
parameter
➢ Call the start() method to invoke run() method.

❖ Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

Ex:1) Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...

Ex2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.
So you need to explicitely create Thread class object.We are passing the object of your class
that implements Runnable so that your class run() method may execute.

❖ 3.Stopping and blocking a Thread:

➢ Stopping a Thread:
Whenever we want to stop a Thread running further we may do by calling its stop() method
Ex: obj.stop();
Here obj is a Thread object
This statement causes the Thread to move to the dead state .a Thread will also move to the dead
state automatically when it reaches the end of its method. The stop() method may be used when
the thread to be stopped before its completion.

➢ Blocking a Thread:

JAGAN’S DEGREE COLLEGE Page 94


II B.Sc(M.S.C.S/M.P.C.S)

A Thread can also be temporarily suspended or blocked from enterning from entering into the
runnable and running state by using following Thread methods
1.sleep()
2.suspend()
3.wait()
These methods cause state when the specified time is elapsed in the case of sleep() the
resume() method is invoked in the case of suspend() and the notify() method is in called in the
case of wait() method.

single task using a thread:


If we need to perform a single task using multiple threads then we need to use only
one/single run() method.

Example

In this example, we simply extend the thread and perform a single task using multiple
threads.

1. class MultithreadEx1 extends Thread


2. {
3. public void run()
4. {
5. System.out.println("Start task one");
6. }
7. public static void main(String args[])
8. {
9. MultithreadEx1 th1 = new MultithreadEx1();
10. MultithreadEx1 th2 = new MultithreadEx1();
11. MultithreadEx1 th3 = new MultithreadEx1();
12. th1.start();
13. th2.start();
14. th3.start();
15. }
16. }

Output

JAGAN’S DEGREE COLLEGE Page 95


II B.Sc(M.S.C.S/M.P.C.S)

Multi tasking using threads:


To perform multiple tasks by multiple threads, we need to use multiple run() methods

Example: Multithreading in JAVA

class SleepThread extends Thread {


//run method for thread
public void run() {
for(int i=1;i<5;i++) {
try {
//call sleep method of thread
Thread.sleep(1000);
}catch(InterruptedException e){System.out.println(e);}
//print current thread instance with loop variable
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
class Main{
public static void main(String args[])
{
//create two thread instances
SleepThread thread_1 = new SleepThread();
SleepThread thread_2 = new SleepThread();
//start threads one by one
thread_1.start();
thread_2.start();
}
}

Output:

JAGAN’S DEGREE COLLEGE Page 96


II B.Sc(M.S.C.S/M.P.C.S)

4. Thread life cycle:


A thread can be in one of the five states. .But, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no running
state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New Born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state(Terminated)

1. NewBorn state:
When we create a Thread object then Thread is in new born state .at this state we can do only
one of the following things
➢ Scheduled it for running using start() method
➢ Kill it using stop() method

2. Runnable state: In this state the Thread Is ready for execution and is waiting for the
availability of the processor. That is the Thread has joined the queue of Threads.

3. Running state: Running state means that the processor has given its time to the Thread for
execution. The running Thread may stop its execution by calling any one of the following
methods
➢ suspend (): The Threads has been suspended using suspend”() method and again starts
with resume() method.

JAGAN’S DEGREE COLLEGE Page 97


II B.Sc(M.S.C.S/M.P.C.S)

➢ sleep(): The Threads has been sleep for a specified time using sleep() method and
execution continues after the specified time
➢ wait():the Threads has been wait for occurring of some events using wait() method and
again starts with the notify() method
4. Blocked state: a Thread is said to be blocked state whenever the Thread is suspended or
sleeping or waiting.
5. Dead state: A Thread is said to be dead state when its run() method completed the execution
or by calling stop() method.

5. Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
thread is waiting for an object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread. Since, both threads are waiting for
each other to release the lock, the condition is called deadlock.

6. Inter-thread communication in Java


Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.Cooperation (Inter-thread
communication) is a mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()

1) wait() method
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.

Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.

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

JAGAN’S DEGREE COLLEGE Page 98


II B.Sc(M.S.C.S/M.P.C.S)

Syntax: public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()

Daemon Thread in Java:

Daemon thread in java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer
etc.

You can see all the detail by typing the jconsole in the command prompt. Thejconsole
tool provides information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java:

o It provides services to user threads for background supporting


tasks. It hasno role in life than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?

The sole purpose of the daemon thread is that it provides services


to user thread for background supporting task. If there is no user thread,
why should JVM keep running this thread. That is why JVM terminates
the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class:

The java.lang.Thread class provides two methods for java daemon thread
No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as


status) daemon thread or user thread.

2) public boolean isDaemon() is used to check that current is


daemon.

JAGAN’S DEGREE COLLEGE Page 99


II B.Sc(M.S.C.S/M.P.C.S)

Simple example of Daemon thread in java:

1. public class TestDaemonThread1 extends Thread{


2. public void run(){
3. if(Thread.currentThread().isDaemon()){//checking for daemon thread
4. System.out.println("daem
on thread work");5. }
6. else{
7. System.out.println("u
ser thread work");8.
}
9. }
10. public static void main(String[] args){
11. TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
12. TestDaemonThread1 t2=new TestDaemonThread1();
13. TestDaemonThread1 t3=new
TestDaemonThread1();14.
15. t1.setDaemon(true);//now t1 is
daemon thread16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. . }
21. }

Output

daemon thread work


user thread work user
thread work
.
Note: If you want to make a user thread as Daemon, it must not be startedotherwise it
will throw IllegalThreadStateException.
Thread Group in Java:

Java provides a convenient way to group multiple threads in a single object. In such
way, we can suspend, resume or interrupt group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class.

A ThreadGroup represents a set of threads. A thread group can


also include the other thread group. The thread group creates a tree in
which every thread group except the initial thread group has a parent.

JAGAN’S DEGREE COLLEGE Page 100


II B.Sc(M.S.C.S/M.P.C.S)

A thread is allowed to access information about its own thread


group, but it cannot access the information about its thread group's parent
thread group or any other thread groups.

Constructors of ThreadGroup class:

There are only two constructors of ThreadGroup class.

N.o Constructor Description

1) ThreadGroup(String name) creates a thread group with


given name.

2) ThreadGroup(ThreadGroup parent, creates a thread group with


String name) given parent group and name.

Let's see a code to group multiple threads.


1. ThreadGroup tg1 = new ThreadGroup("Group A");
2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread
group name, MyRunnable is the class that implements Runnable interface
and "one", "two" and "three" are the thread names.

Now we can interrupt all threads by a single line of code only.

1. Thread.currentThread().getThreadGroup().interrupt();

ThreadGroup Example:

1. public class ThreadGroupDemo implements Runnable{


2. public void run() {
3. System.out.println(Thread.currentThread().g
etName());4. }
5. public static void main(String[] args) {
6. ThreadGroupDemo runnable = new ThreadGroupDemo();
7. ThreadGroup tg1 = new ThreadGroup("Parent
ThreadGroup");8.
9. Thread t1 = new Thread(tg1, runnable,"one");
10. t1.start();

JAGAN’S DEGREE COLLEGE Page 101


II B.Sc(M.S.C.S/M.P.C.S)

11. Thread t2 = new Thread(tg1, runnable,"two");


12. t2.start();
13. Thread t3 = new Thread(tg1, runnable,"three");
14. t 3.start();
15. System.out.println("Thread Group Name: "+tg1.getName());
16. tg1.list();
17. }
18. }
Output:
One
Two
Three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent
ThreadGroup,maxpri=10]
Thread[one,5,Par
ent
ThreadGroup]
Thread[two,5,Par
eent
ThreadGroup]
Thread[three,5,P
arent
ThreadGroup]
Deadlock in java:
Deadlock in java is a part of multithreading. Deadlock can occur
in a situationwhen a thread is waiting for an object lock, that is acquired
by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.

Example of Deadlock in java:

public class TestDeadlockExample1

public static void main(String[] args)

JAGAN’S DEGREE COLLEGE Page 102


II B.Sc(M.S.C.S/M.P.C.S)

final String resource1 = "ratan jaiswal";

final String resource2 = "vimal jaiswal";

// t1 tries to lock resource1 then resource2

Thread t1 = new Thread()

public void run()

{ synchronized (resource1)

System.out.println("Thread 1: locked resource


1");

try {
Thread.sleep(100);
}
catch (Exception e) {}
synchronized (resource2)
{
System.out.println("Thread 1: locked resource 2");

}
// t2 tries to lock resource2 then resource1

Thread t2 = new Thread() {

public void run() {

synchronized (resource2) {

System.out.println("Thread 2: locked
resource 2");

try { Thread.sleep(100);} catch (Exception


e) {}
synchronized (resource1) {

System.out.println("Thread 2: locked resource 1");

}
}
};
t1.start();

JAGAN’S DEGREE COLLEGE Page 103


II B.Sc(M.S.C.S/M.P.C.S)

t2.start();

}
}

Output: Thread 1: locked resource 1


Thread 2: locked resource

7. Java Thread Priorities


Priority of a thread describes how early it gets execution and selected by the thread
scheduler. In Java, when we create a thread, always a priority is assigned to it. In a
Multithreading environment, the processor assigns a priority to a thread scheduler. The priority
is given by the JVM or by the programmer itself explicitly. The range of the priority is between
1 to 10 and there are three constant variables which are static and used to fetch priority of a
Thread. They are as following:

1. public static int MIN_PRIORITY


It holds the minimum priority that can be given to a thread. The value for this is 1.

2. public static int NORM_PRIORITY


It is the default priority that is given to a thread if it is not defined. The value for this is 0.

3. public static int MAX_PRIORITY


It is the maximum priority that can be given to a thread. The value for this is 10.
Get and Set methods in Thread priority
1. public final intgetPriority()
In Java, getPriority() method is in java.lang.Thread package. it is used to get the priority of a
thread.

2. public final void setPriority(intnewPriority)


In Java setPriority(intnewPriority) method is in java.lang.Thread package. It is used
to set the priority of a thread. The setPriority() method throws IllegalArgumentException if the
value of new priority is above minimum and maximum limit.

Example:classMyThreadextendsThread
{
publicvoidrun()
{
System.out.println("Thread Running...");
}

publicstaticvoidmain(String[]args)

JAGAN’S DEGREE COLLEGE Page 104


II B.Sc(M.S.C.S/M.P.C.S)

{
MyThread p1 =newMyThread();
MyThread p2 =newMyThread();
MyThread p3 =newMyThread();
p1.start();
System.out.println("P1 thread priority : "+
p1.getPriority());
System.out.println("P2 thread priority : "+
p2.getPriority());
System.out.println("P3 thread priority : "+
p3.getPriority());

}
}

Output:

P1 thread priority : 5
Thread Running...
P2 thread priority : 5
P3 thread priority : 5

UNIT–V
APPLETS:

An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application,
including the following −

❖ An applet is a Java class that extends the java.applet.Applet class.


❖ A main() method is not invoked on an applet, and an applet class will not define main().
❖ Applets are designed to be embedded within an HTML page.
❖ When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
❖ A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
❖ The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
❖ Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.

JAGAN’S DEGREE COLLEGE Page 105


II B.Sc(M.S.C.S/M.P.C.S)

❖ Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.

Use of applets:

Java applets are used to provide interactive features to web applications and can be executed
by browsers for many platforms. They are small, portable Java programs embedded in HTML
pages and can run automatically when the pages are viewed. Malware authors have used Java
applets as a vehicle for attack. Most Web browsers, however, can be configured so that these
applets do not execute - sometimes by simply changing browser security settings to "high."

❖ Life Cycle of an Applet:

The methods in the Applet class gives you the framework on which you build any serious
applet

When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

Let’s look more closely at these methods.

• init − This method is intended for whatever initialization is needed for your applet. It
is called after the param tags inside the applet tag have been processed.

JAGAN’S DEGREE COLLEGE Page 106


II B.Sc(M.S.C.S/M.P.C.S)

• start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
• stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java −

importjava.applet.*;
importjava.awt.*;

publicclassHelloWorldAppletextendsApplet{
publicvoid paint (Graphics g){
g.drawString("Hello World",25,50);
}
}

These import statements bring the classes into the scope of our applet class −

• java.applet.Applet
• java.awt.Graphics

Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.

❖ The Applet Class:

Every applet is an extension of the java.applet.Applet class. The base Applet


class provides methods that a derived Applet class may call to obtain information and services
from the browser context.
These include methods that do the following −
• Get applet parameters
• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet

JAGAN’S DEGREE COLLEGE Page 107


II B.Sc(M.S.C.S/M.P.C.S)

Additionally, the Applet class provides an interface by which the viewer or


browser obtains information about the applet and controls the applet's execution. The viewer
may −

• Request information about the author, version, and copyright of the applet
• Request a description of the parameters the applet recognizes
• Initialize the applet
• Destroy the applet
• Start the applet's execution
• Stop the applet's execution

The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.The "Hello, World" applet is complete as it
stands. The only method overridden is the paint method.

❖ Invoking an Applet: or Applet tag or <applet> tag

An applet may be invoked by embedding directives in an HTML file and viewing


the file through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Following
is an example that invokes the "Hello, World" applet −

<html>
<title>The Hello, World Applet</title>
<hr>
<appletcode="HelloWorldApplet.class"width="320"height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>

Note − You can refer to HTML Applet Tag to understand more about calling applet from
HTML.

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width
and height are also required to specify the initial size of the panel in which an applet runs. The
applet directive must be closed with an </applet> tag.

Example program:

importjava.applet.*;// used
//to access showStatus()
importjava.awt.*;//Graphic
//class is available in this package
importjava.util.Date;// used
//to access Date object
public class GFG extends Applet
{

JAGAN’S DEGREE COLLEGE Page 108


II B.Sc(M.S.C.S/M.P.C.S)

public void paint(Graphics g)


{
Date dt = new Date();
super.showStatus("Today is" + dt);
//in this line, super keyword is
// avoidable too.
}
}

Save as: GFG.java

Save as: GFG.HTML

<html>

<applet code="GFG123" height="100" width="100">

</applet>

</html>

Run as:Javac GFG.java

appletviewer GFG.html

Output:

JAGAN’S DEGREE COLLEGE Page 109


II B.Sc(M.S.C.S/M.P.C.S)

❖ Swing components in java

Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing
window-based applications. Java Swing is lightweight and platform-independent that contains
various components and container classes

In Java Swing, there are several components like a scroll bar, button, text field, text area,
checkbox, radio button, etc. These components jointly form a GUI that offers a rich set of
functionalities and allows high-level customization.

Below are the top components of swing in java are:


 JButton
We use JButton class to create a push button on the UI. The button can include some
display text or images. It yields an event when clicked and double-clicked. We can
implement a JButton in the application by calling one of its constructors.

Syntax:
JButton okBtn = new JButton(“Click”);

This constructor returns a button with the text Click on it.


JButton homeBtn = new JButton(carIcon);

Returns a button with a car Icon on it.


JButton homeBtn2 = new JButton(carIcon, “Car”);

Returns a button with the car icon and text as Car.

Display:

JAGAN’S DEGREE COLLEGE Page 110


II B.Sc(M.S.C.S/M.P.C.S)

 JLabel
We use JLabel class to render a read-only text label or images on the UI. It does not
generate any event.

Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);

This constructor returns a label with specified text.


JLabel imgLabel = new JLabel(carIcon);

It returns a label with a car icon.

The JLabel Contains four constructors. They are as follows:


1. JLabel()
2. JLabel(String s)
3. JLabel(Icon i)
4. JLabel(String s, Icon i, int horizontalAlignment)

Display:

 JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted
text in the box. We can initialize the text field by calling its constructor and passing an
optional integer parameter. This parameter sets the box width measured by the number of
columns. Also, it does not limit the number of characters that can be input into the box.
Syntax:
JTextField txtBox = new JTextField(50);

It is the most widely used text component. It has three constructors:

JAGAN’S DEGREE COLLEGE Page 111


II B.Sc(M.S.C.S/M.P.C.S)

1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)

Note: cols represent the number of columns in the text field.

Display:

 JCheckBox
The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on
and off. On selecting, the state is set to "on," and a small tick is displayed inside the box.
Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);

It returns a checkbox with the label Pepperoni pizza. Notice the second parameter in
the constructor. It is a boolean value that denotes the default state of the check-box. True
means the check-box defaults to the "on" state.

Display:

 JRadioButton
A radio button is a group of related buttons from which we can select only one. We use
JRadioButton class to create a radio button in Frames and render a group of radio buttons in
the UI. Users can select one choice from the group.

Syntax:
JRadioButton jrb = new JRadioButton("Easy");

Display:

JAGAN’S DEGREE COLLEGE Page 112


II B.Sc(M.S.C.S/M.P.C.S)

❖ Applet with swing components


we have created the applets based on AWT(Abstract Window Toolkit) by
extending the Applet class of the awt package. We can even create applets based on
the Swing package. In order to create such applets, we must extend JApplet class of
the swing package. JApplet extends Applet class, hence all the features of Applet
class are available in JApplet as well, including JApplet's own Swing based features.
Swing applets provides an easier to use user interface than AWT applets.

 Creating a swing apple


• In the upcoming code, first, we have created a swing applet by extending JApplet class
and we have added a JPanel to it.

• Next, we have created a class B, which has extended JPanel class of Swing package and
have also implemented ActionListener interace to listen to the button click event
generated when buttons added to JPanel are clicked.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="Applet21" width="500" height="200">
</applet>
*/

public class Applet21 extends JApplet


{

public void init()


{
add(new B()); //Adding a JPanel to this Swing applet
}

class B extends JPanel implements ActionListener


{

JAGAN’S DEGREE COLLEGE Page 113


II B.Sc(M.S.C.S/M.P.C.S)

JLabel jb;
JButton Box2, box2, box3, box4;
String str;

B()
{
jb= new JLabel("Welcome, please click on any button to unbox some interesting
knowledge -");
Box2 = new JButton("Box2");
box2 = new JButton("Box2");
box3 = new JButton("Box3");
box4 = new JButton("Box4");

str ="";

setLayout(new FlowLayout());

add(jb);
add(Box2);
add(box2);
add(box3);
add(box4);

Box2.addActionListener(this);
box2.addActionListener(this);
box3.addActionListener(this);
box4.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getActionCommand().equals("Box2"))
{
str="Amazon is the largest tropical rain forest, covering 40% of the South
America Continent.";
repaint();
}

if(ae.getActionCommand().equals("Box2"))
{
str="The Mariana Trench is the deepest point in Earth's ocean, with depth of
over 10,994 metres.";
repaint();
}

if(ae.getActionCommand().equals("Box3"))
{

JAGAN’S DEGREE COLLEGE Page 114


II B.Sc(M.S.C.S/M.P.C.S)

str="The coldest temperature ever recorded was -128.6F in Antarctica, on July


21, 1983.";
repaint();
}
if(ae.getActionCommand().equals("Box4"))
{
str="The oldest person to climb Mt. Everent was Japanese Miura Yiuchiro, at
the age of 80.";
repaint();
}

}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(str, 2, 170);
}

Output-

In the applet shown above, four buttons are presented in the output. These buttons are
added to B class(which has extended JPanel). This JPanel is in turn added to our Swing applet
class, Applet21. Whenever a button is clicked, an interesting fact about the world is presented
to the user.
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.

Example of animation in applet:

import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {

Image picture;
JAGAN’S DEGREE COLLEGE Page 115
II B.Sc(M.S.C.S/M.P.C.S)

public void init() {


picture =getImage(getDocumentBase(),"bike_1.gif");
}

public void paint(Graphics g) {


for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);

try{Thread.sleep(100);}catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument of
drawImage() method of is ImageObserver object. The Component class implements ImageObserver interface. So
current class object would also be treated as ImageObserver because Applet class indirectly extends the Component
class.

myapplet.html

<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

❖ Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:

public String getParameter(String parameterName)

Example of using parameter in Applet:

JAGAN’S DEGREE COLLEGE Page 116


II B.Sc(M.S.C.S/M.P.C.S)

import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}

myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

What is a database server?

A database server is a type of hardware that runs database software. Database


software helps users or companies store, manage, retrieve, update or change files, information
logs and other forms of digital data. The two primary components of database servers are
back-end functions and client-facing services. The back end of a database server stores all the
digital files and information. Client-facing services allow the people or companies using that
database to access, modify, add to or monitor the data stored on the server.

A company can rent a database server from a provider to store its crucial business
information. Database server companies often use one server to provide services to multiple
clients. Many businesses decide to rent databases from providers because a database server
requires large memory and storage capabilities. Some businesses may also choose to own and
maintain their own database servers.

Types of database servers

There are multiple types of database servers, including:

JAGAN’S DEGREE COLLEGE Page 117


II B.Sc(M.S.C.S/M.P.C.S)

Centralized database servers: Centralized database servers operate from one specific
location. Larger companies may use a centralized database server to access the servers that
control, store, organize and back up their data directly.

Distributed database servers: Distributed database servers spread an organization's data


across multiple servers. Using more than one server to store company data can help make
accessing various digital processes and information faster and more reliable.

Operational database servers: Operational database servers function simultaneously,


allowing users to update the information on a database server immediately from any
authorized device within their network. An operational database can be a great option for
companies that use the information on their database to send communications between
employees.

Cloud database servers: A cloud database server connects users to their database server
through the internet. Many database server providers use cloud computing databases to give
users easy and fast access to their services.

7 examples of database servers

Here are some examples of database servers:

1. Microsoft SQL

One common database server is Microsoft (MS) SQL. SQL is a type of programming
language that organizes data for a DBMS. Both Windows and Linux computing systems and
devices can run and connect with MS SQL. Users can connect with data on Microsoft SQL
either locally or through the internet and at the same time as other users.

2. MySQL

MySQL uses relational database management systems (RDBMS), meaning it


organizes information and files based on how those files connect to each other. You can find
MySQL database systems in most industries. This is because MySQL is an open-source
project that offers many features, and it's widely compatible with other technologies.

3. MongoDB

MongoDB specializes in storing both structured and unstructured data. In the


computing field, structured data has defined patterns that make its information easy to search
and organize, while unstructured data doesn't. Typically, structured data consists only or
entirely of numerical information. Image files, social media posts, video files and digital
presentations are examples of unstructured data types on which companies rely.

JAGAN’S DEGREE COLLEGE Page 118


II B.Sc(M.S.C.S/M.P.C.S)

4. SQLite

SQLite is an open-source database server. Open-source means users can personalize


the software and code of SQLite to best fit the functions and needs of their organization.
SQLite also needs much less memory, storage and computing power than many other
database servers. This may make SQLite a great choice for organizations that want to access
their database servers through devices with less computing power, such as mobile phones or
tablets

5. PostgreSQL

PostgreSQL is a database server that provides quick database retrieval. PostgreSQL


allows users to customize functions through many programming languages, such as Java and
C++. This can make PostgreSQL a great option for organizations that need to personalize
their database server operations.

6. Microsoft Access

If a company frequently analyzes its data, it may consider using Microsoft Access as
its database service provider. MS Access helps users evaluate large amounts of data and
easily discover or report their findings to others. Many businesses with online stores use MS
Access to manage information about their clients and inventory. One benefit of using MS
Access is that it's easy for people new to database servers to get started, as it provides you
with a beginner's guide.

7. MariaDB

MariaDB is a database server that can efficiently use resources and process user
commands. It operates on many computing systems, including Mac, Windows and Linux.
MariaDB offers both various features, such as ways to encrypt your stored data.

Java Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5 following
steps.

In this example we are using MySql as the database. So we need to know following
informations for the mysql database:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

2. Connection URL: The connection URL for the mysql database


is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.

JAGAN’S DEGREE COLLEGE Page 119


II B.Sc(M.S.C.S/M.P.C.S)

3. Username: The default username for the mysql database is root.

4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create
database first.

1. create database sonoo;


2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and password both.

1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
To connect java application with the mysql database, mysqlconnector.jar file is required to
be loaded.

Two ways to load the jar file:


1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath

JAGAN’S DEGREE COLLEGE Page 120


II B.Sc(M.S.C.S/M.P.C.S)

1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:


Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

2) Set classpath:
There are two ways to set the classpath:

o temporary
o permanent

How to set the temporary classpath


open command prompt and write:

1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Register JDBC Driver

You must register the driver in your program before you use it. Registering the driver
is the process by which the Oracle driver's class file is loaded into the memory, so it can be
utilized as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver
in one of two ways.

Approach I - Class.forName()

The most common approach to register a driver is to use


Java's Class.forName() method, to dynamically load the driver's class file into memory, which
automatically registers it. This method is preferable because it allows you to make the driver
registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver −
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but then you'll
have to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {

JAGAN’S DEGREE COLLEGE Page 121


II B.Sc(M.S.C.S/M.P.C.S)

System.out.println("Error: unable to load driver class!");


System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}

Approach II - DriverManager.registerDriver()

The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant
JVM, such as the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database.

There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver

2. Native-API driver (partially java driver)

3. Network Protocol driver (fully java driver)

4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC

JAGAN’S DEGREE COLLEGE Page 122


II B.Sc(M.S.C.S/M.P.C.S)

bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged

because of thin driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.

Advantages:

o easy to use.

o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC function
calls.

o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method

calls into native calls of the database API. It is not written entirely in java.

JAGAN’S DEGREE COLLEGE Page 123


II B.Sc(M.S.C.S/M.P.C.S)

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.

o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

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

JAGAN’S DEGREE COLLEGE Page 124


II B.Sc(M.S.C.S/M.P.C.S)

Advantage:

o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.

o Requires database-specific coding to be done in the middle tier.

o Maintenance of Network Protocol driver becomes costly because it requires database-


specific coding to be done in the middle tier.

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

JAGAN’S DEGREE COLLEGE Page 125


II B.Sc(M.S.C.S/M.P.C.S)

Advantage:

o Better performance than all other drivers.

o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

Stored Procedures and Callable Statements

The CallableStatement interface provides methods to execute the stored procedures.


Since the JDBC API provides a stored procedure SQL escape syntax, you can call stored
procedures of all RDBMS in single standard way.

Creating a CallableStatement

You can create an object of the CallableStatement (interface) using


the prepareCall() method of the Connection interface. This method accepts a string
variable representing a query to call the stored procedure and returns
a CallableStatement object.
A Callable statement can have input parameters, output parameters or both. To pass
input parameters to the procedure call you can use place holder and set values to these
using the setter methods (setInt(), setString(), setFloat()) provided by the
CallableStatement interface.
Suppose you have a procedure name myProcedure in the database you can prepare a
callable statement as:

JAGAN’S DEGREE COLLEGE Page 126


II B.Sc(M.S.C.S/M.P.C.S)

//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");

Setting values to the input parameters

You can set values to the input parameters of the procedure call using the setter methods.
These accepts two arguments, one is an integer value representing the placement index
of the input parameter and, the other is a int or, String or, float etc… representing the value
you need to pass as input parameter to the procedure.
Note: Instead of index you can also pass the name of the parameter in String format.

cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");

Executing the Callable Statement

Once you have created the CallableStatement object you can execute it using one of
the execute() method.

cstmt.execute();
Example
Suppose we have a table named Employee in the MySQL database with the following
data:

+---------+--------+----------------+
| Name | Salary | Location |
+---------+--------+----------------+
| Amit | 30000 | Hyderabad |
| Kalyan | 40000 | Vishakhapatnam |
| Renuka | 50000 | Delhi |
| Archana | 15000 | Mumbai |
+---------+--------+----------------+
And we have created a procedure named myProcedure to insert values in to this table
as shown below:

Create procedure myProcedure (IN name VARCHAR(30), IN sal INT, IN loc


VARCHAR(45))
-> BEGIN
-> INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc);
-> END //

JAGAN’S DEGREE COLLEGE Page 127


II B.Sc(M.S.C.S/M.P.C.S)

Following is a JDBC example which inserts new records into the Employee table by
calling the above created procedure, using a callable statement.

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CallableStatementExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

//Getting the connection


String mysqlUrl = "jdbc:mysql://localhost/testdb";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Preparing a CallableStateement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");

cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");

cstmt.setString(1, "Kalyan");
cstmt.setInt(2, 4000);
cstmt.setString(3, "Vishakhapatnam");

cstmt.setString(1, "Rukmini");
cstmt.setInt(2, 5000);
cstmt.setString(3, "Delhi");

cstmt.setString(1, "Archana");
cstmt.setInt(2, 15000);
cstmt.setString(3, "Mumbai");

JAGAN’S DEGREE COLLEGE Page 128


II B.Sc(M.S.C.S/M.P.C.S)

cstmt.execute();
System.out.println("Rows inserted ....");
}
}
Output

Connection established......
Rows inserted ....
If you retrieve the contents of the Employee table using the select query, you can
observe newly added records as shown below:

mysql> select * from employee;


+---------+--------+----------------+
| Name | Salary | Location |
+---------+--------+----------------+
| Amit | 30000 | Hyderabad |
| Kalyan | 40000 | Vishakhapatnam |
| Renuka | 50000 | Delhi |
| Archana | 15000 | Mumbai |
| Raghav | 3000 | Hyderabad |
| Raghav | 3000 | Hyderabad |
| Kalyan | 4000 | Vishakhapatnam |
| Rukmini | 5000 | Delhi |
| Archana | 15000 | Mumbai |
+---------+--------+----------------+
9 rows in set (0.00 sec)

ResultSet interface

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:

1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


2. ResultSet.CONCUR_UPDATABLE);

JAGAN’S DEGREE COLLEGE Page 129


II B.Sc(M.S.C.S/M.P.C.S)

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next
from the current position.

2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean absolute(int row): is used to move the cursor to the specified row number in
the ResultSet object.

6) public boolean relative(int row): is used to move the cursor to the relative row number in
the ResultSet object, it may be positive or negative.

7) public int getInt(int columnIndex): is used to return the data of specified column index
of the current row as int.

8) public int getInt(String columnName): is used to return the data of specified column name of
the current row as int.

9) public String getString(int columnIndex): is used to return the data of specified column index
of
the current row as String.

10) public String getString(String is used to return the data of specified column name of
columnName): the current row as String.

Example of Scrollable ResultSet

Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");

JAGAN’S DEGREE COLLEGE Page 130


II B.Sc(M.S.C.S/M.P.C.S)

7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");

9. //getting the record of 3rd row


10. rs.absolute(3);
11. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
12.
13. con.close();
14. }}

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement.

Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

JAGAN’S DEGREE COLLEGE Page 131


II B.Sc(M.S.C.S/M.P.C.S)

Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given parameter inde

public void setString(int paramIndex, String value) sets the String value to the given parameter index

public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) sets the double value to the given parameter inde

public int executeUpdate() executes the query. It is used for create, drop,

insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an

instance of ResultSet.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:

1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query

JAGAN’S DEGREE COLLEGE Page 132


II B.Sc(M.S.C.S/M.P.C.S)

11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }

Example of PreparedStatement interface that updates the record


1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
download this example

Example of PreparedStatement interface that deletes the record


1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");

Example of PreparedStatement interface that retrieve the records of a table


1. PreparedStatement stmt=con.prepareStatement("select * from emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

JAGAN’S DEGREE COLLEGE Page 133


II B.Sc(M.S.C.S/M.P.C.S)

Example of PreparedStatement to insert records until user press n


1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
7.
8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12. do{
13. System.out.println("enter id:");
14. int id=Integer.parseInt(br.readLine());
15. System.out.println("enter name:");
16. String name=br.readLine();
17. System.out.println("enter salary:");
18. float salary=Float.parseFloat(br.readLine());
19.
20. ps.setInt(1,id);
21. ps.setString(2,name);
22. ps.setFloat(3,salary);
23. int i=ps.executeUpdate();
24. System.out.println(i+" records affected");
25.
26. System.out.println("Do you want to continue: y/n");
27. String s=br.readLine();
28. if(s.startsWith("n")){
29. break;
30. }
31. }while(true);
32.
33. con.close();
34. }}

JAGAN’S DEGREE COLLEGE Page 134


II B.Sc(M.S.C.S/M.P.C.S)

JAGAN’S DEGREE COLLEGE Page 135

You might also like