II B.Sc IV SEM JAVA
II B.Sc IV SEM JAVA
S)
UNIT-I
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.
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.
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.
JVM Architecture: - JVM contains class loader, memory area, execution engine etc. the
following diagram illustrates the JVM Architecture.
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.
• 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.
• 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.
❖ 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:
➢ Eg: PI
MAX_VALUE
FONT_BOLD
❖ Keyword:
➢ All keywords should be written by using all small letters as follows:
➢ Eg: public
void
static
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. 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
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
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;
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
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);
Output
a
❖ 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
publicclassTest {
publicstaticvoidmain(String[] args)
{
String s = "Hello";
System.out.println(s);
System.out.println(s1);
}
}
Output
Hello
error: cannot find symbol
symbol: variable Hello
location: class Test
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.
❖ 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:
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
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
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
6. Conditional operator:
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;
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);
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
• 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
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.
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;
}
}
}
• 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
• 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
• 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 + " ");
}
}
}
Output:
02468
❖ Return statement:
int display()
{
return 10;
}
public static void main(String[] args)
{
Return1 e =new Return1();
System.out.println(e.display());
}
}
Output:
10
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:
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.
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.
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
• 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;
Statement Result
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;
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]
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
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
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+ “!”);
}
}
}
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";
What if we want to have two different object with the same string? For that we would
need to create strings 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:
1 char charAt(int index) returns char value for the particular index
4 String substring(intbeginIndex, returns substring for given begin index and end
intendIndex) index.
6 boolean equals(Object another) checks the equality of string with the given object.
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
Ex Program:
Output:Sachin
Here Sachin is not changed but a new object is created with sachintendulkar. That
is why string is known as immutable.
Output:Sachin Tendulkar
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).
Organization of OOPS
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: -
• 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.
❖ 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
}
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
}
❖ 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();
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
…..…..
}
❖ 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{
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();
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.
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.
<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:
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.
Output:
111 Karan
222 Aryan
❖ 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.
❖ 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
❖ 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
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.
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
Addition.java
class Addition
{
public static void main(String[] args)
{
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
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.
Display.java
InstanceMethodExample.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.
Example:
class Student{
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
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.
❖ 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
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
//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++)
{
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
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Output:
Factorial of 5 is: 120
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
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.
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.
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.
1. The object that you create can be used without duplication of code.
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
• 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.
• 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.
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
{
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.*;
class Employee {
// Driver Class
class Gfg {
Output
Salary : 60000
Benefits : 10000
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");
}
}
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:
class One {
public void print()
{
System.out.println("Multi level");
}
}
{
System.out.println("Inheritance");
}
}
// 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:
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();
Output:
Class A
Class B
Class A
Class C
Class A
Class D
Example:
interface One {
public void print_gk();
}
interface Two {
public void print_for();
}
// Drived class
public class Main {
public static void main(String[] args)
{
child c = new child();
c.print_gk();
c.print_for();
c.print_gk();
}
}
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)
{
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));
}
}
class Test
{
public static void main(String args[ ])
{
two t=new two();
t.calc(49);
}
}
Output:
Square root=7
1.Polymorphic Variables
class ProgrammingLanguage {
public void display() {
System.out.println("I am Programming Language.");
}
}
class Main {
public static void main(String[] args) {
pl.display();
Output:
I am Programming Language.
I am Object-Oriented Programming Language.
because,
• 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
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 {
obj1.display();
obj1.print();
Output:
Private methods in Java are not visible to any other class which limits their scope to
the class in which they are declared.
Example
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();
}
}
Output
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.
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).
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
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");
}
}
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");
}
}
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{
}
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).
Ex:abstractclass Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}
}
}
Output
❖ 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{
classMain{
publicstaticvoidmain(String[] args){
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().
We have inherited a subclass Dog from the superclass Animal. Here, the subclass
Dog provides the implementation for the abstract method makeSound().
5.Interfaces in Java:-
❖ 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>{
Eg:
// interface
interfaceAnimal{
publicvoidanimalSound();// interface method (does not have a body)
publicvoidrun();// interface method (does not have a body)
}
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)
❖ 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:
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;
}
}
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:
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
{
…….
……..
Example:
Somethingwentwrong.
The 'try catch' is finished.
Ex:
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
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
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:
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
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.
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
exceptions are to be handled. An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
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.
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.
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
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{
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{
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:
❖ 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:
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:
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.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
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;
• 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.
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!
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.
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. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
Output:Hello
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.
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();
7. }
8. }
Output:Hello
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:
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. }
➢ public members of the class are available anywhere .The scope of public members of
the class is "GLOBAL SCOPE".
➢ 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.
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
➢ 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.
➢ 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:
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.
Example
In this example, we simply extend the thread and perform a single task using multiple
threads.
Output
Output:
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.
➢ 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.
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(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.
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()
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.
The java.lang.Thread class provides two methods for java daemon thread
No. Method Description
Output
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.
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.
1. Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example:
{ synchronized (resource1)
try {
Thread.sleep(100);
}
catch (Exception e) {}
synchronized (resource2)
{
System.out.println("Thread 1: locked resource 2");
}
// t2 tries to lock resource2 then resource1
synchronized (resource2) {
System.out.println("Thread 2: locked
resource 2");
}
}
};
t1.start();
t2.start();
}
}
Example:classMyThreadextendsThread
{
publicvoidrun()
{
System.out.println("Thread Running...");
}
publicstaticvoidmain(String[]args)
{
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 −
❖ 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."
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( )
• 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.
• 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.
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.
• 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.
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
{
<html>
</applet>
</html>
appletviewer GFG.html
Output:
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.
Syntax:
JButton okBtn = new JButton(“Click”);
Display:
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...”);
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);
1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)
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:
• 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>
*/
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);
}
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"))
{
}
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.
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)
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:
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>
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.
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.
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.
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
3. MongoDB
4. SQLite
5. PostgreSQL
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.
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.
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.
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.
2) Set classpath:
There are two ways to set the classpath:
o temporary
o permanent
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
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()
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.
bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged
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.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
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.
Advantage:
Disadvantage:
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
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.
Advantage:
Disadvantage:
Creating a CallableStatement
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
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");
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:
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());
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");
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:
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) 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.
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");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Syntax:
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,
instance of ResultSet.
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
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. }