Sunteți pe pagina 1din 266

Java Faculty Guide 1

Core Java Facutly Guide

Accord Info Matrix


Chennai
Java Faculty Guide 2

J1–Introduction to Java
TOPIC TO COVER
 What is java?
 Programming language – Categories – Java – Types of java applications – Java Editions – Java
Features
 Java Platform
 JDK – JRE – JVM – Jdk versions – Installation – path setting
 Writing and executing HelloWorld Program
 Required tools – Coding – Compilation and Running program
 How a java program works
 Java compiler – Byte code - Just in time compiler - Role of JVM
 Programming Fundamentals
 Keywords – Identifiers – Variable – Local variable with example

NOTES MUST BE PRESENT


Java is a modern high level; object oriented; platform independent programming language and
is used to develop applications for various environments, from mobile devices to large
enterprise applications. It provides development platform for various kind of application.

Different Development Platform provided by Java


Java provided different development platform or we can call it as different editions of
java.

Java2 SE (Standard Edition)


Standard Edition of java SE: Used for developing applications for desktop pc and servers.
Java SE provides the basic language support.

Java2 EE (Enterprise Edition)


Java EE is built on the java SE. That is java EE is Java SE with additional API for
development of Web application and Enterprise Application.

Java2 ME (Micro Edition)


It provides a platform to develop application for devices with limited storage , display
and power. J2ME is used to develop applications for Mobile devices, PDA, etc.

Accord Info Matrix


Chennai
Java Faculty Guide 3

Java Version
Java language has undergone several changes since the version JDK 1.0(Java Development Kit)
which was released to 1996. The Latest available version is called Java SE 8.

 JDK Alpha and Beta (1995)


 JDK 1.0 (23rd Jan, 1996)
 JDK 1.1 (19th Feb, 1997)
 J2SE 1.2 (8th Dec, 1998)
 J2SE 1.3 (8th May, 2000)
 J2SE 1.4 (6th Feb, 2002)
 J2SE 5.0 (30th Sep, 2004)
 Java SE 6 (11th Dec, 2006)
 Java SE 7 (28th July, 2011)
 Java SE 8 (18th March, 2014)

Java Standard Edition


As a beginning point of learning java we will start with Java SE. As Mentioned earlier, Java SE or
the Standard Edition is a java platform for development of portable code for Desktop and
server environments. The Java SE includes the Java Development Kit and the Java Runtime
Environment or the JRE.
NOTES MUST BE PRESENT

JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware
and software platforms. JVM, JRE and JDK are platform dependent because configuration of
each OS differs. But, Java is platform independent.

JRE

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is
the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM
uses at runtime.

JDK

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development
tools.

Accord Info Matrix


Chennai
Java Faculty Guide 4

Architecture of Java
Java combines both the approaches of compilation and interpretation. First, java compiler
compiles the source code into bytecode. At the run time, Java Virtual Machine (JVM) interprets
this bytecode and generates machine code which will be directly executed by the machine in
which java program runs. So java is both compiled and interpreted language.

How is Java Platform Independent?

Let us see how java achieves platform independency.

A java program code that is stored in .java file, otherwise called as the source code is compiled
by the java compiler and generates the byte code. The byte code is stored in .class file
The Java Virtual Machine is a platform specific component. That is, JVM is unique for each
Operating System platform. It is available with JRE installed in any machine. The JVM reads the
class files (byte code) and converts it in to machine code that is executed by the machine in
which the java program executes.

Why Java is Secured?


The bytecode that is used for the execution inspected before execution by Java Runtime
Environment (JRE). This is mainly done by the “Class Loader” and “Bytecode Verifier”. Hence a
high level of security is achieved.

Accord Info Matrix


Chennai
Java Faculty Guide 5

What is Garbage Collection?


Garbage collection is a process that is happening automatically by which Java achieves better
memory management. In object oriented programming, objects communicate to each
other. Whenever an object is created, there will be some memory allocated for this object. This
memory will remain as allocated until there are some references to this object. When there is
no reference to this object, Java will assume that this object is not used anymore. When
garbage collection process happens, these objects will be destroyed and memory will be
reclaimed by the JVM.

How Java Changed the Internet


Simplifying web programming in general, Java innovated a new type of networked
program called the applet that changed the way the online world thought about content. Java
also addressed some of the thorniest issues associated with the Internet: portability and
security

NOTES MUST BE PRESENT

Platform independent:Java is compiledinto platform independent byte code. This byte code is
distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is
being run.

Simple Java is designed to be easy to learn. If you understand the basic concept of OOP java
would be easy to master.

Secure
With Java.s secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.

Architectural- neutral
Java compiler generates an architecture-neutral object file format which makes the
compiled code to be executable on many processors, with the presence Java runtime system.

Portable
Being architectural neutral and having no implementation dependent aspects of the
specification makes Java portable. Java language is designed to develop application that can
be transported to different network environments. In such cases the application should be
capable of executing on variety of hardware architecture and should be able to execute on
different Operating System environments. Since java application can run on variety of platform
it called as platform independent language.

Accord Info Matrix


Chennai
Java Faculty Guide 6

Robust
Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking. Java language can be used to create highly reliable
software. The features like Dynamic Memory Management and runtime error management has
made the java program more Robust (Strong) and reliable

Multi-threaded
Java’s multi-threaded feature it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly running interactive
applications.

Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and light weight process.

High Performance:
With the use of Just-In-Time compilers Java enables high performance.

Distributed
Java is designed for the distributed environment of the internet.

Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.

A First Simple Program


Now let us see how to write a program, compile it and execute it. All java programs
should be written as class. The class contains the functionalities and the data. In a java class the
functionalities are provided by methods.
In java, a standard program can contain as much required no. of classes. One of the class
should contain a method called main(), which is always the beginning point of execution of the
program.

Accord Info Matrix


Chennai
Java Faculty Guide 7

Writing a java program can be done with any test editors. Like notepad, notepad++
TestClass.java
class TestClass
{
public static void main(String args[])
{
System.out.println("Welcome to java programming);
}
}

Consider the program saved in D: in examples folder,


The above is a simple java class with main method, which when executed, gives the ouput
‘welcome to java programing on the console’. The class contains the mean method where the
program start to execute. The the signature of the main method should be exactly the same as
how it is declared. It is mandatory because the program when executed the JVM will expect a
meain method whith exactly the same signature.
Now we will see how to compile and then execute the program.
To compile, open the windows command prompt In the command prompt use the javac tool to
compile the program.

Once after the program is compiled, we can test it by using the java command

At this point, remember that when you save a java program save the program file with the
extension .java and the file name should be same as the name of the class where the main
method is added.

Accord Info Matrix


Chennai
Java Faculty Guide 8

Lexical Issues

Java programs are a collection of whitespace, identifiers, literals, operators, separators, and
keywords.

NOTES MUST BE PRESENT

Keywords
Keywords are reserved words of java has fixed meaning. You cannot use any of the following as
identifiers in your programs.

Whitespace
Java is a free-form language. For instance, the Example program could have been written all on
one line or in any other strange way you felt like typing it, as long as there was at least one
whitespace character between each token that was not already delineated by an operator or
separator. In Java, whitespace is a space, tab, or newline.

Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. They must not begin with a number, lest they be confused with a
numeric literal.
Examplecount , a4, $test

Literals
A constant value in Java is created by using a literal representation of it.
Example 100, 89.0

Separators
Separators help define the structure of a program. The separators used in HelloWorld
are parentheses, ( ), braces, { }, the period, ., and the semicolon, ;. The table lists the six Java
separators (nine if you count opening and closing separators as two).
Variable
Variable is a name of memory location. it’s a container to store a value. It changes
during program execution.
Syntax: datatypevariablename=value;
Example: int a=10;

Accord Info Matrix


Chennai
Java Faculty Guide 9

Types:

Local Variable-A variable that is declared inside the method is called local variable.
Instance Variable-A variable that is declared inside the class but outside the method is called
instance variable .
static variable-A variable that is declared as static is called static variable.
final variable-A variable that is declared as final called final variable.

Example:
class A{
int data=50;//instance variable
final float pi=3.14f;//final variable
staticint m=100;//static variable
void method(){
int n=90;//local variable
}
}

Local variable:
A variable that is declared inside the method is called local variable.It should be initialized.Its
scope is within method.
Example Program to understand local variable:
classVarEx
{
public static void main(String args[]){
int num1=10;
int num2=20,num3=30,result;
System.out.print("Number1 value:"+num1);
System.out.println("\tNumber2 value:"+num2+"\tNumber3 value:"+num3);
result=num1+num2+num3;
System.out.print("Addition:"+result);
}
}
Output:
Number1 value:10 Number2 value:20 Number3 value:30
Addition:30

Accord Info Matrix


Chennai
Java Faculty Guide 10

Lab Assignment
1. Write a program to print the following content in console
Java is object oriented Programming language
Java is high level
Java is platform independent
2. Write a program to perform arithmetic operations for two integers
3. Write program to swap two numbers using third variable
4. Write program to swap two numbers without using third variable
5. Write a program to convert total number of days into years, months, weeks, days
FAQ
1. What is Java?
2. What are types of Java Applications?
3. Explain java Editions
4. Explain Java Platform Jdk,Jre
5. What is difference between Jdk,Jre,Jvm? and Are they platform dependent or independent
6. What is the role of Java Compiler and Justintime compiler
7. Explain Java is platform Independent (Wora)
8. How java is secured
9. What is the difference between c and Java
10. What is the difference between C++ and Java
11. Explain HelloWorld Program
12. Why Main method is static
13. What is Jvm ,role of Jvm,Memory available in Jvm
14. How java is Robust
15. What are variables and its types
16. What is the use of String args[] in main()? if we didn't use what will happen? other than
String will it support any argument
17. Why main() return type is void? Why not other Return types

Accord Info Matrix


Chennai
Java Faculty Guide 11

J2–Data types, Operators, Control Statements


TOPIC TO COVER
 Datatypes
 Primitive – Non Primitive Data type - Example
 Operators
 Types - Example
 Control Statements
 Decision Making - Looping

Data types
DataType is a type of a data what variable can hold.There are two types of datatypes,
1. Primitive Data Types
2. Primitive Data Types
Primitive Data Types-Has Fixed Size ,There are 8 Primitive datatypes in java
Non-Primitive Data Types-No fixed size String,class,Array,Collection
Primitive Data Types
DATATYPE KEYWORD SIZE DECLARATION DEFAULTVALUE
Boolean boolean 1 bit true/false false
Character char 2 byte ‘c’ White space
Byte byte 1 byte Whole Numbers 0
short short 2 byte
Integer int 4 byte
Long long 8 byte
Floating point float 4 byte 10.2f; 0.0
double double 8 byte 2312.23;

Example Program To Understand All Data type In A Single Program:


public class DataTypeEx {
public static void main(String[] args) {
byte b =100;
short s =123;
int v = 123543;
long a= 1234567891;
float e = 12.25f;
double d = 12345.234d;
booleanval = false;
char ch = ‘Y’;
System.out.println(“byte Value = “+ b+”\tshort Value = “+ s+”\tint Value = “+ v+”\tlong Value =
“+ a);

Accord Info Matrix


Chennai
Java Faculty Guide 12

System.out.println(“float Value = “+e+”\tdouble Value = “+ d);


System.out.println(“boolean Value = “+ val);
System.out.println(“char Value = “+ ch); }
}
Output:
byte Value =100 short Value =123 int Value =123543 long Value = 1234567891
float Value =12.25 double Value =12345.234d
boolean Value =false char Value =Y

char uses 2 byte in java


because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of
unicodesystem.To get detail about Unicode see below.

Unicode System
Unicode is a universal international standard character encoding that is capable of representing
most of the world's written languages.
Before Unicode, there were many language standards:
 ASCII (American Standard Code for Information Interchange) for the United States.
 ISO 8859-1 for Western European Language.
 KOI-8 for Russian.
 GB18030 and BIG-5 for chinese, and so on.
This caused two problems:
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length.Some common
characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Example Program To Understand All Data type In A Single Program:
public class DataTypeEx {
public static void main(String[] args) {
byte b =100;
short s =123;
int v = 123543;
long a= 1234567891;
float e = 12.25f;
double d = 12345.234d;

Accord Info Matrix


Chennai
Java Faculty Guide 13

booleanval = false;
char ch = ‘Y’;
System.out.println(“byte Value = “+ b+”\tshort Value = “+ s+”\tint Value = “+ v+”\tlong Value
= “+ a);
System.out.println(“float Value = “+e+”\tdouble Value = “+ d);
System.out.println(“boolean Value = “+ val);
System.out.println(“char Value = “+ ch); } }
Operators:
Operators are symbols used to perform operation between operands.
Category Symbols
Assignment = += -= *= /= %=
Arithmetic + - * / %
Increment and Decrement ++ --(Pre,Post)
Relational == != > >= < <=
Conditional ? : (ternary)
Type comparison instanceof
Bitwise and Bit shift ~ << >> >>> & ^ |
Logical && || !
SPECIAL OPERATORS new –dynamic memory allocation
new , . . – member resolution

Operator

Operator is a special symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift
operator, bitwise operator, ternary operator and assignment operator.

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Java Arithmatic Operators Example
The following simple example program demonstrates the arithmetic operators.
class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;

Accord Info Matrix


Chennai
Java Faculty Guide 14

int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}

Operator Description Example


Addition - Adds values on either side of
+ A + B will give 30
the operator
Subtraction - Subtracts right hand
- A - B will give -10
operand from left hand operand
Multiplication - Multiplies values on
* A * B will give 200
either side of the operator
Division - Divides left hand operand by
/ B / A will give 2
right hand operand
Modulus - Divides left hand operand by
% right hand operand and returns B % A will give 0
remainder
Increment - Increase the value of
++ B++ gives 21
operand by 1
Decrement - Decrease the value of
-- B-- gives 19
operand by 1

The Relational Operators:


There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:

Accord Info Matrix


Chennai
Java Faculty Guide 15

Java Relational Operators Example


The following simple example program demonstrates the relational operators.

class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Operator Description Example


Checks if the value of two operands
== are equal or not, if yes then condition (A == B) is not true.
becomes true.
Checks if the value of two operands
!= are equal or not, if values are not (A != B) is true.
equal then condition becomes true.
Checks if the value of left operand is
greater than the value of right
> (A > B) is not true.
operand, if yes then condition
becomes true.
Checks if the value of left operand is
< less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.
Checks if the value of left operand is
less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition
becomes true.

Accord Info Matrix


Chennai
Java Faculty Guide 16

The Bitwise Operators:


Java defines several bitwise operators which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Java Bitwise Operators Example
The following simple example program demonstrates the bitwise operators
class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


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

c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */


System.out.println("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */


System.out.println("a << 2 = " + c );
c = a >> 2; /* 215 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c );}}

Accord Info Matrix


Chennai
Java Faculty Guide 17

Operator Description Example


Binary AND Operator copies a bit to
& (A & B) will give 12 which is 0000 1100
the result if it exists in both operands.
Binary OR Operator copies a bit if it
| (A | B) will give 61 which is 0011 1101
exists in eather operand.
Binary XOR Operator copies the bit if it
^ (A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.
Binary Ones Complement Operator is
~ unary and has the efect of 'flipping' (~A ) will give -60 which is 1100 0011
bits.
Binary Left Shift Operator. The left
operands value is moved left by the
<< A << 2 will give 240 which is 1111 0000
number of bits specified by the right
operand.
Binary Right Shift Operator. The left
operands value is moved right by the
>> A >> 2 will give 15 which is 1111
number of bits specified by the right
operand.
Shift right zero fill operator. The left
operands value is moved right by the
>>> number of bits specified by the right A >>>2 will give 15 which is 0000 1111
operand and shifted values are filled
up with zeros.

The Logical Operators:


The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Java Logical Operators Example
The following simple example program demonstrates the logical operators.
class Test {
public static void main(String args[]) {
int a = true;
int b = false;
System.out.println("a && b = " + (a&&b) );

Accord Info Matrix


Chennai
Java Faculty Guide 18

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


System.out.println("!(a && b) = " + !(a && b) );
}
}

Operator Description Example


Called Logical AND operator. If both the
&& operands are non zero then then (A && B) is false.
condition becomes true.
Called Logical OR Operator. If any of the
|| two operands are non zero then then (A || B) is true.
condition becomes true.
Called Logical NOT Operator. Use to
reverses the logical state of its operand.
! !(A && B) is true.
If a condition is true then Logical NOT
operator will make false.

The Assignment Operators:


There are following assignment operators supported by Java language:
Java Assignment Operators Example
The following simple example program demonstrates the assignment operatorsoperators.
class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 0;

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

c += a ;
System.out.println("c += a = " + c );

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

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

Accord Info Matrix


Chennai
Java Faculty Guide 19

a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );

a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );

c <<= 2 ;
System.out.println("c <<= 2 = " + c );

c >>= 2 ;
System.out.println("c >>= 2 = " + c );

c >>= 2 ;
System.out.println("c >>= a = " + c );

c &= a ;
System.out.println("c &= 2 = " + c );

c ^= a ;
System.out.println("c ^= a = " + c );

c |= a ;
System.out.println("c |= a = " + c );
}
}

Operator Description Example


Simple assignment operator, Assigns
= values from right side operands to C = A + B will assigne value of A + B into C
left side operand
Add AND assignment operator, It
adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to left
operand
-= Subtract AND assignment operator, C -= A is equivalent to C = C - A

Accord Info Matrix


Chennai
Java Faculty Guide 20

It subtracts right operand from the


left operand and assign the result to
left operand
Multiply AND assignment operator,
It multiplies right operand with the
*= C *= A is equivalent to C = C * A
left operand and assign the result to
left operand
Divide AND assignment operator, It
divides left operand with the right
/= C /= A is equivalent to C = C / A
operand and assign the result to left
operand
Modulus AND assignment operator,
It takes modulus using two
%= C %= A is equivalent to C = C % A
operands and assign the result to
left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
bitwise exclusive OR and assignment
^= C ^= 2 is same as C = C ^ 2
operator
bitwise inclusive OR and assignment
|= C |= 2 is same as C = C | 2
operator

Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as :

variable x = (expression) ? value if true : value if false

Following is the example:


public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

Accord Info Matrix


Chennai
Java Faculty Guide 21

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

Control Statements
Programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program.

Selection Statements-(Decision Making):-Perform statement which condition is true.


– Simple if and if...else
– Nested If
– Nested if Statements
– Using switch Statements
Repetition Statements-(Looping):-Repeat the operation until condition gets false.
– Looping: while, do, and for
– Using break and continue

The if Statement:
Syntax:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 22

The if...else Statement:


Syntax:

if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}}

The if...else if...else Statement:


Syntax:
The syntax of a if...else is:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}

Accord Info Matrix


Chennai
Java Faculty Guide 23

Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
Nested if...else Statement:
Syntax:
The syntax for a nested if...else is as follows:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

You can nest else if...else in the similar way as we have nested if statement.

Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
} } }

Accord Info Matrix


Chennai
Java Faculty Guide 24

The switch Statement:


Syntax:
The syntax of enhanced for loop is:

switch(expression){
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
Example:
public class Test {
public static void main(String args[]){
char grade = args[0].charAt(0);
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 25

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:

while(Boolean_expression
)
{
//Statements
}

Example:
public class Test {
public static void main(String args[]){
int x= 10;
while( x < 20 ){
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Accord Info Matrix


Chennai
Java Faculty Guide 26

Example:
public class Test {
public static void main(String args[]){
int x= 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

The for Loop:


Syntax:
The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}
Example:

public class Test {


public static void main(String args[]){
for(int x = 10; x < 20; x = x+1){
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.

Accord Info Matrix


Chennai
Java Faculty Guide 27

Syntax:
The syntax of a break is a single statement inside any loop:

break;
Example:

public class Test {


public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
if( x == 30 ){
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

The continue Keyword:


Syntax:
The syntax of a continue is a single statement inside any loop:

continue;
Example:

public class Test {


public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
if( x == 30 ){
continue;

Accord Info Matrix


Chennai
Java Faculty Guide 28

}
System.out.print( x );
System.out.print("\n");
}
}
}

Lab Assignment
1. Write program to find greatest of two numbers using conditional operator
2. Write program to find greatest of three numbers using conditional operator
3. Write a program to find greatest of three numbers using else if ladder
4. Write a program to calculate commission of a sales man according to the given rate using
nested if statement
Sales Value Commission Rate (%)
0 to 5000 0%
5000 to 10000 5%
10000 to 20000 10%
20000 to 30000 12%
Above 30000 15%
5. Write a program to show day name according to day nuber (1-7) using switch
6. Write a program to print Natural number Series
7. Write a program to print Fibonacci series
8. Write a program to print 1-100 odd numbers
9. Write a program to print 1-100 even numbers
10. Write a program to print 1-100 prime numbers
11. Write a program to find factorial of a number using for loop
12. Write a program to count number of digits
13. Write a program to find sum of digits

Accord Info Matrix


Chennai
Java Faculty Guide 29

J3 - Class and Object, Constructor


TOPIC TO COVER
 What is Object Oriented Programming?
 Object oriented programming - Oop Concepts-Advantage of object oriented programming
 Class and Object
 Class – Object – Member variable – Instance Methods – Creating multiple objects using
methods
 Encapsulation
 Encapsulation – Advantage – Data hiding – Accessing private data members
 Constructor
 Constructor – Advantage – Types – Creating multiple objects using Constrcutor
 Access Modifiers
 Access Modifiers - Accessibility chart for modifiers
 Static keyword
 Static keyword - Usage
 This Keyword
 this keyword – Usage

Methodologies of Solving a Problem?


In software development, there are many methodologies available to consider problem,
They are,
 Sequence Programming - Consider problem in order to sequence ex- Cobal
 Structured Programming - Consider problem in terms of structure i.e functions ex-C
 Object oriented programming- Consider problem in terms of object ex- java,c#
 Object base programming - Supports Objects but not all concepts of Oops
ex-javascript,vbscript
NOTE SHOULD BE PRESENT:
What is Object Oriented Programming?
Object Oriented Programming uses Objects as the basic entity. This provides the support
for splitting the functionalities (Methods) and data (variables) into different modules (Parts).
This provides support of organized maintenance of code in the application.
Object Oriented Programming Concepts
 Class
 Object
 Inheritance
 Abstraction

Accord Info Matrix


Chennai
Java Faculty Guide 30

 Polymorphism
 Encapsulation

Advantage of OOPs
 makes development and maintenance easier
 provides data hiding
 provides ability to simulate real-world event much more effectively

Class:
In an object oriented programming, the basic component that build the program is a ‘class’. A
class is the basic building block of an Object Oriented Program. A class contains the definition
of the Object that will be created in the run time of the application.
Object
Object is the basic runtime entity of any object oriented application. In reality Objects are the
memory location that contains the member data and the methods defined in a class.
For a class as much as required objects can be created in an applications execution time.

NOTES SHOULD BE PRESENT:


CLASS:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
 fields
 methods
 constructors
 blocks
 nested class and interface

Syntax of creating a class Syntax of creating a class


class <class_name>{ class Student{
data members; int id;
} String name;
}

Accord Info Matrix


Chennai
Java Faculty Guide 31

OBJECT:
Object is a real timeentity. Object is a run time entity. Object is an entity which has state and
behavior. Object is an instance of a class. They are called as the instance of a class.

Syntax of creating an object


Classnamereferencevariable =new construtorcall();
Example:
Student s=new Student();

new keyword
The new keyword is used to allocate memory at run time. All objects get memory in Heap
memory area.
Some common terminologies used in class
Class variables - belong to the entire class as a whole. There is only one copy of each class
variable
Instance variables - data that belongs to individual objects; every object has its own copy of
each one
Member variables - refers to both the class and instance variables that are defined by a
particular class
Class methods - belong to the class as a whole and have access only to class variables.
Instance methods - belong to individual objects and have accessed to instance variables for the
specific class

General Rules you have to keep in mind when creating a class


Class name should be a valid identifier. That is, name should not be a java keyword. No special
symbols, spaces or should not start with number.
The members of the class should be enclosed with in opening and closing braces.
There can be any number of methods and variables in a class.
Example Program To Understand class and object
class Student{
introllno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;

Accord Info Matrix


Chennai
Java Faculty Guide 32

}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(101,"Ria");
s2.insertRecord(102,"Ryu");
s1.displayInformation();
s2.displayInformation(); }}
Output
101 Ria
102 Ryu

Encapsulation
If a data member is private it means it can only be accessed within the same class. No outside
class can access private data member (variable) of other class. However if we setup public
getter and setter methods, to update the private data fields then the outside class can access
those private data fields via public methods. This way data can only be accessed by public
methods thus making the private fields and their implementation hidden for outside classes.
That’s why encapsulation is known as data hiding.

NOTES SHOULD BE PRESENT:


Encapsulation:
Encapsulation in java is a process of wrapping code and data together into a single unit.
We can create a fully encapsulated class in java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
Advantage:
 By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data.
Example Program To Understand Encapsulation:
class Student{
private String name;

Accord Info Matrix


Chennai
Java Faculty Guide 33

private int id;


public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public intgetId(){
return id;
}
public void setId(int id){
this.id=id;
}
}
class TestEncaps{
public static void main(String[] args){
Student s=new Student();
s.setName("Vijay");
System.out.println(s.getName());
s.setId(101);
System.out.println(s.getId());
}
}
Output
Vijay
101

NOTES SHOULD BE PRESENT:


Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.

Accord Info Matrix


Chennai
Java Faculty Guide 34

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor
A constructor that have no parameter is known as default constructor.

Syntax
<class_name>()
{
//initialization
}

If there is no constructor in a class, compiler automatically creates a default constructor.


Default constructor provides the default values to the object like 0, null etc. depending on the
type.

Parameterized constructor
A constructor that has parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.

Example Program To Understand Parameterized Constructor:


class Student{
int id;
String name;
Student(inti,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){

Accord Info Matrix


Chennai
Java Faculty Guide 35

Student s1 = new Student(111,"Ria");


Student s2 = new Student(222,"Ryu");
s1.display();
s2.display();
}
}
Output
101 Ria
102 Ryu

Scope of the members of the class


The scope of the member represents the availability of the members in different content
throughout the program. Scope modifiers or access modifiers
To define the scope of a member of a class, we use some key words they are called as the scope
modifiers or access modifiers.
In java a member of a class can be in four different scope
1. public
2. protected
3. private
4. default

NOTES SHOULD BE PRESENT:


Scope Availability Example
Public Public members of a class are available other classes or public int age;
different package.
protected Protected members are available to any class of the protected int age;
same package and to sub classes of the other package
Private Private members are available only to the class in private intaccount_no;
which they are declared.
Default Default members are available to the classes of the Int id;
same package but not available to the other package
classes.

Accord Info Matrix


Chennai
Java Faculty Guide 36

static Keyword
A static member of a class shares the memory among the entire object created for its container
class. All the static members are loaded to a memory location called as the ‘static memory
location’ which will be accessed by the entire object created for that class. A static member of
a class can be accessed by using the class name (no need for creating the object). This is the
reason why the ‘main’ method if the standard class is declared as static.
A non- static member cannot the accessed for a static context. That is static method or the
static block of statement.
NOTES SHOULD BE PRESENT:
The static keyword is used in java mainly for memory management.
Usage of Static Keyword
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).

Example program to understand static keyword


class Student{
introllno;
String name;
static String college = "Accord";
static void change(){
college = "InfoMatrix"; }

Student(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}


public static void main(String args[]){
Student s1 = new Student (111,"Jaanu");
Student s2 = new Student (222,"Ryu");

Accord Info Matrix


Chennai
Java Faculty Guide 37

Student s3 = new Student (333,"Ria");

s1.display();
Student.change();
s2.display();
s3.display();
}
}
Output
111 Jaanu Accord
222 RyuInfoMatrix
333 RiaInfoMatrix

this Keyword
The actual parameter and formal parameter values must be distinct, if we have same names for
both it will give default values for the objects.
this Keyword
this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

Accord Info Matrix


Chennai
Java Faculty Guide 38

Lab Assignment

1. Class using Distance, have instance variable as feet, inches


2. Perform four types of method in a same program find area of circle(), rectangle(), square(),
triangle()
3. Class using Employee, have instance variable as id, name, designation, salary use setter and
getter method for multiple objects
4. Parametrized Constructor with Circle class
5. Calling Constructor from another Constructor with using this keyword
6. Class using Student, have instance variable as id, name, collage use static keyword for
collage="VIT" for 3 students and 2 Student collage="MIT" and this keyword to represent current
class reference

FAQ
1. What is the difference between an object and a class ?
2. What is oops
3. What is the difference between object oriented and structured oriented programming language
4. What is the difference between object oriented and object based programming
5. What are oop concepts
6. Explain class definition ,advantage,syntax,example
7. Explain object definition ,advantage,syntax,example
8. Explain constructor definition ,advantage,types,syntax,example
9. What is the purpose of default constructor?
10. Does constructor return any value?
11. Difference between method and Constructor
12. What is static variable?
13. What is static method?
14. Why main method is static?
15. What is static block?
16. Can we execute a program without main() method?
17. What if the static modifier is removed from the signature of the main method?
18. What is difference between static (class) method and instance method?
19. What is the use of this keyword in java?
20. What do you mean by data hiding

Accord Info Matrix


Chennai
Java Faculty Guide 39

J3 – Inheritance, Abstraction
TOPIC TO COVER
 Inheritance
 Inheritance – Advantage - Syntax – Example - Types of Inheritance – Which inheritance not
support by java and why
 Super Keyword
 Super keyword - Usage
 Abstraction
 Abstraction – Advantage – Types
 Abstract class
 Abstract class – Syntax – Example
 Interface
 Interface – Syntax – Example
 Abstract class and Interface
 Difference

Inheritance
In programming terminology inheritance is extending the functionalities of a class. It
also referred as the process where one class acquires the properties (methods and fields) of
another. With the use of inheritance the information is made manageable in a hierarchical
order.
NOTES SHOULD BE PRESENT:
Inheritance
When you want to create a new class and there is already a class that includes some of
the code that you want, you can derive your new class from the existing class.
By doing this, you can reuse the fields and methods of the existing class without having
to write them yourself.
Super class:
The class which has common property also known as parent and base class
Sub class
The class which has additional property also known as child and derived class
Advantage
 A subclass inherits all the members (fields, methods, and nested classes) from its super class.
 Code Reusability
 Used to achieve method overriding

Accord Info Matrix


Chennai
Java Faculty Guide 40

Syntax
class Baseclass class Employee
{ {
//data members int salary;
} }
class DerivedClass extends BaseClass class Programmer extends Employee
{ {
//data members int bonus;
} }

Note:
In java a predefined class called ‘Object’ available in the java.lang package contains all
the properties common to all classes in java. So a class which we create in java is directly or
indirectly inherits the properties if this class. So in java at the top most of the classes hierarchy
is Object class some class inherit directly from it and other classes inherit from those classes
and so on.
Example program to understand inheritance
class Calculation{
int z;
public void addition(intx,int y)
{
z=x+y;
System.out.println("The sum of the given numbers"+z);
}
public void subtraction(intx,int y)
{
z=x-y;
System.out.println("The difference between the given numbers"+z);
}
}
class My_Calculation extends Calculation
{
public void multiplication(intx,int y){
z=x*y;
System.out.println("The difference between the given numbers"+z);

Accord Info Matrix


Chennai
Java Faculty Guide 41

}
}

class TestInh{
public static void main(String args[]){
int a=20 , b=10;
My_Calculationcalc = new My_Calculation();
calc.addition(a,b);
calc.subtraction(a,b);
calc.multiplication(a,b);}
}
Output:
The sum of the given numbers30
The difference between the given numbers10
The difference between the given numbers200

NOTES SHOULD BE PRESENT:


Types of Inheritance
Single Level
where there is only one base class and one sub class.

Multilevel Inheritance
In Multilevel Inheritance a class will be inheriting a class and as well as that derived class act as
the parent class to other class also.

Multiple Inheritance
Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is not supported in java. But it is possible through the concept of interface.

Why multiple inheritance is not supported in java.


Multiple inheritance of implementation is the ability to inherit method definitions from
multiple classes. Problems arise with this type of multiple inheritance, such as name conflicts
and ambiguity (duplication).

Accord Info Matrix


Chennai
Java Faculty Guide 42

Hierarchical Inheritance
In hierarchical inheritance there will be multiple sub classes and one super class. All the sub
class having the properties the super class.

Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and
Multiple inheritance. A hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces.

Types of Inheritance

Accord Info Matrix


Chennai
Java Faculty Guide 43

What happens to constructor when inherited?


The constructor of a class is not inherited by its sub class. But when u instantiate the sub class
the super class constructor get executed first followed by the immediate sub class. Whatever
be the no of class be involved in the inheritance in the multi level inheritance, the super most
construct will be executed followed by the next sub class and so on.

super keyword
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.

Usage of java super Keyword


1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.Another way, it shows only important things to the user and hides the
internal details for example sending sms, you just type the text and send the message. You
don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.There are two ways
to achieve abstraction in java Abstract class ,Interface
NOTES SHOULD BE PRESENT:
Abstraction is a process of hiding the implementation details. In other words it is providing the
specification for methods .
In Java Abstraction is achieved using
 Abstract classes(0 to 100%)
 Interfaces. (100%)

Accord Info Matrix


Chennai
Java Faculty Guide 44

NOTES SHOULD BE PRESENT:


Abstract class
A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods ie., methods without
body/definition

But, if a class has at least one abstract method, then the class mustbe declared abstract.
If a class is declared abstract it cannot be instantiated. To use an abstract class you have to
inherit it from another class, provide implementations to the abstract methods in it.
If you inherit an abstract class you have to provide implementations to all the abstract
methods in it.
Example Program To Understand abstract class:
abstract class AbstractEmployee{
private String name;
private String address;
private String number;
public AbstractEmployee(String name,Stringaddress,String number){
this.name=name;
this.address=address;
this.number=number;
}
void showDetails(){
System.out.println("name"+name);
System.out.println("current address"+address);
System.out.println("Mobile"+number);
}
abstract void calculateSalary(int arg1,int arg2);
}
class PermanentEmployee extends AbstractEmployee
{
PermanentEmployee(String name,Stringaddress,String number){
super(name,address,number);
}
void calculateSalary(int arg1,int arg2){
System.out.println("Calculate for"+arg1+" working days");

Accord Info Matrix


Chennai
Java Faculty Guide 45

System.out.println("Salary per day"+arg2+" rupees");


float salary=arg1+arg2;
System.out.println("Salary is"+salary);
}
}
class TestAbt
{
public static void main(String args[]){
PermanentEmployee per = new PermanentEmployee("Rajesh","chennai","9843156732");
per.showDetails();
per.calculateSalary(28,1200);
}
}

Output
Name Rajesh
Current Address Chennai
Mobile 9843156732
Calculate for 28 working days
Salary per day 1200 rupees
Salary is:1228.0

NOTES SHOULD BE PRESENT:


Interfaces
In the Java programming language, an interface is a reference type, similar to a class that can
contain only constants, method signatures. Interfaces cannot be instantiated they can only be
implemented by classes or extended by other interfaces. When a class implements an
interface, it provides a method body for each of the methods declared in the interface. It
provides the specification for the method that should be defined in the class that will
implement it. An Interface is created with the keyword interface. Interface is best choice for
Type declaration or defining contract between multiple parties.

If multiple programmers are working in different module of project they still use each other’s
API by defining interface and not waiting for actual implementation to be ready. This brings us
lot of flexibility and speed in terms of coding and development

Accord Info Matrix


Chennai
Java Faculty Guide 46

Example Program To UnderstandMultiple Implementation:


interface MyInterface
{
public void method1();
public void method2();
}
interface MyInterface2
{
public void method3();
}
class XYZ implements MyInterface,MyInterface2
{
public void method1()
{
System.out.println("Implementation of method1");
}
public void method2()
{
System.out.println("Implementation of method2");
}
public void method3()
{
System.out.println("Implementation of method3");
}
}

class TestIntf
{
public static void main(String args[])
{
MyInterfaceobj=new XYZ();
obj.method1();
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 47

Output
Implementation of method1

Note:
 We can’t instantiate an interface in java. Interface provides complete abstraction as none of its
methods can have body.
 On the other hand, abstract class provides partial abstraction as it can have abstract and
concrete(methods with body) methods both.
 implements keyword is used by classes to implement an interface.
 While providing implementation in class of any method of an interface, it needs to be
mentioned as public.
 Class implementing any interface must implement all the methods, otherwise the class should
be declared as “abstract”.
 Interface cannot be declared as private, protected All the interface methods are by default
abstract and public.
 Variables declared in interface are public, static and final by default.

Difference Between Abstract class and Interface

Abstract class Interface


1) Abstract class can have abstract and non-
Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final,
Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Accord Info Matrix


Chennai
Java Faculty Guide 48

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Lab Assignment
Data Members for the class are eid, ename, designation, salary and location ,use types of
methods efficiently
1. Write a program to achieve single level inheritance for the following classes
Employee
|
Programmer
2. Write a program to achieve multi level inheritance for the following classes
Employee
|
Programmer
|
Junior_Programmer
3. Write a program to achieve hierarchical inheritance for the following classes
Employee
| |
Programmer Tester
4. Write a program to achieve hybrid inheritance for the following classes
Employee
| |
Programmer Tester
| |
Junior_Programmer Manual_Tester

5. Write a program to use super keyword to call immediate parent data members
6. Write a program to achieve abstraction using abstract class the following class
abstract class Bank
|
classAtm
Have withdraw() deposit() as abstract method and display() as concrete method

7. Write a program to achieve multiple inheritances for the following classes through interface
Tester
| |
ManualTester AutomationTester

Accord Info Matrix


Chennai
Java Faculty Guide 49

FAQ

1. Explain inheritance definition ,advantage,syntax,example


2. Explain the types of inheritance
3. Which is a super class for all classes in java
4. Which inheritance is not support by java , why
5. What is super in java where and all you can use
6. Can you use this() and super() both in a constructor
7. Can you have virtual functions in java
8. Explain abstraction definition ,advantage, how will you achieve it
9. Explain abstract class definition ,advantage,syntax,example
10. What is the difference between abstraction and encapsulation
11. Can there be any abstract method without abstract class?
12. Can you use abstract and final both with a method?
13. Is it possible to instantiate the abstract class?
14. What is interface?
15. Can you declare an interface method static?
16. Can an Interface be final?
17. What is marker interface?
18. What is difference between abstract class and interface?

Accord Info Matrix


Chennai
Java Faculty Guide 50

J4 – Polymorphism, Packages
TOPIC TO COVER
 Polymorphism
 Method overloading – Advantage – Method Overriding – Advantage – Difference between
method overloading and method overriding
 Binding , Casting, Dynamic method dispatch
 Binding – Types – Object casting – Types – Dynamic method dispatch
 Final Keyword
 Final Keyword - Advantage
 Packages
 Package – Java Sub Packages – User defined Packages

Polymorphism
Polymorphism is the capability of a method to do different things based on the object
that it is acting upon.Subclasses of a class can define their own unique behaviors and yet share
some of the same functionality of the parent class. Polymorphism done in two ways, they are
compile time and run time polymorphism

NOTES SHOULD BE PRESENT:


Polymorphism
Polymorphism is the ability of an object to take on many forms. Poly-many ,morphism -forms
Two Types of polymorphism
 Compile time polymorphism-Method Overloading
 Run time polymorphism-Method Overriding
Method Overloading
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
i.e Same function with different functionality.
Advantage : Method overloading increases the readability of the program.
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type

Accord Info Matrix


Chennai
Java Faculty Guide 51

Example Program To UnderstandMethod Overloading:


class Calculation{
void sum(inta,int b)
{
System.out.println(a+b);
}
void sum(float a,float b)
{
System.out.println(a+b);
}
void sum(inta,intb,int c)
{
System.out.println(a+b+c);
}
void sum()
{
int a=10,b=20;
System.out.println(a+b);
}
int add(int a) {
int b=20;
returna+b;
}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
obj.sum(20.0f,20.0f);
obj.sum();
System.out.println(obj.add(40));
}
}
Output:
30
40

Accord Info Matrix


Chennai
Java Faculty Guide 52

40.0
30
60

NOTES SHOULD BE PRESENT:


Method Overriding
If a class has a method with name , argument list, return type as a methods of its super class
then that method is said to be overridden.
Givingspecific implementation for the method which already provided by parent class, it is
known as Method Overriding.
Advantage :
Method Overriding is used to provide specific implementation of a method that is
already provided by its super class. Method Overriding is used for Runtime Polymorphism

Example Program To Understand Method Overriding:


class Bank{
intgetRateOfInterest(){return 0;}
}
class SBI extends Bank{
intgetRateOfInterest(){return 8;}
}
class ICICI extends Bank{
intgetRateOfInterest(){return 7;}
}
class AXIS extends Bank{
intgetRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

Accord Info Matrix


Chennai
Java Faculty Guide 53

}
}

Output
SBI Rate of Interest:8
ICICI Rate of Interest:7
AXIS Rate of Interest:9

NOTES SHOULD BE PRESENT:


Difference between Method Overloading and Method Overriding
S.NO METHOD OVERLOADING METHOD OVERRIDING

1 Method overloading increases the Method overriding provides the specific


readability of the program. implementation of the method that is
already provided by its super class.
2 methodoverlaoding is occurs within the Method overriding occurs in two classes
class. that have IS-A relationship.

3 In this case, parameter must be In this case, parameter must be same.


different.

Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
 Static binding (also known as early binding)-When type of the object is determined at compiled
time(by the compiler), it is known as static binding.
 Dynamic binding (also known as late binding)-When type of the object is determined at run-
time, it is known as dynamic binding.
Casting objects
 upcasting -When Superclass type refers to the object of Child class, it is known as upcasting.
 downcasting-When Subclass type refers to the object of Parent class, it is known as
downcasting.

Accord Info Matrix


Chennai
Java Faculty Guide 54

Dynamic Method Dispatch or Run time Polymorphism


We are calling the method by the reference variable of Parent class. Since it refers to
the subclass object and subclass method overrides the Parent class method, subclass method is
invoked at runtime.

NOTES SHOULD BE PRESENT:


Dynamic Method Dispatch or Run time Polymorphism
Method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
Example Program to understand Dynamic Method Dispatch
class Bank{
intgetRateOfInterest(){return 0;}
}
class SBI extends Bank{
intgetRateOfInterest(){return 8;}
}
class ICICI extends Bank{
intgetRateOfInterest(){return 7;}
}
class AXIS extends Bank{
intgetRateOfInterest(){return 9;}
}
class Test3{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}
}
Output
SBI Rate of Interest:8
ICICI Rate of Interest:7
AXIS Rate of Interest:9

Accord Info Matrix


Chennai
Java Faculty Guide 55

NOTES SHOULD BE PRESENT:


final keyword
final is used to declare a variable or a method or a class as final.
1. Final variables cannot change the value once after created.
2. It gives a compilation error when attempted to change.
3. Final class cannot be inheritedFinal methods cannot be overridden.

Packages
Packages in Java are a mechanism to encapsulate a group of classes, interfaces and sub
packages. Many implementations of Java use a hierarchical file system to manage source and
class files. It is easy to organize class files into packages. All we need to do is put related class
files in the same directory, give the directory a name that relates to the purpose of the classes,
and add a line to the top of each class file that declares the package name, which is the same as
the directory name where they reside.
NOTES MUST BE PRESENT:
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
Built-In Package:
applet,awt,beans,io,lang,math,net,nio,rmi,security,sql,text,util.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Example Program to understand user defined package:
A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
B.java
packagemypack;
import pack.*;

Accord Info Matrix


Chennai
Java Faculty Guide 56

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Compilation: javac –d . A.java
javac –d . A.java
Running: java mypack.B
Output
Hello

Note:
1. The super package for java is java
2. The super class for all classes in java is Object class
3. Object class is belong to lang package
4. The default package for java is lang

Lab Assignment
1. Overload login() with different possibilities like login(uname), login(uname,pwd),
login(uame,pwd,pin) etc.,
2. Override os() for the following mobiles as class Samsung, Apple, Microsoft
3. Write a program to achieve constructor overloading
4. Write a program to achieve dynamic method dispatch for both abstraction and method
overriding
5. Write a program to get the usage of final keyword
6. Write a program for creating custom package

Accord Info Matrix


Chennai
Java Faculty Guide 57

FAQ
1. Explain polymorphism definition, advantage, types
2. Explain method overloading definition ,example
3. Explain method overriding definition ,example
4. Can we overload main() method?if possible how? if not why?
5. Can we override main() method?if possible how? if not why?
6. Can we override static method?
7. Why we cannot override static method?
8. Can we override the overloaded method?
9. Difference between method Overloading and Overriding.
10. What is the use of final keyword
11. Can we intialize blank final variable?
12. Can you declare the main method as final?
13. What is Runtime Polymorphism?
14. Can you achieve Runtime Polymorphism by data members?
15. What is the difference between static binding and dynamic binding?
16. What is package?
17. Do I need to import java.lang package any time? Why ?
18. Can I import same package/class twice? Will the JVM load the package twice at
runtime?
19. What is static import ?

Accord Info Matrix


Chennai
Java Faculty Guide 58

J6 – Array and String


TOPIC TO COVER
 What is Array?
 Array advantage – Limitations – Types of array (single, multi)
 What is String?
 How to declare – String manipulation functions
 Writing and executing Program using all string functions
 What is String Buffer?
 Important methods of String Buffer class – Related Program
 What is String Builder?
 Important methods of String Builder class – Related Program

ARRAY

Array is a collection of similar type of elements that have contiguous memory location. It is an
object that contains elements of similar data type. It is a data structure where we store similar
elements. We can store only fixed set of elements in a java array.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
o Random access: We can get any data located at any index position.

Disadvantages

o Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.

Limitations

o Array in java is index based, first element of the array is stored at 0 index.
o Array variable name should have subscript [];

Types of JAVA

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Accord Info Matrix


Chennai
Java Faculty Guide 59

1. Single Dimensional

Syntax:

Datatype <varname>[]={val1,val2,……valN};

Datatype[] <varname>={val1,val2,……valN};

Datatype <varname>[]=new Datatype[size];

Example of single dimensional array

class Testarray{

public static void main(String args[]){

String course[]=new String[5];//declaration and instantiation

course[0]=”JAVA”;//initialization

course[1]=”J2EE”;

course[2]=”PHP”;

course[3]=”DOT NET”;

course[4]=”ANDROID”;

//printing array using for…loop

for(int i=0;i<course.length;i++)//length is the property of array

{ System.out.println(course[i]); }

//printing array using for each…loop

for(String temp:course)

System.out.println(temp);

}}

Accord Info Matrix


Chennai
Java Faculty Guide 60

2. Multi Dimensional Array

Syntax:

dataType[][] Varname; (or)

dataType [][]Varname; (or)

dataType Varname[][]; (or)

dataType []Varname[];

Example of multi dimensional array

class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(arr[i][j]+" ");

System.out.println();

} }}

Accord Info Matrix


Chennai
Java Faculty Guide 61

String

In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string

Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new
instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.

String is a sequence of characters. But in java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.

How to create String object

There are two ways to create String object:

o By string literal
o By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";

String s2="Welcome";//will not create new instance

In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will
return the reference to the same instance.

Accord Info Matrix


Chennai
Java Faculty Guide 62

2) By new keyword

String s=new String("Welcome");


In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap (non pool).

Example

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

SN Methods with Description

isLetter()
1
Determines whether the specified char value is a letter.

isDigit()
2
Determines whether the specified char value is a digit.

isWhitespace()
3
Determines whether the specified char value is white space.

isUpperCase()
4
Determines whether the specified char value is uppercase.

isLowerCase()
5
Determines whether the specified char value is lowercase.

Accord Info Matrix


Chennai
Java Faculty Guide 63

toUpperCase()
6
Returns the uppercase form of the specified char value.

toLowerCase()
7
Returns the lowercase form of the specified char value.

toString()
8 Returns a String object representing the specified character valuethat is, a one-
character string.

Immutable String in Java

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

Once string object is created its data or state can't be changed but a new string object is
created.

Java StringBuffer class

Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously.
So it is safe and will result in an order.

Important Constructors of StringBuffer class

1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
4. Important methods of StringBuffer class
5. public synchronized StringBuffer append(String s): is used to append the specified string with
this string. The append() method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
6. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string
with this string at the specified position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
7. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to
replace the string from specified startIndex and endIndex.

Accord Info Matrix


Chennai
Java Faculty Guide 64

8. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string
from specified startIndex and endIndex.
9. public synchronized StringBuffer reverse(): is used to reverse the string.
10. public int capacity(): is used to return the current capacity.
11. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal
to the given minimum.
12. public char charAt(int index): is used to return the character at the specified position.
13. public int length(): is used to return the length of the string i.e. total number of characters.
14. public String substring(int beginIndex): is used to return the substring from the specified
beginIndex.
15. public String substring(int beginIndex, int endIndex): is used to return the substring from the
specified beginIndex and endIndex.

Mutable string

A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method

2) StringBuffer insert() method

3) StringBuffer replace() method

4) StringBuffer delete() method

5) StringBuffer reverse() method

6) StringBuffer capacity() method

7) StringBuffer ensureCapacity() method

Java StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class


1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity as length.

Accord Info Matrix


Chennai
Java Faculty Guide 65

Important methods of StringBuilder class

Method Description

public StringBuilder is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.

public StringBuilder insert(int is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public StringBuilder is used to replace the string from specified startIndex and
replace(int startIndex, int endIndex.
endIndex, String str)

public StringBuilder is used to delete the string from specified startIndex and
delete(int startIndex, int endIndex.
endIndex)

public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.

public void is used to ensure the capacity at least equal to the given
ensureCapacity(int minimum.
minimumCapacity)

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of
characters.

Accord Info Matrix


Chennai
Java Faculty Guide 66

public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.

LAB TASK

1. WAP to print the array in ascending order


2. WAP to get input as mark using array and then find sum of marks
3. WAP to design following pattern
a.

**

***

****

*****

b.

*****

****

***

**

Accord Info Matrix


Chennai
Java Faculty Guide 67

c. *

* *

* * *

* * * *

* * * * *

4. WAP to reverse a string (do not use reverse function)


5. Program to find the entered input is alphabet, integer or symbol
6. Program to find frequency of vowels in entered string
7. Check two strings are equal or not with out using the equals() method
8. Replace the string
Input: C# is Object Oriented, C# is easy to learn Replace C# as JAVA
9. Count number of words in string
10. Assume String words[]={“JAVA”,”J2EE”,”PHP”,”DOTNET”,”ANDROID”}. Find the position of the
word “ANDROID” and reverse it.
11. To Find repeated elements in array

FAQ:::::
1. Can you pass the negative number as an array size?
2. Can you change the size of the array once you define it? OR Can you insert or delete the
elements after creating an array?
3. What is the difference between int[] a and int a[] ?
4. There are two array objects of int type. one is containing 100 elements and another one is
containing 10 elements. Can you assign array of 100 elements to an array of 10 elements?
5. “int a[] = new int[3]{1, 2, 3}” – is it a legal way of defining the arrays in java?
6. What are the differences between Array and ArrayList in java?
7. What is ArrayIndexOutOfBoundsException in java? When it occurs?
8. How do you search an array for a specific element?
9. Is String a keyword in java?
10. Is String a primitive type or derived type?
11. In how many ways you can create string objects in java?
12. What is string constant pool?

Accord Info Matrix


Chennai
Java Faculty Guide 68

13. What do you mean by mutable and immutable objects?


14. Why StringBuffer and StringBuilder classes are introduced in java when there already exist
String class to represent the set of characters?
15. How many objects will be created in the following code and where they will be stored in the
memory?
16. How do you create mutable string objects?
17. do you have any idea why strings have been made immutable in java?
18. What is the similarity and difference between StringBuffer and StringBuilder class?

Accord Info Matrix


Chennai
Java Faculty Guide 69

J7 and J8 – Logical Programming


TOPIC TO COVER
 Write and explain logical programs using array
 Write and explain logical string program using String manipulation functions

Check Even or Odd

To check whether the input number is an even number or an odd number in Java programming,
you have to ask to the user to enter the number, now if number is divisible by 2 (it will be even
number) and if the number is not divisible by 2 (it will be an odd number)

Source code

import java.util.Scanner;

public class OddOrEven

public static void main(String args[])

int num;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

if(num%2 == 0)

System.out.print("This is an Even Number");

else

Accord Info Matrix


Chennai
Java Faculty Guide 70

System.out.print("This is an Odd Number");

Check Prime or Not

To check whether the input number is a prime number or not a prime number in Java
programming, you have to ask to the user to enter the number and start checking for prime
number. If number is divisible from 2 to one less than that number, then the number is not
prime number otherwise it will be a prime number

Source code

import java.util.Scanner;

public class PrimeOrNot

public static void main(String args[])

int num, i, count=0;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

for(i=2; i<num; i++)

if(num%i == 0)

Accord Info Matrix


Chennai
Java Faculty Guide 71

count++; break;

if(count == 0)

System.out.print("This is a Prime Number");

else {

System.out.print("This is not a Prime Number");

Check Alphabet or Not

To check whether the entered character is an alphabet or not an alphabet in Java Programming,
you have to ask to the user to enter a character and start checking for alphabet. If the character
is in between a to z(will be alphabet) or A to Z(will also be alphabet) otherwise it will not be an
alphabet.

Source code

import java.util.Scanner;

public class AlphabetOrNot

public static void main(String args[])

char ch;

Scanner scan = new Scanner(System.in);

Accord Info Matrix


Chennai
Java Faculty Guide 72

System.out.print("Enter a Character : ");

ch = scan.next().charAt(0);

if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))

System.out.print(ch + " is an Alphabet");

else

System.out.print(ch + " is not an Alphabet");

Check Vowel or Not

To check whether the input alphabet is a vowel or not in Java Programming, you have to ask to
the user to enter a character (alphabet) and check if the entered character is equal to a, A, e, E,
i, I, o, O, u, U. If it is equal to any one of the 10, then it will be vowel otherwise it will not be a
vowel.

Source code

import java.util.Scanner;

public class VowelOrNot

public static void main(String args[])

Accord Info Matrix


Chennai
Java Faculty Guide 73

char ch;

Scanner scan = new Scanner(System.in);

System.out.print("Enter an Alphabet : ");

ch = scan.next().charAt(0);

if(ch=='a' || ch=='A' || ch=='e' || ch=='E' ||

ch=='i' || ch=='I' || ch=='o' || ch=='O' ||

ch=='u' || ch=='U')

System.out.print("This is a Vowel");

else

System.out.print("This is not a Vowel");

Accord Info Matrix


Chennai
Java Faculty Guide 74

Check Leap Year or Not

To check whether the input year is a leap year or not a leap year in Java Programming, you have
to ask to the user to enter the year and start checking for the leap year.

Source Code

import java.util.Scanner;

public class LeapYearOrNot

public static void main(String args[])

int yr;

Scanner scan = new Scanner(System.in);

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

yr = scan.nextInt();

if((yr%4 == 0) && (yr%100!=0))

System.out.print("This is a Leap Year");

else if(yr%100 == 0)

System.out.print("This is not a Leap Year");

else if(yr%400 == 0)

Accord Info Matrix


Chennai
Java Faculty Guide 75

System.out.print("This is a Leap Year");

else

System.out.print("This is not a Leap Year");

Check Original Equals Reverse or Not

To check whether the original number is equal to its reverse or not in Java programming, you
have to ask to the user to enter the number and reverse that number then check that reverse is
equal to the original or not, before reversing the number make a variable of the same type and
place the value of the original number to that variable to check after reversing the number.

Source Code

import java.util.Scanner;

public class PalindromeNumber

public static void main(String args[])

int num, orig, rev=0, rem;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

Accord Info Matrix


Chennai
Java Faculty Guide 76

orig=num;

while(num>0)

rem = num%10;

rev = rev*10 + rem;

num = num/10;

if(orig == rev)

System.out.print("Reverse is Equal to Original");

else

System.out.print("Reverse is not Equal to Original");

Accord Info Matrix


Chennai
Java Faculty Guide 77

Perform Mathematical Operations

To perform mathematical operations such as addition, subtraction, multiplication and division


of any two number in Java Programming, you have to ask to the user to enter the two number
and then perform the action accordingly.

Source Code

import java.util.Scanner;

public class Calculation

public static void main(String args[])

int a, b, res;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");

a = scan.nextInt();

b = scan.nextInt();

res = a + b;

System.out.println("Addition = " +res);

res = a - b;

System.out.println("Subtraction = " +res);

Accord Info Matrix


Chennai
Java Faculty Guide 78

res = a * b;

System.out.println("Multiplication = " +res);

res = a / b;

System.out.println("Division = " +res);

Add Digits of Number

To add digits of any number in Java Programming, you have to ask to the user to enter the
number to add their digits and display the summation of digits of that number.

Source Code

import java.util.Scanner;

public class AddDigits

public static void main(String args[])

int num, rem=0, sum=0, temp;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

temp = num;

Accord Info Matrix


Chennai
Java Faculty Guide 79

while(num>0)

rem = num%10;

sum = sum+rem;

num = num/10;

System.out.print("Sum of Digits of " +temp+ " is " +sum);

Calculate Arithmetic Mean or Average

To calculate the arithmetic mean of some numbers in Java Programming, you have to ask to the
user to enter number size then ask to enter the numbers of that size to perform the addition,
then make a variable responsible for the average and place addition/size in average, then
display the result on the output screen.

Source Code

import java.util.Scanner;

public class ArithmeticMean

public static void main(String args[])

int n, i, sum=0, armean;

int arr[] = new int[50];

Scanner scan = new Scanner(System.in);

Accord Info Matrix


Chennai
Java Faculty Guide 80

System.out.print("How many Number you want to Enter ? ");

n = scan.nextInt();

System.out.print("Enter " +n+ " Numbers : ");

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

arr[i] = scan.nextInt();

sum = sum + arr[i];

armean = sum/n;

System.out.print("Arithmetic Mean = " +armean);

Calculate Grade of Students

To calculate the grade of a student on the basis of his/her total marks in Java Programming, you
have to ask to the user to enter the marks obtained in some subjects (5 subjects here), then
calculate the percentage and start checking for the grades to display the grade on the output
screen.

Accord Info Matrix


Chennai
Java Faculty Guide 81

Source Code

import java.util.Scanner;

public class StudentGrade

public static void main(String args[])

int mark[] = new int[5];

int i;

float sum=0, avg;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Marks Obtained in 5 Subjects : ");

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

mark[i] = scan.nextInt();

sum = sum + mark[i];

avg = sum/5;

System.out.print("Your Grade is ");

if(avg>80)

System.out.print("A");

Accord Info Matrix


Chennai
Java Faculty Guide 82

else if(avg>60 && avg<=80)

System.out.print("B");

else if(avg>40 && avg<=60)

System.out.print("C");

else

System.out.print("D");

Print Table of Number

To print the table of a number in Java Programming, you have to ask to the user to enter any
number and start multiplying that number from 1 to 10 and display the multiplication result at
the time of multiplying on the output screen.

Source Code

import java.util.Scanner;

public class PrintTables

public static void main(String args[])

Accord Info Matrix


Chennai
Java Faculty Guide 83

int num, i, tab;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

System.out.print("Table of " + num + " is\n");

for(i=1; i<=10; i++)

tab = num*i;

System.out.print(num + " * " + i + " = " + tab + "\n");

Add n Numbers

To add n numbers in Java Programming, you have to ask to the user to enter the value of n
(how many number he/she want to enter ?), then ask to enter n (required amount of) numbers
to perform the addition of all the numbers and display the addition result on the output screen.

Source Code

import java.util.Scanner;

public class AddNumber

Accord Info Matrix


Chennai
Java Faculty Guide 84

public static void main(String args[])

int i, n, sum=0, num;

Scanner scan = new Scanner(System.in);

System.out.print("How many Number You want to Enter to Add them ? ");

n = scan.nextInt();

System.out.print("Enter " +n+ " numbers : ");

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

num = scan.nextInt();

sum = sum + num;

System.out.print("Sum of all " +n+ " numbers is " +sum);

Interchange Two Numbers

To interchange two numbers in Java Programming, make a variable say temp of the same type,
place the first number to the temp, then place the second number to the first and place temp
to the second.

Source Code

import java.util.Scanner;

Accord Info Matrix


Chennai
Java Faculty Guide 85

public class Swapping

public static void main(String args[])

int a, b, temp;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Value of A and B :\n");

System.out.print("A = ");

a = scan.nextInt();

System.out.print("B = ");

b = scan.nextInt();

temp = a;

a = b;

b = temp;

System.out.print("Number Interchanged Successfully..!!\n");

System.out.print("A = " +a);

System.out.print("\nB = " +b);

}}

Accord Info Matrix


Chennai
Java Faculty Guide 86

Reverse Number

To reverse a number in Java Programming, you have to ask to the user to enter the number.
Start reversing the number, first make a variable rev and place 0 to rev initially, and make one
more variable say rem. Now place the modulus of the number to rem and place rev*10+rem to
the variable rev, now divide the number with 10 and continue until the number will become 0.

Source Code

import java.util.Scanner;

public class ReverseNumber

public static void main(String args[])

int num, rev=0, rem;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

while(num != 0)

rem = num%10;

rev = rev*10 + rem;

num = num/10;

System.out.print("Reverse = " +rev);

Accord Info Matrix


Chennai
Java Faculty Guide 87

Count Positive, Negative and Zero

To count the number of positive number, negative number, and zero from the given set of
numbers entered by the user, you have to first ask to the user to enter a set of numbers (10
numbers here) to check all the number using for loop to count how many positive, negative,
and zero present in the provided set of numbers and display the output on the screen as shown
in the following program.

Source Code

import java.util.Scanner;

public class PositiveZeroNegative

public static void main(String args[])

int countp=0, countn=0, countz=0, i;

int arr[] = new int[10];

Scanner scan = new Scanner(System.in);

System.out.print("Enter 10 Numbers : ");

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

arr[i] = scan.nextInt();

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

Accord Info Matrix


Chennai
Java Faculty Guide 88

if(arr[i] < 0)

countn++;

else if(arr[i] == 0)

countz++;

else

countp++;

System.out.print(countp + " Positive Numbers");

System.out.print("\n" + countn + " Negative Numbers");

System.out.print("\n" + countz + " Zero");

Print Prime Numbers

To print all the prime numbers between the particular range provided by the user in Java
Programming, you have to check the division from 2 to one less than that number (say n-1), if
the number divided to any number from 2 to on less than that number then that number will
not be prime, otherwise that number will be prime number.

Accord Info Matrix


Chennai
Java Faculty Guide 89

Source Code

import java.util.Scanner;

public class PrimeSeries

public static void main(String args[])

int start, end, i, j, count=0;

Scanner scan = new Scanner(System.in);

System.out.print("Enter the Range :\n");

System.out.print("Enter Starting Number : ");

start = scan.nextInt();

System.out.print("Enter Ending Number : ");

end = scan.nextInt();

System.out.print("Prime Numbers Between " + start + " and " +end+ " is :\n");

for(i=start; i<=end; i++)

count = 0;

for(j=2; j<i; j++)

if(i%j == 0)

Accord Info Matrix


Chennai
Java Faculty Guide 90

count++;

break;

if(count == 0)

System.out.print(i + " ");

Find Largest of Three Numbers

To find the largest number of/in three numbers in Java Programming, you have to ask to the
user to enter the three numbers, now start checking which one is the largest number, after
finding the largest number, display that number as the largest number of the three number
without using logical operator on the screen as shown in the following program.

Source Code

import java.util.Scanner;

public class LargestOfThree

public static void main(String args[])

int a, b, c, big;

Accord Info Matrix


Chennai
Java Faculty Guide 91

Scanner scan = new Scanner(System.in);

System.out.print("Enter Three Numbers : ");

a = scan.nextInt();

b = scan.nextInt();

c = scan.nextInt();

// let a is the largest

big = a;

if(big<b)

if(b>c)

big = b;

else

big = c;

else if(big<c)

Accord Info Matrix


Chennai
Java Faculty Guide 92

if(c>b)

big = c;

else

big = b;

else

big = a;

System.out.print("Largest Number is " +big);

Find Factorial of a Number

To find the factorial of any number in Java Programming, you have to ask to the user to enter
the number, now find the factorial of the entered number using for loop and display the
factorial result of the given number on the output screen as shown in the following program.

Accord Info Matrix


Chennai
Java Faculty Guide 93

Source Code

import java.util.Scanner;

public class Factorial

public static void main(String args[])

int num, i, fact=1;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Number : ");

num = scan.nextInt();

for(i=num; i>0; i--)

fact = fact*i;

System.out.print("Factorial of " + num + " is " + fact);

Find HCF & LCM of Two Numbers

To find the HCF and LCF of two number in Java Programming, you have to ask to the user to
enter the two number, to find the HCF and LCF of the given two number to display the value of
the HCF and LCM of the two numbers on the output screen as shown in the following program.

Accord Info Matrix


Chennai
Java Faculty Guide 94

Source Code

import java.util.Scanner;

public class HCFLCM

public static void main(String args[])

int a, b, x, y, t, hcf, lcm;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Number : ");

x = scan.nextInt();

y = scan.nextInt();

a = x;

b = y;

while(b != 0)

t = b;

b = a%b;

a = t;

Accord Info Matrix


Chennai
Java Faculty Guide 95

hcf = a;

lcm = (x*y)/hcf;

System.out.print("HCF = " +hcf);

System.out.print("\nLCM = " +lcm);

Calculate Area and Perimeter of Square and Rectangle

To calculate the area and perimeter of a square and rectangle in Java Programming, you have
to ask to the user to enter length and breadth of the rectangle and side length of the square
and make two variable, one for area and one for perimeter for each to perform the
mathematical calculation and display the result on the output screen.

Source Code

import java.util.Scanner;

public class AreaPerimeter

public static void main(String args[])

int len, bre, peri, area;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Length and Breadth of Rectangle : ");

len = scan.nextInt();

bre = scan.nextInt();

Accord Info Matrix


Chennai
Java Faculty Guide 96

area = len*bre;

peri = (2*len) + (2*bre);

System.out.print("Area = " +area);

System.out.print("\nPerimeter = " +peri);

Calculate Area & Circumference of Circle

To calculate the area and circumference of any circle in Java Programming, you have to ask to
the user to enter the radius of the circle and initialize the radius value in the variable say r and
make two variable, one to store the area of the circle and the other to store the circumference
of the circle, and place 3.14*r*r in area and 2*3.14*r in circumference, then display the result
on the output screen.

Source Code

import java.util.Scanner;

public class AreaCircumference

public static void main(String args[])

float r;

double area, circum;

Scanner scan = new Scanner(System.in);

Accord Info Matrix


Chennai
Java Faculty Guide 97

System.out.print("Enter Radius of Circle : ");

r = scan.nextFloat();

area = 3.14*r*r;

circum = 2*3.14*r;

System.out.print("Area of Circle = " +area);

System.out.print("\nCircumference of Circle = " +circum);

Convert Fahrenheit to Centigrade

To convert Fahrenheit to centigrade in Java programming, you have to ask to the user to enter
the temperature in Fahrenheit temperature to convert it into centigrade to display the
equivalent temperature value in centigrade as shown in the following program.

Source Code

import java.util.Scanner;

public class Fahrenheit

public static void main(String args[])

float fah;

Accord Info Matrix


Chennai
Java Faculty Guide 98

double cel;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Temperature in Fahrenheit : ");

fah = scan.nextFloat();

cel = (fah-32) / 1.8;

System.out.print("Equivalent Temperature in Celsius = " + cel);

}}

Convert Centigrade to Fahrenheit

To convert centigrade to Fahrenheit in Java Programming, you have to ask to the user to enter
the temperature in centigrade to convert it into Fahrenheit to display the equivalent
temperature in Fahrenheit as shown in the following program.

Source Code

import java.util.Scanner;

public class Centigrade

public static void main(String args[])

float cen;

double fah;

Scanner scan = new Scanner(System.in);

Accord Info Matrix


Chennai
Java Faculty Guide 99

System.out.print("Enter Temperature in Centigrade : ");

cen = scan.nextFloat();

fah = (1.8*cen) + 32;

System.out.print("Equivalent Temperature in Fahrenheit = " + fah);

Print ASCII Values of Characters

To print the ASCII values of all the character in Java Programming, use the number from 1 to
255 and place their equivalent character as shown in the following program.

Source Code

public class PrintAscii{

public static void main(String args[]) {

String ch;

int i;

for(i=1; i<=255; i++)

ch = new Character((char)i).toString();

System.out.print(i+ " -> " + ch + "\t");

}}}

Accord Info Matrix


Chennai
Java Faculty Guide 100

Print Fibonacci Series

To print Fibonacci series in Java Programming, you have to first print the starting two of the
Fibonacci series and make a while loop to start printing the next number of the Fibonacci series.
Use the three variables say a, b and c. Place b in c and c in a, and now place a+b in c to print the
value of c to make the Fibonacci series as shown in the following program.

Source Code

import java.util.Scanner;

public class Fibonacci

public static void main(String args[])

int a=0, b=1, c=0, limit;

Scanner scan = new Scanner(System.in);

System.out.print("Upto How Many Term ? ");

limit = scan.nextInt();

System.out.print("Fibonacci Series : " + a + " " + b + " ");

c = a + b;

limit = limit - 2;

while(limit>0)

Accord Info Matrix


Chennai
Java Faculty Guide 101

System.out.print(c + " ");

a = b;

b = c;

c = a + b;

limit--;

Check Armstrong or Not

To check whether a number is an Armstrong number or not Armstrong number in Java


Programming, you have to ask to the user to enter the number, now check whether the
entered number is an Armstrong number or not as shown in the following program.

To check whether any positive number is an Armstrong number or not, you have to perform the
summation of, three times multiplication of, all the digits present in the number, if the
summation result is equal to the actual number then the number will be an Armstrong number,
otherwise the number will not be an Armstrong number, following is the example :

Since 153 = 1*1*1 + 5*5*5 + 3*3*3. So 153 is an Armstrong number

Since 12 is not equal to 1*1*1+2*2*2. So 12 is not an Armstrong number

Source Code

import java.util.Scanner;

Accord Info Matrix


Chennai
Java Faculty Guide 102

public class Armstrong

public static void main(String args[])

int n, nu, num=0, rem;

Scanner scan = new Scanner(System.in);

System.out.print("Enter any Positive Number : ");

n = scan.nextInt();

nu = n;

while(nu != 0)

rem = nu%10;

num = num + rem*rem*rem;

nu = nu/10;

if(num == n)

System.out.print("Armstrong Number");

else

Accord Info Matrix


Chennai
Java Faculty Guide 103

System.out.print("Not an Armstrong Number");

Generate Armstrong Numbers

To generate Armstrong number in Java Programming, you have to ask to the user to enter the
interval in which he/she want to generate Armstrong numbers between desired range as
shown in the following program.

Source Code

import java.util.Scanner;

public class ArmstrongSeries

public static void main(String args[])

int num1, num2, i, n, rem, temp, count=0;

Scanner scan = new Scanner(System.in);

System.out.print("Enter the Interval :\n");

System.out.print("Enter Starting Number : ");

num1 = scan.nextInt();

System.out.print("Enter Ending Number : ");

Accord Info Matrix


Chennai
Java Faculty Guide 104

num2 = scan.nextInt();

for(i=num1+1; i<num2; i++)

temp = i;

n = 0;

while(temp != 0)

rem = temp%10;

n = n + rem*rem*rem;

temp = temp/10;

if(i == n)

if(count == 0)

System.out.print("Armstrong Numbers Between the Given Interval are :\n");

System.out.print(i + " ");

count++;

if(count == 0)

Accord Info Matrix


Chennai
Java Faculty Guide 105

System.out.print("Armstrong Number not Found between the Given Interval.");

Find ncR nPr

To find ncR and nPr in Java Programming, you have to ask to the user to enter the value of n
and r to find the ncR and nPr to display the value of ncR and nPr on the screen as shown in the
following program.

Source Code

import java.util.Scanner;

public class NCRNPR

public static int fact(int num)

int fact=1, i;

for(i=1; i<=num; i++)

fact = fact*i;

return fact;

public static void main(String args[])

Accord Info Matrix


Chennai
Java Faculty Guide 106

int n, r;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Value of n : ");

n = scan.nextInt();

System.out.print("Enter Value of r : ");

r = scan.nextInt();

System.out.print("NCR = " +(fact(n)/(fact(n-r)*fact(r))));

System.out.print("\nNPR = " +(fact(n)/(fact(n-r))));

Print Patterns

To print patterns in Java Programming, you have to use two loops, first is outer loop and the
second is inner loop. The outer loop is responsible for rows and the inner loop is responsible for
columns.

Accord Info Matrix


Chennai
Java Faculty Guide 107

Source Code

public class Pattern

public static void main(String args[])

int i, j, n=1;

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

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

System.out.print(n+ " ");

n++;

System.out.println();

Print Diamond Pattern

To print diamond pattern in Java Programming, you have to use six for loops, the first for loop
(outer loop) contains two for loops, in which the first for loop is to print the spaces, and the
second for loop print the stars to make the pyramid of stars. Now the second for loop (outer
loop) also contains the two for loop, in which the first for loop is to print the spaces and the
second for loop print the stars to make the reverse pyramid of stars, which wholly makes
Diamond pattern of stars as shown in the following program.

Accord Info Matrix


Chennai
Java Faculty Guide 108

Source Code

import java.util.Scanner;

public class DiamondPattern

public static void main(String args[])

int n, c, k, space=1;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Number of Rows (for Diamond Dimension) : ");

n = scan.nextInt();

space = n-1;

for(k=1; k<=n; k++)

for(c=1; c<=space; c++)

System.out.print(" ");

space--;

for(c=1; c<=(2*k-1); c++)

Accord Info Matrix


Chennai
Java Faculty Guide 109

System.out.print("*");

System.out.println();

space = 1;

for(k=1; k<=(n-1); k++)

for(c=1; c<=space; c++)

System.out.print(" ");

space++;

for(c=1; c<=(2*(n-k)-1); c++)

System.out.print("*");

System.out.println();

Accord Info Matrix


Chennai
Java Faculty Guide 110

Print Floyd Triangle

To print the Floyd's triangle in Java programming, you have to use two for loops, the outer loop
is responsible for rows and the inner loop is responsible for columns and start printing the
Floyd's triangle as shown in the following program.

Source Code

import java.util.Scanner;

public class FloydTriangle

public static void main(String args[])

int range, i, j, k=1;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Range (Upto How Many Line ?) : ");

range = scan.nextInt();

System.out.print("Floyd's Triangle :\n");

for(i=1; i<=range; i++)

for(j=1; j<=i; j++, k++)

System.out.print(k + " ");

Accord Info Matrix


Chennai
Java Faculty Guide 111

System.out.println();

Print Pascal Triangle

To print pascal triangle in Java Programming, you have to use three for loops and start printing
pascal triangle as shown in the following example.

Source Code

import java.util.Scanner;

public class PascalTriangle

public static void main(String args[])

int r, i, k, number=1, j;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Number of Rows : ");

r = scan.nextInt();

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

for(k=r; k>i; k--)

Accord Info Matrix


Chennai
Java Faculty Guide 112

System.out.print(" ");

number = 1;

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

System.out.print(number+ " ");

number = number * (i - j) / (j + 1);

System.out.println();

One Dimensional Array Program

To print one dimensional array in Java Programming you have to use only one for loop as
shown in the following program.

Source Code

import java.util.Scanner;

public class OneDimensionArray

public static void main(String args[])

Accord Info Matrix


Chennai
Java Faculty Guide 113

int arr[] = new int[50];

int n, i;

Scanner scan = new Scanner(System.in);

System.out.print("How Many Element You Want to Store in Array ? ");

n = scan.nextInt();

System.out.print("Enter " + n + " Element to Store in Array : ");

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

arr[i] = scan.nextInt();

System.out.print("Elements in Array is :\n");

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

System.out.print(arr[i] + " ");

Accord Info Matrix


Chennai
Java Faculty Guide 114

Find Largest Element in Array

To find the largest element in an array in Java Programming, first you have to ask to the user to
enter the size and elements of the array. Now start finding for the largest element in the array
to display the largest element of the array on the output screen as shown in the following
program.

Source Code

import java.util.Scanner;

public class Largest

public static void main(String args[])

int large, size, i;

int arr[] = new int[50];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");

size = scan.nextInt();

System.out.print("Enter Array Elements : ");

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

arr[i] = scan.nextInt();

System.out.print("Searching for the Largest Number....\n\n");

Accord Info Matrix


Chennai
Java Faculty Guide 115

large = arr[0];

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

if(large < arr[i]) //for smallest if(small >arr[i])

large = arr[i];

System.out.print("Largest Number = " +large);

Reverse Array

To reverse an array in Java Programming, you have to ask to the user to enter the array size and
then the array elements. Now start swapping the array elements. Make a variable say temp of
the same type. And place the first element in the temp, then the last element in the first, and
temp in the last and so on.

Source Code

import java.util.Scanner;

public class ArrayReverse

public static void main(String args[])

Accord Info Matrix


Chennai
Java Faculty Guide 116

int size, i, j, temp;

int arr[] = new int[50];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");

size = scan.nextInt();

System.out.print("Enter Array Elements : ");

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

arr[i] = scan.nextInt();

j = i - 1; // now j will point to the last element

i = 0; // and i will point to the first element

while(i<j)

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

i++;

j--;

Accord Info Matrix


Chennai
Java Faculty Guide 117

System.out.print("Now the Reverse of Array is : \n");

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

System.out.print(arr[i]+ " ");

Delete Element from Array

To delete any element from an array in Java programming, you have to first ask to the user to
enter the size and elements of the array, now ask to enter the element/number which is to be
delete. Now to delete that element from the array first you have to search that element to
check whether that number is present in the array or not, if found then place the next element
after the founded element to the back until the last as shown in the following program.You can
also use any of the following two searching techniques available in Java to search the required
element which is going to delete from the array:

Source Code

import java.util.Scanner;

public class DeleteElement

public static void main(String args[])

Accord Info Matrix


Chennai
Java Faculty Guide 118

int size, i, del, count=0;

int arr[] = new int[50];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");

size = scan.nextInt();

System.out.print("Enter Array Elements : ");

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

arr[i] = scan.nextInt();

System.out.print("Enter Element to be Delete : ");

del = scan.nextInt();

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

if(arr[i] == del)

for(int j=i; j<(size-1); j++)

arr[j] = arr[j+1];

count++;

break;

Accord Info Matrix


Chennai
Java Faculty Guide 119

if(count==0)

System.out.print("Element Not Found..!!");

else

System.out.print("Element Deleted Successfully..!!");

System.out.print("\nNow the New Array is :\n");

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

System.out.print(arr[i]+ " ");

Two Dimensional Array Program

Two dimensional array can be made in Java Programming language by using the two loops, the
first one is outer loop and the second one is inner loop. Outer loop is responsible for rows and
the inner loop is responsible for columns. And both rows and columns combine to make two-
dimensional (2D) Arrays.

Accord Info Matrix


Chennai
Java Faculty Guide 120

Source Code

import java.util.Scanner;

public class TwoDimension

public static void main(String args[])

int row, col, i, j;

int arr[][] = new int[10][10];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Number of Row for Array (max 10) : ");

row = scan.nextInt();

System.out.print("Enter Number of Column for Array (max 10) : ");

col = scan.nextInt();

System.out.print("Enter " +(row*col)+ " Array Elements : ");

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

for(j=0; j<col; j++)

arr[i][j] = scan.nextInt();

Accord Info Matrix


Chennai
Java Faculty Guide 121

System.out.print("The Array is :\n");

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

for(j=0; j<col; j++)

System.out.print(arr[i][j]+ " ");

System.out.println();

Add Two Matrices

To add two matrices in Java Programming, you have to ask to the user to enter the elements of
both the 3*3 matrix, now start adding the two matrix to form a new/third matrix which is the
addition result of the two given matrix. After adding the two matrices, display the third matrix
which is the result of the addition of the two matrices.

Source Code

import java.util.Scanner;

public class AddMatrix

public static void main(String args[])

int i, j;

int mat1[][] = new int[3][3];

Accord Info Matrix


Chennai
Java Faculty Guide 122

int mat2[][] = new int[3][3];

int mat3[][] = new int[3][3];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Matrix 1 Elements : ");

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

for(j=0; j<3; j++)

mat1[i][j] = scan.nextInt();

System.out.print("Enter Matrix 2 Elements : ");

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

for(j=0; j<3; j++)

mat2[i][j] = scan.nextInt();

System.out.print("Adding both Matrix to form the Third Matrix...\n");

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

Accord Info Matrix


Chennai
Java Faculty Guide 123

for(j=0; j<3; j++)

mat3[i][j] = mat1[i][j] + mat2[i][j];

System.out.print("The Two Matrix Added Successfully..!!\n");

System.out.print("The New Matrix will be :\n");

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

for(j=0; j<3; j++)

System.out.print(mat3[i][j]+ " ");

System.out.println();

Accord Info Matrix


Chennai
Java Faculty Guide 124

Subtract Two Matrices

To subtract two matrices in Java Programming, you have to ask to the user to enter the two
matrix, then start subtracting the matrices i.e., subtract matrix second from the matrix first like
mat1[0][0] - mat2[0][0], mat1[1][1] - mat2[1][1], and so on. Store the subtraction result in the
third matrix say mat3[0][0], mat3[1][1], and so on.

Source Code

import java.util.Scanner;

public class SubtractingMatrix

public static void main(String args[])

int i, j;

int mat1[][] = new int[3][3];

int mat2[][] = new int[3][3];

int mat3[][] = new int[3][3];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Matrix 1 Elements : ");

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

for(j=0; j<3; j++)

mat1[i][j] = scan.nextInt();

Accord Info Matrix


Chennai
Java Faculty Guide 125

System.out.print("Enter Matrix 2 Elements : ");

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

for(j=0; j<3; j++)

mat2[i][j] = scan.nextInt();

System.out.print("Subtracting Matrices (i.e. Matrix1 - Matrix2)...\n");

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

for(j=0; j<3; j++)

mat3[i][j] = mat1[i][j] - mat2[i][j];

System.out.print("Result of Matrix1 - Matrix2 is :\n");

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

for(j=0; j<3; j++)

System.out.print(mat3[i][j]+ " ");

Accord Info Matrix


Chennai
Java Faculty Guide 126

System.out.println();

Transpose Matrix

To transpose any matrix in Java Programming, first you have to ask to the user to enter the
matrix elements. Now, to transpose any matrix, you have to replace the row elements by the
column elements and vice-versa.

Source Code

import java.util.Scanner;

public class TransposeMatrix

public static void main(String args[])

int i, j;

int arr[][] = new int[3][3];

int arrt[][] = new int[3][3];

Scanner scan = new Scanner(System.in);

System.out.print("Enter 3*3 Array Elements : ");

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

Accord Info Matrix


Chennai
Java Faculty Guide 127

for(j=0; j<3; j++)

arr[i][j] = scan.nextInt();

System.out.print("Transposing Array...\n");

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

for(j=0; j<3; j++)

arrt[i][j] = arr[j][i];

System.out.print("Transpose of the Matrix is :\n");

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

for(j=0; j<3; j++)

System.out.print(arrt[i][j]+ " ");

System.out.println();

}}

Accord Info Matrix


Chennai
Java Faculty Guide 128

Multiply Two Matrices

To multiply two matrices in Java Programming, you have to first ask to the user to enter the
number of rows and columns of the first matrix and then ask to enter the first matrix elements.
Again ask the same for the second matrix. Now start multiplying the two matrices and store the
multiplication result inside any variable say sum and finally store the value of sum in the third
matrix say multiply[ ][ ] at the equivalent index as shown in the following program.

Source Code

import java.util.Scanner;

public class MatrixMultiplication

public static void main(String args[])

int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);

System.out.print("Enter Number of Rows and Columns of First Matrix : ");

m = in.nextInt();

n = in.nextInt();

int first[][] = new int[m][n];

System.out.print("Enter First Matrix Elements : ");

for(c=0 ; c<m; c++)

Accord Info Matrix


Chennai
Java Faculty Guide 129

for(d=0; d<n; d++)

first[c][d] = in.nextInt();

System.out.print("Enter Number of Rows and Columns of Second Matrix : ");

p = in.nextInt();

q = in.nextInt();

if ( n != p )

System.out.print("Matrix of the entered order can't be Multiplied..!!");

else

int second[][] = new int[p][q];

int multiply[][] = new int[m][q];

System.out.print("Enter Second Matrix Elements :\n");

for(c=0; c<p; c++)

Accord Info Matrix


Chennai
Java Faculty Guide 130

for(d=0; d<q; d++)

second[c][d] = in.nextInt();

System.out.print("Multiplying both Matrix...\n");

for(c=0; c<m; c++)

for(d=0; d<q; d++)

for(k=0; k<p; k++)

sum = sum + first[c][k]*second[k][d];

multiply[c][d] = sum;

sum = 0;

System.out.print("Multiplication Successfully performed..!!\n");

System.out.print("Now the Matrix Multiplication Result is :\n");

Accord Info Matrix


Chennai
Java Faculty Guide 131

for(c=0; c<m; c++)

for(d=0; d<q; d++)

System.out.print(multiply[c][d] + "\t");

System.out.print("\n");

}}

Copy String

To copy string in Java Programming, you have to ask to the user to enter the string to make
copy to another variable say strCopy and display this variable which is the copied value of the
given string as shown in the following program.

Source Code

import java.util.Scanner;

public class StringCopy

public static void main(String args[])

String strOrig;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");

strOrig = scan.nextLine();

Accord Info Matrix


Chennai
Java Faculty Guide 132

System.out.print("Copying String...\n");

StringBuffer strCopy = new StringBuffer(strOrig);

System.out.print("String Copied Successfully..!!\n");

System.out.print("The Copied String is " + strCopy);

Reverse String

To reverse any string in Java Programming, you have to ask to the user to enter the string and
start placing the character present at the last index of the original string in the first index of the
reverse string (make a variable say rev to store the reverse of the original string).

Source Code

import java.util.Scanner;

public class ReverseString

public static void main(String args[])

String orig, rev="";

int i, len;

Accord Info Matrix


Chennai
Java Faculty Guide 133

Scanner scan = new Scanner(System.in);

System.out.print("Enter a String to Reverse : ");

orig = scan.nextLine();

len = orig.length();

for(i=len-1; i>=0; i--)

rev = rev + orig.charAt(i);

System.out.print("Reverse of Entered String is : " +rev);

Remove Vowels from String

To delete or remove vowels from string in Java programming, you have to first ask to the user
to enter the string and start deleting/removing all the vowels present in the string as shown in
the following two programs.

Here, we have two methods to delete vowels from the string, first method is shortcut method
that uses the method replaceAll() to replace all the vowels with no-space (in short deleting all
the vowels using this method shortly) from the string then copy that string into another string
without having any vowels whereas the second method is to remove/delete vowels manually.

Accord Info Matrix


Chennai
Java Faculty Guide 134

Source Code

import java.util.Scanner;

public class RemovingVowel

public static void main(String args[])

String strOrig, strNew;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");

strOrig = scan.nextLine();

System.out.print("Removing Vowels from The String [" +strOrig+ "]\n");

strNew = strOrig.replaceAll("[aeiouAEIOU]", "");

System.out.print("All Vowels Removed Successfully..!!\nNow the String is :\n");

System.out.print(strNew);

Source Code

import java.util.Scanner;

public class VowelsRemove

Accord Info Matrix


Chennai
Java Faculty Guide 135

public static void main(String args[])

String str, r;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");

str = scan.nextLine();

System.out.print("Removing Vowels from String [" +str+ "]\n");

r = removeVowels(str);

System.out.print("Vowels Removed from the Entered String Successfully..!!\nNow the String


is :\n");

System.out.print(r);

private static String removeVowels(String s)

String finalString = "";

int i;

for(i=0; i<s.length(); i++)

Accord Info Matrix


Chennai
Java Faculty Guide 136

if (!isVowel(Character.toLowerCase(s.charAt(i))))

finalString = finalString + s.charAt(i);

return finalString;

private static boolean isVowel(char c)

String vowels = "aeiou";

int i;

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

if(c == vowels.charAt(i))

return true;

return false;

Accord Info Matrix


Chennai
Java Faculty Guide 137

Delete Words from Sentence

To delete any particular word from the string/sentence in Java Programming, first, you have to
ask to the user to enter the string/sentence, second ask to enter the any word present in the
string/sentence to delete that word from the string. After asking the two, now check for the
presence of that word and perform the deletion of that word from the sentence as shown in
the following program.

Source Code

import java.util.Scanner;

public class DeleteWord

public static void main(String args[])

String strOrig, word;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");

strOrig = scan.nextLine();

System.out.print("Enter a Word to be Delete from the String : ");

word = scan.nextLine();

System.out.print("Deleting all '" + word + "' from '" + strOrig + "'...\n");

strOrig = strOrig.replaceAll(word, "");

Accord Info Matrix


Chennai
Java Faculty Guide 138

System.out.print("Specified word deleted Successfully from the String..!!");

System.out.print("\nNow the String is :\n");

System.out.print(strOrig);

Find Frequency of Character

To find the frequency or to count the occurrence of all the characters present in the
string/sentence, you have to ask to the user to enter the string, now start searching for the
occurrence of all the characters present inside the string to find the frequency of all the
characters in the string/sentence and display the frequency of all the characters on the output
screen as shown in the following program.

Source Code

import java.util.Scanner;

public class characterOccurance

public static void main(String args[])

int ci, i, j, k, l=0;

String str, str1;

char c, ch;

Scanner scan = new Scanner(System.in);

Accord Info Matrix


Chennai
Java Faculty Guide 139

System.out.print("Enter a String : ");

str=scan.nextLine();

i=str.length();

for(c='A'; c<='z'; c++)

k=0;

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

ch = str.charAt(j);

if(ch == c)

k++;

if(k>0)

System.out.println("The character " + c + " has occurred for " + k + " times");

Accord Info Matrix


Chennai
Java Faculty Guide 140

Count Word in Sentence

To count the occurrence of all the words present in a string/sentence in Java Programming,
first, you have to ask to the user to enter the sentence and start counting all the words with
present in the given string/sentence using the method countWords() as shown in the following
program.

Source Code

import java.util.Scanner;

public class CountWords

public static int countWords(String str)

int count = 1;

for(int i=0; i<=str.length()-1; i++)

if(str.charAt(i) == ' ' && str.charAt(i+1)!=' ')

count++;

return count;

public static void main(String args[])

String sentence;

Scanner scan = new Scanner(System.in);

Accord Info Matrix


Chennai
Java Faculty Guide 141

System.out.print("Enter a Sentence : ");

sentence = scan.nextLine();

System.out.print("Total Number of Words in Entered Sentence is " +


countWords(sentence));

Remove Spaces from String

To remove/delete spaces from the string or sentence in Java programming, you have to ask to
the user to enter the string. Now replace all the spaces from the string using the method
replaceAll().

Source Code

import java.util.Scanner;

public class RemoveSpace

public static void main(String args[])

String str, strWithoutSpace;

int i;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Sentence : ");

str = scan.nextLine();

Accord Info Matrix


Chennai
Java Faculty Guide 142

//1. Using replaceAll() Method

strWithoutSpace = str.replaceAll(" ", "");

System.out.println(strWithoutSpace);

//2. Without Using replaceAll() Method

char[] strArray = str.toCharArray();

StringBuffer sb = new StringBuffer();

for (i = 0; i < strArray.length; i++)

if( (strArray[i] != ' ') && (strArray[i] != '\t') )

sb.append(strArray[i]);

System.out.println(sb);

}}

Accord Info Matrix


Chennai
Java Faculty Guide 143

Sort String

To sort strings in alphabetical order in Java programming, you have to ask to the user to enter
the two string, now start comparing the two strings, if found then make a variable say temp of
the same data type, now place the first string to the temp, then place the second string to the
first, and place temp to the second string and continue.

Source Code

import java.util.Scanner;

public class SortString

public static void main(String[] input)

int i, j;

String temp;

Scanner scan = new Scanner(System.in);

String names[] = new String[5];

System.out.print("Enter 5 Names/Words : ");

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

names[i] = scan.nextLine();

System.out.println("\nSorting Words/Names in Alphabetical Order...\n");

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

Accord Info Matrix


Chennai
Java Faculty Guide 144

for(j=1; j<5; j++)

if(names[j-1].compareTo(names[j])>0)

temp=names[j-1];

names[j-1]=names[j];

names[j]=temp;

System.out.print("Words/Names Sorted in Alphabetical Order Successfully..!!");

System.out.println("\nNow the List is :\n");

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

System.out.println(names[i]);

Accord Info Matrix


Chennai
Java Faculty Guide 145

Convert Uppercase to Lowercase

To convert or change uppercase string or character to lowercase string or character in Java


Programming, use the ASCII values of character to convert any character from uppercase to
lowercase as shown in the first program. And the second program uses the method
toLowerCase() to convert string from uppercase to lowercase.

Source Code

import java.util.Scanner;

public class UpperToLowerCase{

public static void main(String[] input) {

char ch;

int temp;

Scanner scan = new Scanner(System.in);

System.out.print("Enter a Character in Uppercase : ");

ch = scan.next().charAt(0);

temp = (int) ch;

temp = temp + 32; //for lowercase temp = temp - 32;

ch = (char) temp;

System.out.print("Equivalent Character in Lowercase = " + ch);

Accord Info Matrix


Chennai
Java Faculty Guide 146

Swap Two Strings

To swap two string in Java Programming, you have to first ask to the user to enter the two
string, then make a temp variable of the same type. Now place the first string in the temp
variable, then place the second string in the first, now place the temp string in the second.

Source Code

import java.util.Scanner;

public class SwappingString

public static void main(String[] input)

String str1, str2, strtemp;

Scanner scan = new Scanner(System.in);

System.out.print("Enter First String : ");

str1 = scan.nextLine();

System.out.print("Enter Second String : ");

str2 = scan.nextLine();

System.out.println("\nStrings before Swapping are :");

System.out.print("String 1 = " +str1+ "\n");

System.out.print("String 2 = " +str2+ "\n");

strtemp = str1;

str1 = str2;

Accord Info Matrix


Chennai
Java Faculty Guide 147

str2 = strtemp;

System.out.println("\nStrings after Swapping are :");

System.out.print("String 1 = " +str1+ "\n");

System.out.print("String 2 = " +str2+ "\n");

1. Check Anagram or Not

2. To check whether the two string are anagram or not anagram in Java programming, you have to
ask to the user to enter the two string to start checking for anagram.

Source Code

import java.util.Scanner;

public class CheckAnagram

public static void main(String[] input)

String str1, str2;

int len, len1, len2, i, j, found=0, not_found=0;

Scanner scan = new Scanner(System.in);

System.out.print("Enter First String : ");

str1 = scan.nextLine();

Accord Info Matrix


Chennai
Java Faculty Guide 148

System.out.print("Enter Second String : ");

str2 = scan.nextLine();

len1 = str1.length();

len2 = str2.length();

if(len1 == len2)

len = len1;

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

found = 0;

for(j=0; j<len; j++)

if(str1.charAt(i) == str2.charAt(j))

found = 1;

break;

if(found == 0)

not_found = 1;

break;

Accord Info Matrix


Chennai
Java Faculty Guide 149

if(not_found == 1)

System.out.print("Strings are not Anagram to Each Other..!!");

else

System.out.print("Strings are Anagram");

else

System.out.print("Both Strings Must have the same number of Character to be an


Anagram");

Accord Info Matrix


Chennai
Java Faculty Guide 150

Generate Random Numbers

To generate random numbers in Java programming, you have to create the object of Random
class available in the java.util.Random package as shown in the following program.

Source Code

import java.util.Scanner;

import java.util.Random;

public class RandomNumber

public static void main(String[] input)

int len, i, randnum;

Random rn = new Random();

Scanner scan = new Scanner(System.in);

System.out.print("How Many Random Numbers You want to Generate ? ");

len = scan.nextInt();

System.out.print("\nGenerating " + len + " Random Numbers in the range 0...999 \n");

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

randnum = rn.nextInt(1000);

System.out.print(randnum + " ");

Accord Info Matrix


Chennai
Java Faculty Guide 151

Print Date and Time

To print date and time in Java programming, you have to create and use the object of Date
class. Let's see the following program to know how to print date and time in Java.

Source Code

import java.util.*;

import java.text.*;

public class PrintDate

public static void main(String args[])

Date dNow = new Date( );

SimpleDateFormat ft1 = new SimpleDateFormat ("dd/MM/yyyy");

SimpleDateFormat ft2 = new SimpleDateFormat("E");

SimpleDateFormat ft3 = new SimpleDateFormat("hh:mm:ss a");

System.out.println("The Current Date is " + ft1.format(dNow));

System.out.println("Today is " + ft2.format(dNow));

System.out.println("The Current Time is " + ft3.format(dNow));

Accord Info Matrix


Chennai
Java Faculty Guide 152

9 – Exception Handling
TOPIC TO COVER
 What is exception?
 How to differentiate exception and error
 What is Exception Handling?
 Advantage – Exception class hierarchy – checked and unchecked Exception
 Handling Exception
 Try, catch, throw and throws, try with multi catch, nested try catch
 Creating Custom Exception

Exception
An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications, or the JVM has run out
of memory.
How to differentiate exception and error

S.NO ERROR EXCEPTION

1 All errors in java are unchecked type Exception include both checked as well as
unchecked type

2 Error happen at compile time. They will Checked enception are known to compiler
known as compiler where as unchecked excetion are not
known to compiler because thery occur at
run time

3 It is possible to recover from errors You can recover from exceptions by


handling from through try catch block

4 Errors are mostly caused by the Exceptions are mainly caused by the
environment in which application is application itself
running

5 Eg: java.lang.StackOverFlowError Eg: SQLException, IOExeption, Null pointer


Exception

Accord Info Matrix


Chennai
Java Faculty Guide 153

Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.

Advantage

To maintain the normal flow of the application. Exception normally disrupts the normal
flow of the application that is why we use exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed.

Accord Info Matrix


Chennai
Java Faculty Guide 154

Exception class Heirarchy

NOTE:
1. Checked exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2. Unchecked exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.

Accord Info Matrix


Chennai
Java Faculty Guide 155

Handling Exception

A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch
block is referred to as protected code, and the syntax for using try/catch looks like the
following:

Try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}

Accord Info Matrix


Chennai
Java Faculty Guide 156

System.out.println("Out of the block");


}
}

This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block

Multiple catch Blocks:


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:

Try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown to
the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.

Accord Info Matrix


Chennai
Java Faculty Guide 157

Example:
Here is code segment showing how to use multiple try/catch statements.

try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Try to understand the different in throws and throw
keywords.
The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation

Accord Info Matrix


Chennai
Java Faculty Guide 158

throw new RemoteException();


}
//Remainder of class definition
}

Amethod can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword


The finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred.
Using a finally block allows you to 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 the catch blocks and has the following syntax:

Try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block

Accord Info Matrix


Chennai
Java Faculty Guide 159

}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Example:

public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 160

This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed

Note the followings:


 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses when ever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.
Creating Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

class InvalidAgeException extends Exception{

InvalidAgeException(String s){

super(s);

class TestCustomException1{

static void validate(int age)throws InvalidAgeException{

if(age<18)

throw new InvalidAgeException("not valid");

else

System.out.println("welcome to vote");

public static void main(String args[]){

Accord Info Matrix


Chennai
Java Faculty Guide 161

try{

validate(13);

}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");

Lab Assignment

1. Termination of program due to abrupt exception

2. Exception handling example

3. Throws clause example

4. Throw clause example

5. Multiple catch blocks example

6. Finally block example

7. Without catch block example

8. Custom exception example

FAQ
1. How the exceptions are handled in java? OR Explain exception handling mechanism in java?

2. What is the difference between error and exception in java?

3. Can we keep other statements in between try, catch and finally blocks?

4. Can we write only try block without catch and finally blocks?

5. There are three statements in a try block – statement1, statement2 and statement3. After that
there is a catch block to catch the exceptions occurred in the try block. Assume that exception
has occurred in statement2. Does statement3 get executed or not?

6. What is unreachable catch block error?

7. What are run time exceptions in java. Give example?

8. what are checked and unchecked exceptions in java?

Accord Info Matrix


Chennai
Java Faculty Guide 162

9. What is the difference between ClassNotFoundException and NoClassDefFoundError in java?

10. Can we keep the statements after finally block If the control is returning from the finally block
itself?

11. Does finally block get executed If either try or catch blocks are returning the control?

12. What is the use of throws keyword in java?

13. Why it is always recommended that clean up operations like closing the DB resources to keep
inside a finally block?

14. What is the difference between final, finally and finalize in java?

15. How do you create customized exceptions in java?

16. What is the difference between throw, throws and throwable in java?

17. Can we override a super class method which is throwing an unchecked exception with checked
exception in the sub class?

Accord Info Matrix


Chennai
Java Faculty Guide 163

J10 – IO Package

TOPIC TO COVER
 What is IO Package
 Files and Streams (input and output stream), Dataflow, Buffered and Non - Buffered
 Writing and Reading data from file
 Serialization
 Object input stream and Object output stream
 Runtime Input

What is IO Package

The Java I/O means Java Input/Output. It is provided by the java.io package. This package has
an InputStream and OutputStream. Java InputStream is defined for reading the stream, byte
stream and array of byte stream.

Streams
Stream is used to transfer data from one place to another place.To receive data from keyboard
and process it to produce some result we need stream.
Streams carries data just as a water pipe .
Stream

Input Stream OutputStream

To read Data To Send or Write Data

Standard Streams:
Standard Streams are a feature provided by many operating systems. By default, they read
input from the keyboard and write output to the display. They also support I/O operations on
files.
Java also supports three Standard Streams:
1. Standard Input: Accessed through System.in which is used to read input from the keyboard.
2. Standard Output: Accessed through System.out which is used to write output to be display.
3. Standard Error: Accessed through System.err which is used to write error output to be display.
Java IO Purposes and Features
 The Java IO classes, which mostly consists of streams and readers / writers, are addressing
various purposes. That is why there are so many different classes. The purposes addressed are
summarized below:
 File Access

Accord Info Matrix


Chennai
Java Faculty Guide 164

 Network Access
 Internal Memory Buffer Access
 Inter-Thread Communication (Pipes)
 Buffering
 Filtering
 Parsing
 Reading and Writing Text (Readers / Writers)
 Reading and Writing Primitive Data (long, int etc.)
 Reading and Writing Objects
 Working with files via Java IO can be done in a few different ways:
 Reading files
 Writing files
 Random access to files
 File and Directory Info Access
Reading Files via Java IO
 If you need to read a file from one end to the other you can use a FileInputStream. If you need
to jump around the file and read only parts of it from here and there, you can use a
RandomAccessFile.
Writing File via Java IO
 If you need to write a file from one end to the other you can use FileOutputStream. If you need
to skip around a file and write to it in various places, for instance appending to the end of the
file, you can use a RandomAccessFile.
Random Access to Files via Java IO
 You can get random access to files via Java IO. Random doesn't mean that you read or write
from truly random places. It just means that you can skip around the file and read from or write
to it at the same time. This makes it possible to write onlyparts of an existing file, to append to
it, or delete from it.
File and Directory Info Access
 Sometimes you may need access to information about a file rather than its content. For
instance, if you need to know the file size or the file attributes of a file. The same may be true
for a directory. For instance, you may want to get a list of all files in a given directory. Both file
and directory information is available via the File class.
Creation of Files
For creating a new file File.createNewFile( ) method is used. This method returns a
booleanvalue true if the file is created otherwise return false. If the mentioned file for the
specified directory is already exist then the createNewFile() method returns the false otherwise
the method creates the mentioned file and return true.

Accord Info Matrix


Chennai
Java Faculty Guide 165

import java.io.*;
public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created
to the current directory");
}
else
{
System.out.println("Already created");
}
}
}

Constructing a File Name path

import java.io.*;
class filepath123{
public static void main(String[] args) throws IOException
{
File f=new
File("C:"+File.separator+"Users"+File.separator+"Admin"+File.separator+"Documents"+File.sep
arator+"NetBeansProjects"+File.separator+"Files" + File.separator + "myfile6.txt");
f.createNewFile();
System.out.println("New file \"myfile.txt\"has been created to the specified
location");
System.out.println("The absolute path of the file is: " +f.getAbsolutePath());
}
}
Getting name for folder and file name
File f=new File(“D:”+file.separator+s);
If(f.mkdir())
{
System.out.println(“Directory Created:”);
}
Else

Accord Info Matrix


Chennai
Java Faculty Guide 166

{
System.out.println(“Already Created”);
}
File f1=new File(f+file.separator+s1);
If(!f1.exists())
{
F1.createNewFile();
System.out.println(“Created:”);
}
Else
{
System.out.println(“Already Created”);
}

Reading A File
public class readfile {
public static void main(String aaa[])throws IOException
{
FileInputStream fin=new FileInputStream("myfile.txt");
System.out.println("File Contents");
int ch;
while((ch=fin.read())!=-1)

{
System.out.print((char)ch);
}
fin.close();

}
Reading a File using Streams
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{

Accord Info Matrix


Chennai
Java Faculty Guide 167

// Open the file that is the first


// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Reading a File-User Interaction
public class readfile1 {
public static void main(String aaa[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the File Name");
String fname = br.readLine();
FileInputStream fin = null;
try {
fin = new FileInputStream(fname);

BufferedInputStream bin = new BufferedInputStream(fin);


System.out.println("File Contents");
int ch;
while ((ch = bin.read()) != 'x') {
System.out.print((char) ch);
}
bin.close();
}
catch (FileNotFoundException e) {
System.out.println("File not Found");
}

Accord Info Matrix


Chennai
Java Faculty Guide 168

}
}

Writing data to File


public class writefile {
public static void main(String aa[])throws IOException
{
DataInputStream ob=new DataInputStream(System.in);
FileOutputStream fout=new FileOutputStream("myfile.txt");
System.out.println("Enter the Text x at the end)");
char ch;

while((ch=(char)ob.read())!='x')

fout.write(ch);
}

fout.close();

}
}

Appending Data to a file


import java.io.*;
//Writing File using BufferedoutputrStream
public class writefile1 {
public static void main(String aaa[])throws IOException
{
DataInputStream ob=new DataInputStream(System.in);
FileOutputStream fout=new FileOutputStream("myfile.txt",true);
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
System.out.println("Enter the Text press X at the end");
char ch;
while((ch=(char)ob.read())!='x')
bout.write(ch);
bout.close();
}

Accord Info Matrix


Chennai
Java Faculty Guide 169

Using Buffered Stream-Data to File


import java.io.*;
public class filex1 {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file name to create : ");
String file_name = in.readLine();
File file = new File(file_name);
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
System.exit(0);
}

else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
int n;
System.out.println("Enter how many lines to enetr");
n=Integer.parseInt(in.readLine());
for(int i=1;i<=n;i++)
{
out.write(in.readLine());
Out.newLine();
}
out.close();
System.out.println("File created successfully.");
}
}
}

File-Length
import java.io.*;
public class Filesize {

Accord Info Matrix


Chennai
Java Faculty Guide 170

public static void main(String args[])throws IOException


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the File Name");
String fname = br.readLine();
File file = new File(fname);
// File file = new File("myfile.txt");
long filesize = file.length();
long filesizeInKB = filesize / 1024;
System.out.println("Size of File is: "
+ filesizeInKB + " KB");
}
}

Counting the Lines in a File


import java.io.*;
public class Counting {
public static void main(String[] args) {
try{
System.out.println("Getting line number of a paritcular file
example!");
BufferedReader bf = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Please enter file name with extension:");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
int count = 0;
while (ln.readLine() != null){
count++;
}
System.out.println("Total line no: " + count);
ln.close();
}

else{
System.out.println("File does not exists!");

Accord Info Matrix


Chennai
Java Faculty Guide 171

}
}
catch(IOException e){
e.printStackTrace();
}
}
}

Rename the File Name


The method renameTo(new_file_instance) can be used to rename the appropriate file or
directory. Method renameTo() renames the specified file or directory and returns a boolean
value (true or false). Syntax of the renameTo() method used in this program :
oldfile.renameTo(newfile)
oldfile : oldfile is the created instance of the File class for holding the specified file or
directory name which has to be renamed in the file format.
newfile : newfile is also the instance of File class, which is the new name of file or directory

import java.io.*;
public class renameing {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file or directory name which has to be Renamed :
");
String old_name = in.readLine();
File oldfile = new File(old_name);
if(!oldfile.exists())
{
System.out.println("File or directory does not exist.");
System.exit(0);
}
System.out.print("please enter the new file or directory name : ");
String new_name = in.readLine();
File newfile = new File(new_name);
System.out.println("Old File or directory name : "+ oldfile);
System.out.println("New File or directory name : "+ newfile);
boolean Rename = oldfile.renameTo(newfile);
if(!Rename)
{

Accord Info Matrix


Chennai
Java Faculty Guide 172

System.out.println("File or directory does not rename successfully.");

System.exit(0);

else {

System.out.println("File or directory rename is successfully.");

}
File Deletion
1.deletefile(String file)
File f1 = new File(file);
and delete the file using delete function f1.delete(); which return the Boolean value
(true/false). It returns true if and only if the file or directory is successfully deleted; false
otherwise.
import java.io.*;
public class deletion{
private static void deletefile(String file)
{
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}
else{
System.out.println("File deleted.");
}
}

public static void main(String[] args){

switch(args.length){

Accord Info Matrix


Chennai
Java Faculty Guide 173

case 0: System.out.println("File has not mentioned.");

System.exit(0);

case 1: deletefile(args[0]);

System.exit(0);

default : System.out.println("Multiple files are not allow.");

System.exit(0);

Random Access File-Byte to char


import java.io.*;

public class ReadAccessFile{


public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String str = in.readLine();
File file = new File(str);
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try{
//Open the file for both reading and writing
RandomAccessFile rand = new RandomAccessFile(file,"r");
int i=(int)rand.length();
System.out.println("Length: " + i);
rand.seek(0); //Seek to start point of file

Accord Info Matrix


Chennai
Java Faculty Guide 174

for(int ct = 0; ct < i; ct++){


byte b = rand.readByte(); //read byte from the file
System.out.print((char)b); //convert byte into char
}
rand.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}

Writing Bytes to a File


public class bytes1 {
public static void main(String[] aeee)throws IOException
{
byte cities[]={'d','e','l','h','i','\n','m','a','d','r','a','s','\n','t','r','i','c','h','y'};
FileOutputStream outfile=null;
try
{
outfile=new FileOutputStream("city.txt");
outfile.write(cities);
outfile.close();
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);

}
}
}
Reading Bytes from File
import java.io.*;
public class bytes2 {
public static void main(String[] aaaa)throws IOException
{
FileInputStream infile=null;

Accord Info Matrix


Chennai
Java Faculty Guide 175

DataInputStream ob=new DataInputStream(System.in);


System.out.println("Enter File Name");
String s=ob.readLine();

int b;
try
{
infile=new FileInputStream(s);
while((b=infile.read())!=-1)
{
System.out.println((int)b);
}
infile.close();
}
catch(IOException e)
{
System.out.println(e);

} } }

Serialization

 Serilization is the process of writing the state of an object to a byte stream.


 This is useful when you want to save the state of your program to a persistent storage area,such
as a file.(Serialization)Later you may restore that by objects by using the process of
deserialization.
 Serialization is also needed to implement RMI.
 RMI allows a java object on one machine to invoke a method of a java object on a different
machine.
 An object may be supplied as an argument to that remote method.
 The sending machine serializes the objects and transmits.
 The receiving machine deserializes it.

Accord Info Matrix


Chennai
Java Faculty Guide 176

Object Serialization:

 Object can be represented as sequence of byte which have data as well as information about
states of object. Information about states of objects includes type of object and the data types
stored in the object.
 Serilization is the process of storing object contents in to file,The class whose objects are stored
in the file should implement ‘Serializable’ interface of java.io.package.
 De-serialization is a process of reading back the objects from a file.
 Serialization & deserialization is independent of JVM. It means an object can be serialized on
one platform and can also recreate or deserialized on a totally dissimilar platform.
 The ObjectOutputStream class is used to serialize a object and also contained methods
associated with Serialization.
 The ObjectInputStream class is used to deserialize a object and also contained methods
associated with Deserialization.

Uses

Serialization provides:

 a method of persisting objects, for example writing their properties to a file on disk, or saving
them to a database.
 a method of remote procedure calls, e.g., as in SOAP.
 a method for distributing objects, especially in software componentry such as COM, CORBA,
etc.
 a method for detecting changes in time-varying data.

Serializable is a marker interfaces that tells the JVM is can write out the state of the object
to some stream (basically read all the members, and write out their state to a stream, or to disk
or something). The default mechanism is a binary format.

1. Banking example: When the account holder tries to withdraw money from the server
through ATM, the account holder information along with the withdrawl details will be serialized
(marshalled/flattened to bytes) and sent to server where the details are deserialized
(unmarshalled/rebuilt the bytes)and used to perform operations. This will reduce the network
calls as we are serializing the whole object and sending to server and further request for
information from client is not needed by the server.

Only an object that implements the serializable interface can be saved and restored by the
serialization facilities.

The serializable interface defines no members.

Accord Info Matrix


Chennai
Java Faculty Guide 177

Variables that are declared as transient are not saved by the serialization facilities.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but
one method in particular stands out:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:

public final Object readObject() throws IOException, ClassNotFoundException

Marking the field transient prevents the state from being written to the stream and from being
restored during deserialization.

public class Employee implements java.io.Serializable

public String name;

public String address;

public int number;

public void mailCheck()

System.out.println("Mailing a check to " + name + " " + address);

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo


program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does
not generate any output, but study the code and try to determine what the program is doing.

Accord Info Matrix


Chennai
Java Faculty Guide 178

import java.io.*;

public class SerializeDemo

public static void main(String [] args)

Employee e = new Employee();

e.name = "Reyan Ali";

e.address = "Phokka Kuan, Ambehta Peer";

e.number = 101;

try

FileOutputStream fileOut = new FileOutputStream("employee.ser");

ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e);

out.close();

fileOut.close();

catch(IOException i)

{ i.printStackTrace(); }

}}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program. Study the program and try to determine its output:

import java.io.*;

public class DeserializeDemo

Accord Info Matrix


Chennai
Java Faculty Guide 179

public static void main(String [] args)

Employee e = null;

try

FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new


ObjectInputStream(fileIn);

e = (Employee) in.readObject();

in.close();

fileIn.close();

catch(IOException i)

{ i.printStackTrace();

return;

catch(ClassNotFoundException c)

System.out.println(.Employee class not found.); c.printStackTrace(); return;

System.out.println("Deserialized Employee...");

System.out.println("Name: " + e.name);

System.out.println("Address: " + e.address);

System.out.println("Number: " + e.number); } }

Accord Info Matrix


Chennai
Java Faculty Guide 180

Lab Assignment
1. How to get list of all files from a folder?

2. Filter the files by file extensions and show the file names.

3. How to read file content using byte array?

4. How to read file content line by line in java?

5. How to read input from console in java?

6. How to get file URI reference?

7. How to store and read objects from a file?

8. How to convert inputstream to reader or BufferedReader?

9. How to convert byte array to reader or BufferedReader?

10. How to set file permissions in java?

11. How to read a file using BufferedInputStream?

12. How to write string content to a file in java?

13. How to write byte content to a file in java?

FAQ
1. What is the necessity of two types of streams – byte streams and character streams?
2. What are the super most classes of all streams?
3. Which you feel better to use – byte streams or character streams?
4. What System.out.println()?
5. What is PrintStream and PrintWriter?
6. Which streams are advised to use to have maximum performance in file copying?
7. What is File class?
8. What is RandomAccessFile?

Accord Info Matrix


Chennai
Java Faculty Guide 181

Topic 11: Database Queries.

Topics to Cover

 Explain - database, table, records and data.


 Importance of database.
 Types of database.
 Explain the Concepts of RDBMS
 Types of SQL and its Syntax and Example.
 How to install and run MySQL DB and execute SQL Queries.

What is Database

A database is an organized collection of data. It is the collection of schemas , tables, queries,


reports, views, and other objects. The data are typically organized to model aspects of reality in
a way that supports processes requiring information.

Importance of Database

 Reduced data redundancy.


 Reduced updating errors and increased consistency.
 Greater data integrity and independence from applications programs.
 Improved data access to users through use of host and query languages.
 Improved data security.
 Reduced data entry, storage, and retrieval costs.
 Facilitated development of new applications program.

What is table.

A table is a set of data elements (values) using a model of vertical columns (identifiable by
name) and horizontal rows, the cell being the unit where a row and column intersect.
A table has a specified number of columns, but can have any number of rows.

Accord Info Matrix


Chennai
Java Faculty Guide 182

What is RDBMS – Relational Database Management System

A database management system (DBMS) is system software for creating and


managing databases. The DBMS provides users and programmers with a systematic way to
create, retrieve, update and manage data.

A DBMS makes it possible for end users to create, read, update and delete data in a database.
The DBMS essentially serves as an interface between the database and end users or application
programs, ensuring that data is consistently organized and remains easily accessible.

With relational DBMSs (RDBMSs), this API is SQL, a standard programming language for
defining, protecting and accessing data in a RDBMS.

What is SQL

SQL (Structured Query Language) is a standardized programming language used for managing
relational databases and performing various operations on the data in them. The uses of SQL
include modifying database table and index structures; adding, updating and deleting rows of
data; and retrieving subsets of information from within a database for transaction processing
and analytics applications. Queries and other SQL operations take the form of commands
written as statements.

Types of SQL

 DDL - Data Definition Language.


 DML - Data Manipulation Language.
 DCL - Data Control Language.
 TCL - Transaction Control Language.
 DQL - Data Query Language.

Accord Info Matrix


Chennai
Java Faculty Guide 183

Data Definition Language

Statements are used to define the database structure or schema.

 Create
 Alter
 Drop

Data Manipulation Language

 Insert
 Update
 Delete

Data Control Language

 Grant
 Revoke

Data Query Language

 Select
 Show
 Describe
DDL – Data Definition Language
Database Creation
Create database <dbname>;
Example:
Create database studentmanagement;
Table Creation
Create table <tblname>(<col.name> <datatype>,.,.,.,.);
Example
Create table marks(
sno int,
name varchar(50),
mark1 int,
mark2 int,
mark3 int,
total int,
average float);

Accord Info Matrix


Chennai
Java Faculty Guide 184

And give explanation for types of data type.


Int tinyint bigint
char varchar text
date time
blob longblob shortblob.
(Important to explain, difference between char and varchar)
Change Column name and data type

Syntax

alter table <tblname> change column <old column name> <new column name>
<datatype>;

Eg:

alter table marks change column average avg float;

Add new Column

Syntax

alter table <tblname> add column <column name> <datatype>;

eg:

alter table marks add column result varchar(50);

Remove Existing Column

Syntax

alter table <tblname> drop column <column name>;

eg:

alter table marks drop column result;

Rename Table

Syntax

alter table <tablename> rename <new table name>;

eg:

alter table marks rename studentsMarks;

Accord Info Matrix


Chennai
Java Faculty Guide 185

DML – Data Manipulation Language


Insert records
Syntax
Insert into <tablename>(<col.name>,.,.,.) values(values.,.,.,);
Example
Insert into marks(name,mark1,mark2,mark3) values (“test”,100,100,100);

Update Existing Records


Syntax
Update <tablename> set <column name>=<value> <condition>;
Example
1. Update marks set total=mark1+mark2+mark3,average=total/3;
a. Update all column values in a table
2. Update marks set mark1=100 where name=”test”;
a. Update particular records.

Delete Records
Syntax
Delete from <tablename> <condition>;
Example
Delete from marks; - delete all records in a table
Delete from marks where name=”test”; - delete records with condition.

DQL – Data Query Language


Show table records.
Syntax
Select <column name>,.,. from <tablename>;
Show all records in a table.
Select <column name> ,.,.,. from <tablename> <condition>;
Conditions are used to filter records to display.
Conditions are:
Where
Having
Order by
Group by
Limit

Accord Info Matrix


Chennai
Java Faculty Guide 186

Example
Select * from marks;
Show all records in a table.
Select name, total, average from marks;
Show specified column records.
Select * from marks where mark1 > 95;
Show all records with mark1 column values above 95.
Select * from marks where mark1 > 95 and mark2 > 95 and mark3 > 95;
Show records with multiple conditions.
Select * from marks order by total asc;
Show records and arrange ascending order with duplicate entries.
Select * from marks group by total asc;
Show records and arrange ascending order without duplicate entries.
Select * from marks limit 0,5;
In limit first value – starting index (0)
second value – end index (5)
show specified records with specified starting index
Select * from marks where name like “%er%”;
Show records name value contain characters of ‘er’
select * from marks where name like “a%”;
Show records name value starts with ‘a’
select * from marks where name like “%r”;
Show records name value ends with ‘r’

Important Notes given to student:


Define database, table, and records.
SQL Queries types , syntax and its example
Why database is backend for application development
How to Install & run MySQL database.

Accord Info Matrix


Chennai
Java Faculty Guide 187

FAQ:
1. Define database model.
2. Difference between DBMS and RDBMS.
3. What is normalization?
4. Difference between char, varchar and text datatype.
5. Use of BLOB Datatype.
6. Types of SQL and its syntax.
7. Difference between truncate.

Lab Task

Create Database for Student details


create table for storing marks with below fields,

Sno Int
Name Varchar(50)
Roll No Int
Tamil Int
English Int
Maths Int
Total Int
Average Float
Insert some records in a table , and perform below operation

 Get Mark details for particular students.


 Show list of records , mark value having > 94
 Update mark for Particular student ( eg: Ram Tamil – 50 change Tamil – 80 ).
 Show first highest average students.
 List of Records , student take > 95 in all subject
 List of records , Tamil marks between 90 to 95.
 Update total , avg once student record is inserted.
 List of records , name column value starts with ‘R’
 Find records , name column contains characters of ‘na’
 To add new column – Result – varchar(10);
 To change table name marks to examresult;

Accord Info Matrix


Chennai
Java Faculty Guide 188

Topic: 12 – Database Advanced

Topics to Cover

1. Primary key
2. Foreign key.
3. Sub Queries
4. Aggregate functions.
5. Joins and types of joins.

What is Primary key

A primary key is a field in a table which uniquely identifies each row/record in a database
table. Primary keys must contain unique values. A primary key column cannot have NULL
values. A table can have only one primary key, which may consist of single or multiple fields.

Syntax:
Create table <tablename>(<column.name> <datatype> primary key,.,.,);

Example
Create table employee(
eid varchar(50) primary key,
name varchar(50),
gender varchar(10),
destination varchar(50));

What is foreign key

A foreign key is a column (or columns) that reference a column (most often the primary key) of
another table. The purpose of the foreign key is to ensure referential integrity of the data. In
other words, only values that are supposed to appear in the database are permitted.

A FOREIGN KEY is a key used to link two tables together.

A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in
another table. The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.

Accord Info Matrix


Chennai
Java Faculty Guide 189

Syntax:
Create table <tablename>(<column.name> <datatype>,foreign key
<column.name> references tablename(columnname);

Example
Create table empsalary(
eid varchar(50),
salary int,
date date,
foreign key (eid) references employee(eid));

Sub Queries

A subquery is a SQL query nested inside a larger query.


 A subquery may occur in :
- A SELECT clause
- A FROM clause
- A WHERE clause
 In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE, SET, or DO
statement or inside another subquery.
 A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
 You can use the comparison operators, such as >, <, or =. The comparison operator can
also be a multiple-row operator, such as IN, ANY, SOME, or ALL.
 A subquery can be treated as an inner query, which is a SQL query placed as a part of
another query called as outer query.
 The inner query executes first before its parent query so that the results of the inner
query can be passed to the outer query.

Accord Info Matrix


Chennai
Java Faculty Guide 190

Syntax
Select
<column.name>,.,.
From
<tablename>
Where
Condition=(
Select <column.name> from <tablename> condition;
)
Example

Select * from empsalary where salary=(select eid from employee where name=”ram”);

Aggregate Function

The data that you need is not always stored in the tables. However, you can get it by
performing the calculations of the stored data when you select it. To perform calculations in a
query, you use aggregate functions.

An aggregate function performs a calculation on a set of values and returns a single value.

Types of Aggregate Functions


1. count()
2. sum()
3. avg()
4. min()
5. max()

count()

Count() function returns the number of rows in a select query result.

eg:

select count(*) from tablename; // count of table records

select count(*) from tablename conditions; // count of records , get from select query
with condition;

Accord Info Matrix


Chennai
Java Faculty Guide 191

sum()

The SUM function returns the sum of a set of values. The SUM function ignores NULLvalues. If
no matching row found, the SUM function returns a NULL value.

syntax

select sum(column) from tablename;

select sum(column) from tablename condition;

eg:

In a salary table find total amount to given as salary

select sum(salary) from empsalary; // get total sum amount of salary column.

select sum(salary) from empsalary where month=”March”;

// get total sum amount of salary for the month of March.

avg()

The avg() function calculates the average value of a set of values. It ignores NULL values in the
calculation.

Syntax

select avg(column) from tablename;

eg:

to get average salary for specified year of particular employee.

select avg(salary) from employee where year=”2017” and empid=”AIM098”;

Accord Info Matrix


Chennai
Java Faculty Guide 192

min()

The min() function returns the minimum value in a set of values.

Syntax

select min(column) from tablename;

eg:

select min(salary) from empsalary; // get minimum value in a salary column

select min(salary) from empsalary where month=”march”;

// get minimum salary amount for the month of march.

max()

The max() function returns the maximum value in a set of values.

Syntax

select max(column) from tablename;

eg:

select max(salary) from empsalary; // get maximum value in a salary column

select max(salary) from empsalary where month=”march”;

// get maximum salary amount for the month of march.

Accord Info Matrix


Chennai
Java Faculty Guide 193

Joins

MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed
whenever two or more tables are joined in a SQL statement.

There are different types of MySQL joins:

INNER JOIN

Chances are, you've already written a statement that uses a MySQL INNER JOIN. It is the most
common type of join. MySQL INNER JOINS return all rows from multiple tables where the join
condition is met.

Syntax

SELECT columns

FROM table1

INNER JOIN table2

ON table1.column = table2.column;

Visual Illustration

In this visual diagram, the MySQL INNER JOIN returns the shaded area:

Accord Info Matrix


Chennai
Java Faculty Guide 194

Example

We have a table called suppliers with two fields (supplier_id and supplier_name). It contains
the following data:

supplier_id supplier_name

10000 IBM

10001 Hewlett Packard

10002 Microsoft

10003 NVIDIA

We have another table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:

order_id supplier_id order_date

500125 10000 2017/05/12

500126 10001 2017/05/13

500127 10004 2017/05/14

Accord Info Matrix


Chennai
Java Faculty Guide 195

If we run the MySQL SELECT statement (that contains an INNER JOIN) below:

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date

FROM suppliers

INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id;

Our result set would look like this:

supplier_id name order_date

10000 IBM 2017/05/12

10001 Hewlett Packard 2017/05/13

LEFT JOIN

Another type of join is called a MySQL LEFT JOIN. This type of join returns all rows from the
LEFT-hand table specified in the ON condition and only those rows from the other table where
the joined fields are equal (join condition is met).

Syntax

The syntax for the LEFT JOIN in MySQL is:

SELECT columns

FROM table1

LEFT JOIN table2

ON table1.column = table2.column;

Accord Info Matrix


Chennai
Java Faculty Guide 196

Visual Illustration

In this visual diagram, the MySQL LEFT JOIN returns the shaded area:

The MySQL LEFT JOIN would return the all records from table1 and only those records
from table2 that intersect with table1.

Example

We have a table called suppliers with two fields (supplier_id and supplier_name). It contains
the following data:

supplier_id supplier_name

10000 IBM

10001 Hewlett Packard

10002 Microsoft

10003 NVIDIA

We have a second table called orders with three fields (order_id, supplier_id, and order_date).
It contains the following data:

order_id supplier_id order_date

500125 10000 2017/05/12

500126 10001 2017/05/13

If we run the SELECT statement (that contains a LEFT JOIN) below:

Accord Info Matrix


Chennai
Java Faculty Guide 197

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date

FROM suppliers

LEFT JOIN orders

ON suppliers.supplier_id = orders.supplier_id;

Our result set would look like this:

supplier_id supplier_name order_date

10000 IBM 2017/05/12

10001 Hewlett Packard 2017/05/13

10002 Microsoft <null>

10003 NVIDIA <null>

The rows for Microsoft and NVIDIA would be included because a LEFT JOIN was used. However,
you will notice that the order_date field for those records contains a <null> value.

RIGHT JOIN

Another type of join is called a MySQL RIGHT JOIN. This type of join returns all rows from the
RIGHT-hand table specified in the ON condition and only those rows from the other table
where the joined fields are equal (join condition is met).

Syntax

The syntax for the RIGHT JOIN in MySQL is:

SELECT columns

FROM table1

RIGHT JOIN table2

ON table1.column = table2.column;

Accord Info Matrix


Chennai
Java Faculty Guide 198

Visual Illustration

In this visual diagram, the MySQL RIGHT JOIN returns the shaded area:

The MySQL RIGHT JOIN would return the all records from table2 and only those records
from table1 that intersect with table2.

Example

We have a table called suppliers with two fields (supplier_id and supplier_name). It contains
the following data:

supplier_id supplier_name

10000 Apple

10001 Google

We have a second table called orders with three fields (order_id, supplier_id, and order_date).
It contains the following data:

order_id supplier_id order_date

500125 10000 2017/08/12

500126 10001 2017/08/13

500127 10002 2017/08/14

Accord Info Matrix


Chennai
Java Faculty Guide 199

If we run the SELECT statement (that contains a RIGHT JOIN) below:

SELECT orders.order_id, orders.order_date, suppliers.supplier_name

FROM suppliers

RIGHT JOIN orders

ON suppliers.supplier_id = orders.supplier_id;

Our result set would look like this:

order_id order_date supplier_name

500125 2017/08/12 Apple

500126 2017/08/13 Google

500127 2017/08/14 <null>

The row for 500127 (order_id) would be included because a RIGHT JOIN was used. However,
you will notice that the supplier_name field for that record contains a <null> value.

FAQ

 Type of aggregate function


 Difference between primary key , unique and index
 Types of joins
 How to use foreign key constrains
 Explain sub query creation and its syntax
 List of constrain in MySQL.
 Difference between where and having condition

Accord Info Matrix


Chennai
Java Faculty Guide 200

Lab Task

To Create tables:

Branch
BranchId Varchar(15) – primary key
BranchName Varchar(100)
Country Varchar(50)
Address Text
State Varchar(50)
City Varchar(50)
Contactno Varchar(13)
Pincode Int

Employee
BranchId Varchar(15) – Foreign key Reference of
Branch Table Branch id
EmployeeId Varchar(15) – Primary key
EmployeeName Varchar(50)
Mobile Bigint
Mailid Text
Address Text
Date of Join Date
Destination Varchar(100)
Salary double

Customer
Customerid Varchar(15) – primary key
Empolyeeid Varchar(15) – foreign key reference of
Employee table empolyeeid
Customername Varchar(100)
Address Text
State Varchar(50)
City Varchar(50)
Contactno Varchar(13)
Pincode Int

Accord Info Matrix


Chennai
Java Faculty Guide 201

To create above all tables and insert records. Write queries for below task.

Task List

 Find list of employee in a particular branch


 Print count of branches in a country
 Get branch count for specified state
 Count of customer for each employees
 Display employee , order by department
 List records for particular branch all customers.
 List employee, after join specified years.
 List of employee who getting minimum salary each branch
 List of employee who getting maximum salary each branch
 Display customer records for particular state
 Count customer for each branch.
 Find total Customer for each country.
 Find customer name starts with ‘ar’.
 Get branch code using customer name.
 Show employee name using customer id.
 Find count of customer for each employee.

Accord Info Matrix


Chennai
Java Faculty Guide 202

Topic 13 : JDBC Connectivity.

Topic to Cover

 Define JDBC API.


 Types of Driver.
 How to Connect MySQL DB .
 Statement and PreparedStatement Interface.
 Using ResultSet , how to processing select query.
 How to set class path external driver JAR file.

JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

 Making a connection to a database.


 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an database.

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −

JDBC API: This provides the application-to-JDBC Manager connection.

JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

Accord Info Matrix


Chennai
Java Faculty Guide 203

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

Common JDBC Components

The JDBC API provides the following interfaces and classes −

DriverManager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication sub protocol.
The first driver that recognizes a certain subprotocol under JDBC will be used to establish a
database Connection.

Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.

Accord Info Matrix


Chennai
Java Faculty Guide 204

Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.

Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.

ResultSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.

SQLException: This class handles any errors that occur in a database application.

JDBC Driver

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact with
it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.

JDBC Driver Types

JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when no
other alternative is available.

Accord Info Matrix


Chennai
Java Faculty Guide 205

Type 2: JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to
the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.

If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

Accord Info Matrix


Chennai
Java Faculty Guide 206

Type 3: Network Protocol driver

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

Type 4: All Java Driver

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server.

Accord Info Matrix


Chennai
Java Faculty Guide 207

To Connect DataBase using JDBC API

Step 1:

Register JDBC Driver


You must register the driver in your program before you use it. Registering the driver is
the process by which the MySQL 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.

The most common approach to register a driver is to use Java'sClass.forName() method,


to dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver registration configurable and
portable.

The following example uses Class.forName( ) to register the MySQL driver

try{

Class.forName(“Driver Class Name”);

}catch(ClassNotFoundException ex){

System.out.println(“Error: unable to load driver class”);

Database URL Connection

After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −

 getConnection(String url)
 getConnection(String url, Properties prop)
 getConnection(String url, String user, String password)

Accord Info Matrix


Chennai
Java Faculty Guide 208

Here each form requires a database URL. A database URL is an address that points to
your database. Formulating a database URL is where most of the problems associated with
establishing a connection occurs.

Following table lists down the popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/


databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port


Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName

Example

try{

Class.forName(“Driver Class Name”);

Connection con=DriverManager.getConnection(“Connection url based DB”);

}catch(Exception ex){

System.out.println(e);

Create Statement
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database.

Accord Info Matrix


Chennai
Java Faculty Guide 209

They also define methods that help bridge data type differences between Java and SQL
data types used in a database.

The following table provides a summary of each interface's purpose to decide on the
interface to use.

Interfaces:

Statement

Use the for general-purpose access to your database. Useful when you are using static SQL
statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement

Use the when you plan to use the SQL statements many times. The PreparedStatement
interface accepts input parameters at runtime.

Example

try{
Class.forName(“Driver Class Name”);

Connection conn=DriverManager.getConnection(“Connection url based DB”);

Statement statement=conn.createStatement();
}catch(Exception ex){
System.out.println(e);
}
try{

Class.forName(“Driver Class Name”);

Connection conn=DriverManager.getConnection(“Connection url based DB”);

PreparedStatement statement=conn.prepareStatement(“query”);

}catch(Exception ex){

System.out.println(e);

Accord Info Matrix


Chennai
Java Faculty Guide 210

Execute Queries
The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result
set. The java.sql.ResultSet interface represents the result set of a database query.

A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.

Creating a ResultSet
You create a ResultSet by executing a Statement or PreparedStatement, like this:

try{

Class.forName(“Driver Class Name”);

Connection conn=DriverManager.getConnection(“Connection url based DB”);

PreparedStatement statement=conn.prepareStatement(“query”);

ResultSet result=statement.executeQuery();

}catch(Exception ex){

System.out.println(e);

Or

try{

Class.forName(“Driver Class Name”);

Connection connection=DriverManager.getConnection(“Connection url based


DB”);

Statement statement=connection.createStatement();

ResultSet result=statement.executeQuery(“select query”

}catch(Exception ex){

System.out.println(e);

Accord Info Matrix


Chennai
Java Faculty Guide 211

Iterating the ResultSet

To iterate the ResultSet you use its next() method. The next() method returns true if
theResultSet has a next record, and moves the ResultSet to point to the next record. If there
were no more records, next() returns false, and you can no longer. Once thenext() method has
returned false, you should not call it anymore. Doing so may result in an exception.

Here is an example of iterating a ResultSet using the next() method:

while(result.next()) {

// ... get column values from this record

As you can see, the next() method is actually called before the first record is accessed.
That means, that the ResultSet starts out pointing before the first record. Once next() has been
called once, it points at the first record.

Similarly, when next() is called and returns false, the ResultSet is actually pointing after
the last record. You cannot obtain the number of rows in a ResultSet except if you iterate all the
way through it and count the rows.

However, if the ResultSet is forward-only, you cannot afterwards move backwards


through it. Even if you could move backwards, it would a slow way of counting the rows in
the ResultSet. You are better off structuring your code so that you do not need to know the
number of records ahead of time.

Accessing Column Values

When iterating the ResultSet you want to access the column values of each record. You
do so by calling one or more of the many getXXX() methods. You pass the name of the column
to get the value of, to the many getXXX() methods. For instance:

Accord Info Matrix


Chennai
Java Faculty Guide 212

while(result.next()) {

result.getString (“column name1”);

result.getInt (“column name2”);

result.getBigDecimal(“column name3”);

There are a lot of getXXX() methods you can call, which return the value of the column
as a certain data type, e.g. String, int, long, double, BigDecimal etc. They all take the name of
the column to obtain the column value for, as parameter.

The getXXX() methods also come in versions that take a column index instead of a
column name. For instance:

while(result.next()) {

result.getString (1);

result.getInt (2);

result.getBigDecimal(3);

// etc.

The index of a column typically depends on the index of the column in the SQL
statement. For instance, the select query SQL statement example

select name, age, city from person;

has three columns. The column name is listed first, and will thus have index 1 in
theResultSet. The column age will have index 2, and the column coefficient will have index 3.

Sometimes you do not know the index of a certain column ahead of time. For instance,
if you use a select * from type of SQL query, you do not know the sequence of the columns.

Accord Info Matrix


Chennai
Java Faculty Guide 213

If you do not know the index of a certain column you can find the index of that column
using the ResultSet.findColumn(String columnName) method, like this:

int nameIndex = result.findColumn("name");

int ageIndex = result.findColumn("age");

int city = result.findColumn("city");

while(result.next()) {

String name = result.getString (nameIndex);

int age=result.getInt(ageIndex);

String city= result.getString(city);

FAQ

 What are different types of JDBC Driver.


 Difference between Statement and PreparedStatement.
 How set Driver Configuration.
 What is API.
 How Iterate ResultSet.
 What are the steps to access database in java.

Accord Info Matrix


Chennai
Java Faculty Guide 214

Lab Task
To create Table Marks:

Sno Int
Name Varchar(50)
Roll No Int
Tamil Int
English Int
Maths Int
Total Int
Average Float

1. Get Input from user for Name, Rollno, Tamil, English, Maths Values.
2. Write queries to Insert values into marks table
3. Update Total and Average column values using update query
4. Write queries to show all students records
5. Write queries to show only particular students records.

Accord Info Matrix


Chennai
Java Faculty Guide 215

Topic 14: Networks

Topics to Cover

 Define Network
 Use of network
 Define protocol, port number and URL.
 Explain difference between TCP and UDP
 Use of network concept in java programming
 Getting System information from network.
 Explain Socket Programming.

What is network ?

A network is a collection of computers, servers, mainframes, network devices,


peripherals, or other devices connected to one another allowing for data to be shared and
used. A great example of a network is the Internet, connecting millions of people all over the
world together.

Java Network Programming

The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.

The java.net package provides support for the two common network protocols:

1. TCP: TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
2. UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.

Accord Info Matrix


Chennai
Java Faculty Guide 216

What is protocol?

Sometimes referred to as an access method, a protocol is a standard used to define a


method of exchanging data over a computer network such as local area
network, Internet, Intranet, etc. Each protocol has its own method of how data is formatted
when sent and what to do with it once received, how that data is compressed or how to check
for errors in data.

What is port number?

A port number is a way to identify a specific process to which an Internet or


other network message is to be forwarded when it arrives at a server. For the Transmission
Control Protocol and the User Datagram Protocol, a port number is a 16-bit integer that is put
in the header appended to a message unit.

Java TCP Networking Basics


Typically a client opens a TCP/IP connection to a server. The client then starts to
communicate with the server. When the client is finished it closes the connection again. Here is
an illustration of that:

A client may send more than one request through an open connection. In fact, a client
can send as much data as the server is ready to receive. The server can also close the
connection if it wants to.

Accord Info Matrix


Chennai
Java Faculty Guide 217

Java UDP Networking Basics


UDP works a bit differently from TCP. Using UDP there is no connection between the
client and server. A client may send data to the server, and the server may (or may not) receive
this data. The client will never know if the data was received at the other end. The same is true
for the data sent the other way from the server to the client.

Because there is no guarantee of data delivery, the UDP protocol has less protocol
overhead.

There are several situations in which the connectionless UDP model is preferable over
TCP. These are covered in more detail in the text on Java's UDP DatagramSocket's.

Java InetAddress class


Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example System name or IP address
or www.accordstudents.com, www.google.com, www.facebook.com etc.

Commonly used methods of InetAddress class

Method Description

public static InetAddress getByName(String host) it returns the instance of InetAddress


throws UnknownHostException containing LocalHost IP and name.

public static InetAddress getLocalHost() throws it returns the instance of InetAdddress


UnknownHostException containing local host name and address.

public String getHostName() it returns the host name of the IP address.

public String getHostAddress() it returns the IP address in string format.

Accord Info Matrix


Chennai
Java Faculty Guide 218

Example of Java InetAddress class

Let's see a simple example of InetAddress class to get ip address of www.accordsoft.in website.

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.accordstudents.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

Socket Programming

Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket
to a server.

When the connection is made, the server creates a socket object on its end of the
communication. The client and server can now communicate by writing to and reading from the
socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets:
 The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.

Accord Info Matrix


Chennai
Java Faculty Guide 219

 The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
 After the server is waiting, a client instantiates a Socket object, specifying the
server name and port number to connect to.
 The constructor of the Socket class attempts to connect the client to the
specified server and port number. If communication is established, the client
now has a Socket object capable of communicating with the server.
 On the server side, the accept() method returns a reference to a new socket on
the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a twoway communication protocol, so data can be sent across both streams at the same
time. There are following usefull classes providing complete set of methods to implement
sockets.

ServerSocket Class Methods:

The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests.

public ServerSocket(int port) throws IOException

Attempts to create a server socket bound to the specified port. An exception occurs if the port
is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException

Similar to the previous constructor, the backlog parameter specifies how many incoming clients
to store in a wait queue.

If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.

Here are some of the common methods of the ServerSocket class:

Accord Info Matrix


Chennai
Java Faculty Guide 220

public Socket accept() throws IOException

Waits for an incoming client. This method blocks until either a client connects to the server on
the specified port or the socket times out, assuming that the time-out value has been set using
the setSoTimeout() method. Otherwise, this method blocks indefinitely.

public void setSoTimeout(int timeout)

Sets the time-out value for how long the server socket waits for a client during the accept().

When the ServerSocket invokes accept(), the method does not return until a client connects.
After a client does connect, the ServerSocket creates a new Socket on an unspecified port and
returns a reference to this new Socket. A TCP connection now exists between the client and
server, and communication can begin.

Socket Class Methods:

The java.net.Socket class represents the socket that both the client and server use to
communicate with each other. The client obtains a Socket object by instantiating one, whereas
the server obtains a Socket object from the return value of the accept() method.

public Socket(String host, int port) throws UnknownHostException, IOException.

This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.

public Socket(InetAddress host, int port) throws IOException

This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.
When the Socket constructor returns, it does not simply instantiate a Socket object but it
actually attempts to connect to the specified server and port.

Some methods of interest in the Socket class are listed here. Notice that both the client and
server have a Socket object, so these methods can be invoked by both the client and server.

Accord Info Matrix


Chennai
Java Faculty Guide 221

public InputStream getInputStream() throws IOException

Returns the input stream of the socket. The input stream is connected to the output stream of
the remote socket.

public OutputStream getOutputStream() throws IOException

Returns the output stream of the socket. The output stream is connected to the input stream of
the remote socket.
Example Program

Server Program

import java.net.*;
import java.io.*;
public class ServerProgramming{
public static void main(String args[]){
try{
ServerSocket ss=new ServerSocket(1234);
Socket s=ss.accept();
ObjectInputStream ois=new ObjectInputStream(s.getInputStream());
ObjectOutputStream oos=new
ObjectOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
for(;;){
String msg=ois.readObject().toString();
if(msg.equalsIgnoreCase("end"))
break;
System.out.println("From Client - "+msg);
System.out.print("Me - ");
String message=br.readLine();
oos.writeObject(message);
}
}catch(Exception e){
e.printStackTrace();
}
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 222

Client Program

import java.net.*;
import java.io.*;
class ClientProgramming{
public static void main(String are[]){
try{
Socket s=new Socket("localhost",1234);
ObjectOutputStream oos=new
ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois=new ObjectInputStream(s.getInputStream());
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
for(;;){
System.out.print("Me - ");
String msg=br.readLine();
oos.writeObject(msg);
if(msg.equalsIgnoreCase("end"))
break;
System.out.println("From Server - "+ois.readObject());
}
}catch(Exception e){
e.printStackTrace();
}
}
}

FAQ

1. Type of Protocol
2. Difference between TCP and UDP.
3. What is port number.
4. Range of port number
5. List of classes Access TCP protocol processing.
6. How to check particular system is enable on the network.

Accord Info Matrix


Chennai
Java Faculty Guide 223

Topic J15 – Multithreading

Topic to cover

1. What is Thread.
2. Define multithreading
3. Explain Thread life cycle.
4. Thread priorities.
5. Use of Thread – class and Runnable – Interface .
6. Given Example for wait and sleep.

Thread
A thread, in the context of Java, is the path followed when executing a program. All Java
programs have at least one thread, known as the main thread, which is created by the JVM at
the program’s start, when the main() method is invoked with the main thread. In Java, creating
a thread is accomplished by implementing an interface and extending a class. Every Java thread
is created and controlled by the java.lang.Thread class.

Multithreading

Multithreading in java is a process of executing multiple threads simultaneously. Multithreading


has several advantages over Multiprocessing such as;

1. Threads are lightweight compared to processes


2. Threads share the same address space and therefore can share both data and code
3. Context switching between threads is usually less expensive than between processes
4. Cost of thread intercommunication is relatively low that that of process
intercommunication
5. Threads allow different tasks to be performed concurrently.

Thread Life Cycle


1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

Accord Info Matrix


Chennai
Java Faculty Guide 224

1. New The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2. Runnable The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3. Running The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently
not eligible to run.
5. Terminated A thread is in terminated or dead state when its run() method exits.

Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a
constant of 5).

Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and are very much platform dependent.

Accord Info Matrix


Chennai
Java Faculty Guide 225

Simple Thread Program

Example program to Create Thread by extending Thread class:

classMyThread extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
MyThread t1=new MyThread(); t1.start();
}
}

Output : Thread is running…

Example program to Create by implementing from Runnable Interface


class MyThread2 implements Runnable{
public void run(){
for(int i=1;i<=5;i++) {
System.out.println("Mythread is running "+i+" time");
}
}
public static void main(String args[]){
MyThread2 m1=new MyThread2();
Thread t1=new Thread(m1);
t1.start();
}
}

Output
Mythread is running 1 time
Mythread is running 2 time
Mythread is running 3 time
Mythread is running 4 time
Mythread is running 5 time

Accord Info Matrix


Chennai
Java Faculty Guide 226

Example program to achieve MultiThreading

class MyThread3 extends Thread{


public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println(e);
} System.out.println(i);
}
}
public static void main(String args[]){
MyThread3 t1=new MyThread3();
MyThread3 t2=new MyThread3();
t1.start();
t2.start();
}
}
Output
1
1
2
2
3
3
4
4
5
5

Accord Info Matrix


Chennai
Java Faculty Guide 227

Thread Synchronization in Java

Synchronization in java is the capability of control the access of multiple threads to any shared
resource. Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization

The synchronization is mainly used to


1. To prevent thread interference.
2. To Prevent consistency problem.

Before using synchronization

class Process extends Thread{


int a=10;
public void run(){
try{
a+=5;
for(int i=a;i<a+5;i++){
System.out.println(i);
sleep(200);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class TestSynchronization{
public static void main(String are[]){
Process p=new Process();
Thread first=new Thread(p);
Thread second=new Thread(p);
first.start();
second.start();
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 228

Output

After using synchronization


class Process extends Thread{
int a=10;
public synchronized void run(){
try{
a+=5;
for(int i=a;i<a+5;i++){
System.out.println(i);
sleep(200);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class TestSynchronization{
public static void main(String are[]){
Process p=new Process();
Thread first=new Thread(p);
Thread second=new Thread(p);
first.start();
second.start();
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 229

Output

Important Notes to Given

1. Define Thread
2. Define Multithreading
3. Thread Priorities
4. Thread Life cycle Explanations.
5. Define synchronization.
6. Thread Priorities.

FAQ
1. What is difference between Process and Thread in java?
2. How do you implement Thread in Java?
3. When to use Runnable vs Thread in Java?
4. What default Thread priority?
5. What is the difference between start() and run() method of Thread class?
6. What is the use of Synchronization in Thread?

Accord Info Matrix


Chennai
Java Faculty Guide 230

Day 16: Collection Framework

Topics To Cover

 Recall array concept, discuss about the limitation of array java. Discuss with a real time
example like an online shopping application were the products list is always dynamic in
nature.
 What is collection – definition, advantage over the arrays, what is collection framework,
 Collection framework components – Collection Interfaces and Implementations
 Advantages of collection framework.
 Collection framework hierarchy.
 List , Set , Map, Iterator
 ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable
 Differerce between List and Set, HashSet and TreeSet, Vector and ArrayList, TreeMap
and HashMap, Hashtable and HashMap

Introduction

In java to handle multiple values we use arrays. It is an efficient way to handle multiple values
in a group. Java provides option for handling array of any type. That is array of all primitive
types: byte, int, short, long, float, double, boolean and char. We can also create array of
objects on any types that is, non-primitives.

For example, we can create an array of ‘String’ class that can hold multiple strings. That is,
when we need to represent group of student names or all the state names of country we can
effectively use array.

For creating an array of string

String [] students = new String[10];

The above statement will create an array of string that can hold ten names.

Accord Info Matrix


Chennai
Java Faculty Guide 231

Even we can create array of objects for user defined classes. For example you have to maintain
group of employees and each employee has to be represented using an Employee class.

class Employee{
int id;
String ename
String department;
Employee(int id,String ename,String department,String mobile){
this.id=id;
this.ename=ename;
this.department=department;
}
void printDetails(){
System.out.println(“ID: “+id);
System.out.println(“Name : “+ename);
System.out.println(“Department: “+department);

}
}
For the above class you can create an array to store details of multiple employees.

Example:
Employee[] employees = new Employee[3];
The above code will create an array of five Employee references. Now , each employee
reference can be initialized as:

employees[0] = new Employee(1,”Anand”,”Sales”);


employees[0] = new Employee(2,”Arun”,”Production”);
employees[0] = new Employee(3,”Ajay”,”Marketing”);

The above array can be iterated as:

for(Employee emp:employees){
emp. printDetails();
}

So we understand that, the array can be used to handle collection of any type of data. But, the
limitation is that the array is static in nature. It does not provide any dynamic actions like
adding an additional element or removing elements. Also, array is just a collection of data, it
does not provided any inbuilt mechanism for handling the elements.

Accord Info Matrix


Chennai
Java Faculty Guide 232

Now, java provides an option called as ‘Collection’ for handling collection of objects
dynamically.

Definition :

A Collection is an object that groups multiple objects into a single unit. Collections are used to
store, retrieve, manipulate, and transfer aggregate data. A collection provides option for
handling multiple objects in a dynamic manner. It provides dynamic action like inserting
elements in between, removing objects, adding, searching an object, iterating. Collection
provides an efficient and organized mechanism for handling group of objects.

A real time example

Consider a ticket booking application where the user provides the ‘source station’, ‘destination
station’ and ‘journey’ as input parameters. Not, the application will fetch the data from a
database table and transfers it to a page where it is displayed. Here, the size of the list
retrieved varies as the input values changes. That the size of the list will vary for different input
given by the user. It means that the code cannot declare a fixed size for the list as we are
declaring in an array. This is where the collection is more suitable. The collection not only
provides dynamic size but, also provides inbuilt mechanism for iterating, searching, removing,
replacing the elements. More clearly saying, collection provides inbuilt methods for all the
dynamic actions.

Collection framework:

A collections framework is a unified architecture for representing and manipulating various


types of collections. The ‘collection framework’ provides various classes and interfaces for
handling collection in java. Collection framework in java is organized under the ‘java.util’
package. That is, this package has to be imported when we want to use collection framework.
The Collection framework is divided into main components -- Collection Interfaces and
Collection Implementations

Accord Info Matrix


Chennai
Java Faculty Guide 233

Collection Interfaces: They are abstract data types that are used to represent collection.
Interfaces allow collections to manipulate independently of their details of implementations.
Collection Implementations: They are concrete implementations for the collection interfaces.
Basically, a collection implementation is a reusable data structure.

Advantages of using collection framework

 Reduces the coding effort: It provides useful data structure and algorithm which helps
the developer to bye-pass the low level coding for organize the data.
 Provides High-performance, High-quality data structures.

The collection framework hierarchy

The collection framework consists of an Hierarchy of classes and interfaces to handle


collections. The entire collection API is found in the java.util package
The hierarchy is topped by a an interface called as ‘Collection’

Collection

List Set Queue

ArrayList HashSet LinkedHashSet SortedSet PriorityQueue

Vector TreeSet Deque

Accord Info Matrix


Chennai
Java Faculty Guide 234

List: The List interface represent collection with duplication. The List type of collection stores
the object in insertion order. It provides positional access, that is based on the numerical
positional in the list. It provides methods for adding , removing, iteration of objects.

Set : The Set interface represents collection without duplication. The set interface methods
that are inherited form the Collection interface. Set does not provide the positional access to
the elements.

Implementations of List

ArrayList
It is a resizable array implementation of the List interface. As elements are added to the
ArrayList the capacity grows.

LinkedList
Doubley-linked list implementation of the List interface and Deque interface.

Vector
The vector is a dynamic array implementation of List interface. The size of a Vector can grow or
shrink as needed to accommodate adding and removing items after the Vector has been
created. The difference between Vector and the other implementation is that Vector is
Synchronous.

A Simple Collection using Vector

import java.util.*;
public class VectorDemo {

public static void main(String args[]) {


// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());

Accord Info Matrix


Chennai
Java Faculty Guide 235

v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());

v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());

v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());

v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());

v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());

if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");

// enumerate the elements in the vector.


Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");

while(vEnum.hasMoreElements()){
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
//Using for-each
for(Object obj:v){
String st = (String)obj
System.out.pritnln(st);
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 236

Implementations of Set

HashSet
This class implements the Set interface. Java HashSet class is used to create a collection that
uses a hash table for storage. HashSet stores the elements by using a mechanism called
hashing

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Contains unique
elements only like HashSet. Maintains natural order of elements.

LinkedHashSet
LinkedHashSet class is a Hash table and Linked list implementation of the set interface.
Contains unique elements only like HashSet. provides all optional set operations, and permits
null elements. Maintains insertion order.

An Example of LinkedHasSet using Book Object

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}

public class LinkedHashSetExample {


public static void main(String[] args) {
LinkedHashSet hs=new LinkedHashSet ();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Accord Info Matrix


Chennai
Java Faculty Guide 237

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);


Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
//Traversing hash table
for(Object obj:hs){
Book b =(Book) obj
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

}
}
}

Implementation of Map

HashMap
HashMap contains values mapped to a key. It implements the Map interface. Each key and
element in the HashMap is an entry(key and value). The Keys of the HashMap cannot be
duplicated. It does not maintain insertion order or natural order. Like in HashSet, HashMap
also uses hashing mechanism. HashMap uses hshing mechanism with the key object. Each
entry in the HashMap is represented by the Map.Entry interface.

Example
import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Rajesh");
hm.put(101,"Ramesh");
hm.put(102,"Rajeev");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 238

Tree Map
Java TreeMap class implements the Map interface by using a tree. It provides an efficient
means of storing key/value pairs in sorted order. A TreeMap contains values based on the key.
It implements the NavigableMap interface and extends AbstractMap class. It cannot have null
key but can have multiple null values.

Example

import java.util.*;
public class TreeMapDemo {

public static void main(String args[]) {


// Create a hash map
TreeMap tm = new TreeMap();

// Put elements to the map


tm.put("Ram", new Double(456.43));
tm.put("Shyam", new Double(678.55));
tm.put("Mohan", new Double(99.22));

// Get a set of the entries


Set set = tm.entrySet();

// Get an iterator
Iterator i = set.iterator();

// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();

// Deposit 1000 into Zara's account


double balance = ((Double)tm.get("Mohan")).doubleValue();
tm.put("Mohan", new Double(balance + 1000));
System.out.println("Mohan new balance: " + tm.get("Mohan"));
}
}

Accord Info Matrix


Chennai
Java Faculty Guide 239

Hashtable
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface. It is synchronous map. It cannont have null keys and
null values.
FAQ
1. What is Collection Framework
2. What is advantage of Collection framework over array in java
3. What is the topmost if the collection framework hierarchy
4. What is Iterator interface
5. What is Enumeration interface
6. What is the difference between the Set and List.
7. The Collection API is provided by ___________ package in java
8. What is difference between Vector and the TreeSet
9. Which is faster , Vector or ArrayList ? What is the reason.
10. What is LinkedHashSet ?

Lab Assignments
1. Create a class to represent an Employee , with eid, ename, department fields and
methods for storing and reading values from the fields. Now create an array that can
store 5 employee objects. Search for an employee a specific id and display his/her
details

2. Create a Vector that can store Book object with fields book_id, title ,author and price.
The program should be able to add new book / display a book details using id based in a
choice from the user.

Accord Info Matrix


Chennai
Java Faculty Guide 240

Day 17: Generic Collection

Topics to Cover

 What is Generic Collection


 What is advantage of using Generic
 Using Comparable Interface
 What difference between Comparable and Comparator Interface

Generic Collection

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. Before
generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces
the java programmer to store specific type of objects that will be added into the collection.
Generic Collection is a type safe collection. We say generic is type safe because it doesnot
allow objects other than the declared type.

Advantage of using Generic

Type-Safety: Accepts only a single type of objects in to the collection. That is, a generic
collection can specify the object type to be added into the collection.

Type casting is not required: When objects are reterived from a collection we don’t have to
convert the object type as we have done on non generic collection.

Before Generics, we need to type cast.

List list = new ArrayList();

list.add("hello");

String s = (String) list.get(0);//typecasting

Syntax for creating a generic collection

ColectionClassOrIntefaceName<Type> obj = new ColectionClassName <Type>()

Example

ArrayList<String> list = new ArrayList<String>();

List<String> list = new ArrayList<String>();

Accord Info Matrix


Chennai
Java Faculty Guide 241

Example for creating a Generic Collection

import java.util.*;

class TestGenerics1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();

list.add("rahul");

list.add("jai");

//list.add(32);//compile time error

String s=list.get(1);//type casting is not required

System.out.println("element is: "+s);

Iterator<String> itr=list.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Generic Collection Example using Map

import java.util.*;

class TestGenerics2{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(1,"vijay");

map.put(4,"umesh");

map.put(2,"ankit");

//Now use Map.Entry for Set and Iterator

Set<Map.Entry<Integer,String>> set=map.entrySet();

Accord Info Matrix


Chennai
Java Faculty Guide 242

Iterator<Map.Entry<Integer,String>> itr=set.iterator();

while(itr.hasNext()){

Map.Entry e=itr.next();//no need to typecast

System.out.println(e.getKey()+" "+e.getValue());

Comparable Interface

This one of the commomly used interface whe working with collection framework. Java
Comparable interface is used to order the objects of user-defined class.This interface is found
in java.lang package and contains only one method named compareTo(Object). It provide
single sorting sequence only i.e. you can sort the elements on based on single data member
only. For example it may be rollno, name, age or anything else.

Method in the Comparable Interface

public int compareTo(Object obj): is used to compare the current object with the specified
object.

Collections class

Collections class provides static methods for sorting the elements of collections. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But We cannot sort the elements
of List. Collections class provides methods for sorting the elements of List type elements.

Method of the Collections class to Sort a List

public void sort(List list): is used to sort the elements of List. List elements must be of
Comparable type.

Accord Info Matrix


Chennai
Java Faculty Guide 243

Comparable Example

Student class implementing the Comparable Interface

class Student implements Comparable<Student>{

int rollno;

String name;

int age;

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

public int compareTo(Student st){

if(age==st.age)

return 0;

else if(age>st.age)

return 1;

else

return -1;

TestSort.java

import java.util.*;

import java.io.*;

public class TestSort3{

public static void main(String args[]){

ArrayList<Student> al=new ArrayList<Student>();

Accord Info Matrix


Chennai
Java Faculty Guide 244

al.add(new Student(101,"Vijay",23));

al.add(new Student(106,"Ajay",27));

al.add(new Student(105,"Jai",21));

Collections.sort(al);

for(Student st:al){

System.out.println(st.rollno+" "+st.name+" "+st.age);

Comparator Interface

Java Comparator interface is used to order the objects of user-defined class. This interface is
found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and
equals(Object element). It provides multiple sorting sequence i.e. you can sort the elements on
the basis of any data member, for example rollno, name, age or anything else.

Method in Comparator

public int compare(Object obj1,Object obj2): compares the first object with second object.

Example

Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:

Student .java

class Student{

int rollno;

String name;

int age;

Accord Info Matrix


Chennai
Java Faculty Guide 245

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

AgeComparator.java

This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.

import java.util.*;

class AgeComparator implements Comparator<Student>{

public int compare(Student o1,Student o2){

Student s1=o1;

Student s2=o2;

if(s1.age==s2.age)

return 0;

else if(s1.age>s2.age)

return 1;

else

return -1;

} }

Accord Info Matrix


Chennai
Java Faculty Guide 246

NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

import java.util.*;

class NameComparator implements Comparator<Student>{

public int compare(Student o1,Student o2){

Student s1=o1;

Student s2=o2;

return s1.name.compareTo(s2.name);

} }

Simple.java

import java.util.*;

import java.io.*;

class Simple{

public static void main(String args[]){

ArrayList<Student> al=new ArrayList<Student>();

al.add(new Student(101,"Vijay",23));

al.add(new Student(106,"Ajay",27));

al.add(new Student(105,"Jai",21));

System.out.println("Sorting by Name...");

Collections.sort(al,new NameComparator());

Iterator itr=al.iterator();

while(itr.hasNext()){

Student st=itr.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

Accord Info Matrix


Chennai
Java Faculty Guide 247

System.out.println("sorting by age...");

Collections.sort(al,new AgeComparator());

Iterator itr2=al.iterator();

while(itr2.hasNext()){

Student st=itr2.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

Comparable and Comparator Interfaces

Comparable and Comparator both are interfaces and can be used to sort collection elements.
But there are many differences between Comparable and Comparator interfaces that are given
below.

Comparable Comparator
1) Comparable provides single Comparator provides multiple sorting sequence.
sorting sequence. In other words, we In other words, we can sort the collection on the
can sort the collection on the basis basis of multiple elements such as id, name and
of single element such as id or name price etc.
or price etc.
2) Comparable affects the original Comparator doesn't affect the original class i.e.
class i.e. actual class is modified. actual class is not modified.
3) Comparable provides compareTo() Comparator provides compare() method to sort
method to sort elements. elements.
4) Comparable is found Comparator is found in java.util package.
in java.lang package.
5) We can sort the list elements of We can sort the list elements of Comparator type
Comparable type by Collections.sort(List,Comparator) method.
by Collections.sort(List) method.

Accord Info Matrix


Chennai
Java Faculty Guide 248

FAQ

1. What is Generic in Java


2. What do you mean by a ‘Type Safe collection’ and how do you create a type safe
collection?
3. What is advantages of using Generic Collection
4. What is Comparable and Comparator interfaces
5. What is the difference between using a Comparable and Comparator
6. What is difference between the equals() and the compare() methods
7. What is compareTo() method.

Lab Task

Create an application that reads the data from employee table and loads it to an ArrayList
collection. The ArrayList should use Generic to add the employee records as ‘Employee’ Object.

 Iterate the Collection in order of the Name of the employees.


 Employee table should contain
 Employeeid, Employeename, department, designation
 Employee Object should represent the above table.

Accord Info Matrix


Chennai
Java Faculty Guide 249

Day 18 : Swing framework

Topic to Cover

 What is Graphical User Interface(GUI), Command Line Interface(CLI)


 What is advantage of GUI over CLI?
 What are windows based UI components
 What is swing framework, Abstract Window Toolkit (AWT), Advantage of Swing over
AWT.
 What is event driven application?
 Swing components, Layout managers.

Introduction

Till now we were using Command Line (console screen) as user interface. That is, we interact
with application through the console screen.

Now we are going to use Graphical User Interface (GUI) for interaction with the application.
GUI or Graphical User Interface means the user can interact with the application using the
windows based components.

Advantage of using GUI:

GUI applications are more user- friendly. That is, it gives an easy and interactive interface for
the user.

What is Swing Framework?

The Swing framework provides features for creating Graphical User Interface for java
applications. Swing framework is an advancement of earlier API called Abstract Window
Toolkit(AWT) for developing GUI java. Swing is the mostly used API for creating GUI in java.

Advantages of using Swing

When compared to the previously used API that is the AWT, Swing provides lot of advantages
as listed below

 Swing is light weight. That is swing use only lesser CPU and Memory resource to
execute.
 Swing has more advanced controls when compared to AWT

Accord Info Matrix


Chennai
Java Faculty Guide 250

 Swing has a unique feature called as pluggable look and feel feature that helps to
choose the appearance of the components

Usually the GUI based applications are even driven. That is application executes based on
event that happen in the application. In a GUI based application events are user actions in the
application. For example a user click on a button or select a menu item or type contents in to a
text box are considered as events. So GUI based applications are called as event driven
applications. Simply say event driven application waits for the user interaction to execute a
task.

Swing Components

The swing framework provides many GUI components to be used in an application’s interface.
It provides all commonly used windows based graphical components like buttons, textbox,
textarea, combo box, menus, radio buttons etc.,

Each Swing component is represented by corresponding classes in the framework. The entire
swing framework API is available in javax.swing package.

Swing Components

Component Description
JFrame It used to create a window. A window is basically a container that holds
other components line button, text field, menu bar etc.,
JButton JButton provides a Standard button that when the user click some task is
executed.
JTextField It provides a single line text input.
JTextArea It provides a multiline text input
JLabel A non editable text , usually used to create captions
JComboBox Creates a drop down list
JPasswordField Single line text for input password(masked text input)
JOptionPane Used to create dialogboxes like message dialog, input dialog
JMenuBar It used in menu creation, A menu bar is a container of menus, A menubar is a
collection of menus.
JMenu A menu is a collection of menus.
JMenuItem A menu item is essentially a button sitting in a list, that is, a menu. When the
user selects the "button", the action associated with the menu item is
performed

Accord Info Matrix


Chennai
Java Faculty Guide 251

How to create a Simple Window

A window can be created using either of the two methods. That is by extending the JFrame
class or by instantiating the JFrame class of the Javax.swing package.

Method 1

class MyFrame {

public static void main(String[]args){

JFrame frame = new JFrame();

frame.setSize(400,600);

frame.setTitle(“Welcome to GUI programming”);

frame.setResizable(false);

frame.setVisible(true)

Explain the program

The JFrame class represents a window component which is basically a container component is
windows. The JFrame class is instantiated to generate a window. One the window is created,
the dimension of the window is mentioned by using the setSize() method. The two parametes
of the setSize() represents the width and the height of the window. setTitle() method set the
Title of the window. That is , it set the text of the title bar if the window at the top.
setResizable() accepts a boolean value to allow or disallow the resizing of the window by the
user. setResizable(false) will set the widndow size fixed. Finally the window that is created will
be rendered on the screen by setting the setVisible() to true;

Method 2

Another way of creating a string is just extend the JFrame class.

class MyFrame extends JFrame{

MyFrame(){

setSize(400,600);

Accord Info Matrix


Chennai
Java Faculty Guide 252

setTitle(“Welcome to GUI programming”);

setResizable(false);

setVisible(true)

public static void main(String[] main){

new MyFrame();

}
}

The above class extends the JFrame class. So there is no need for creating the object for the
JFrame class.

Adding other UI components to the JFrame.

To add any UI component to a frame, just instantiate the corresponding of the UI component
and add to the frame by calling the add() method of the JFrame

For example:

class MyFrame extends JFrame{

JButton btn;

MyFrame(){

setSize(400,600);

setTitle(“Welcome to GUI programming”);

setResizable(false);

setVisible(true)

btn= new JButton(“Click”);

add(btn);

Accord Info Matrix


Chennai
Java Faculty Guide 253

public static void main(String[] main){

new MyFrame();

}
}

In the above program an object for the JButton class is create and added to the frame. This will
add a button to the frame.

Like this any component can be added to the frame.

Layout of a frame

A layout represents how the component will be arranged on the frame. It decides how the
frame will look like after the component is added to it.

There are different layouts available to apply for a swing frame. Each layout is represented by
corresponding classes. These classes are called as ’Layout Mangers’. Swing utilizes the Layout
manger class available in the java.awt package.

Different layouts and the corresponding manager classes

Flow layout: This layout add the controls to the right side of the existing control. In this layout
the components do not fill the entire screen. The size of the component is adjusted to the
content. For example the size of a button depends upon the caption of the button, size of a
dropdown is the size of the biggest element in the list. The flow layout is represented by the
class ‘FlowLayout’ in the java.awt package.

Grid Layout: This arranges the controls in a grid of row and columns. Number of rows and
columns in a grid can be controlled. In grid layout the size if the components is adjusted so the
entire area of the frame is shared by all the controls. The grid layout is represented by the class
GridLayout of the java.awt package

The default layout of a swing window is Card Layout. The card layout arranges the controls one
over the another and the components will fill the entire frame. So, only the last component will
be visible.

If you want to use custom layouts, that is , if you want to customize the arrangement of the
controls you should not use any of these above said layouts. The layout of a container, that is,

Accord Info Matrix


Chennai
Java Faculty Guide 254

a JFrame can be changed by using the setLayout() method of the JFrame class. To change the
layout, call this method by passing the object of the corresponding layout manager class.

Example - To set the layout as FlowLayout,

import java.awt.*;

import javax.swing.*;

public class MyFlowLayout{

JFrame f;

MyFlowLayout(){

f=new JFrame();

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));

//setting flow layout of right alignment

f.setSize(300,300);

f.setVisible(true);

public static void main(String[] args) {

new MyFlowLayout();

Accord Info Matrix


Chennai
Java Faculty Guide 255

Example – To set Grid Layout

import java.awt.*;

import javax.swing.*;

public class MyGridLayout{

JFrame f;

MyGridLayout(){

f=new JFrame();

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

JButton b6=new JButton("6");

JButton b7=new JButton("7");

JButton b8=new JButton("8");

JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));

//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);

f.setVisible(true);

public static void main(String[] args) {

new MyGridLayout();

Accord Info Matrix


Chennai
Java Faculty Guide 256

All the above layout will have its own way of ordering the components on the container. If you
want to manually arrange and place the components, we would not use any of the above
layout. Instead, we use “null” layout. That is, we are not going to use any layout.

How to set null layout


To set the null layout call the setLayout() method by passing null value
Example program
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class NullLayoutDemo {
public NullLayoutDemo() {
JFrame fr = new JFrame();
fr.setLayout(null);
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");
JButton btn3 = new JButton("Button 3");
JButton btn4 = new JButton("Button 4");
btn1.setBounds(50, 30, 100, 50); // Left,Top,Width,Height
fr.add(btn1);
btn2.setBounds(50, 100, 100, 50); // Left,Top,Width,Height
fr.add(btn2);
btn3.setBounds(50, 170, 100, 50); // Left,Top,Width,Height
fr.add(btn3);
btn4.setBounds(50, 240, 100, 50); // Left,Top,Width,Height
fr.add(btn4);
fr.setVisible(true);
fr.setSize(250, 400);
}
public static void main(String[] args) {
new NullLayoutDemo();
}}

Accord Info Matrix


Chennai
Java Faculty Guide 257

FAQ:
 What is swing framework
 What is GUI what is the advantage of using GUI in applications
 What is the advantage of using swing framework
 What is a layout manager
 How do you place a component in a custom location on JFrame

Accord Info Matrix


Chennai
Java Faculty Guide 258

Day 19 : Event driven Progaming


Topic to Cover
 What is event driven Programing?
 What is event
 How event is handled in java

Introduction

Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change of state of any object. Example : Pressing
a button, Entering a character in Textbox.

Event handling has three main components,

 Events : An event is a change of state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified when
an event occurs.
 Event Adapters : Event Adapters classes are abstract class that provides some methods
used for avoiding the heavy coding. Adapter class is defined for the listener that has
more than one abstract methods.

How Events are handled ?


A source generates an Event and send it to one or more listeners registered with the source.
Once event is received by the listener, they processe the event and then return. Events are
supported by a number of Java packages, like java.util, java.awt and java.awt.event.

Event Class Description Listener Interface

ActionEvent generated when button is pressed, menu-item ActionListener


is selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released also when

Accord Info Matrix


Chennai
Java Faculty Guide 259

the enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or textfield TextListener


is changed

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened or
closed

ComponentEvent generated when component is hidden, moved, ComponentEventListener


resized or set visible

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses FocusListener


keyboard focus

An Example program
import javax.swing.*;
import java.awt.event.*;
public class EventHandlingExample implements ActionListener{
JFrame f;
JButton b=new JButton("Say Hi");
public void createUI()
{
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
JLabel tbLabel = new JLabel("Click On Button");

Accord Info Matrix


Chennai
Java Faculty Guide 260

b.addActionListener(this);
tbLabel.setBounds(75, 50, 100, 20);
b.setBounds(75,75,150,20);
f.add(tbLabel);
f.add(b);
f.setVisible(true);
f.setSize(300,200);
}
public static void main(String[] args){
EventHandlingExample dd = new EventHandlingExample();
dd.createUI();
}

@Override
public void actionPerformed(ActionEvent e) {
b = (JButton)e.getSource();
sayHi();
}

public void sayHi()


{
JOptionPane.showMessageDialog(f, "Hi, To All.", "Say Hi",
OptionPane.INFORMATION_MESSAGE);
}
Handling Key Event
Here is the code of this program:
import java.awt.*;
import java.awt.event.*;
Accord Info Matrix
Chennai
Java Faculty Guide 261

public class KeyListenerTester extends JFrame implements KeyListener{


J TextField t1;
Label l1;
public KeyListenerTester(String s ) {
super(s);
JPanel p =new Panel();
l1 = new Label ("Key Listener!" ) ;
p.add(l1);
add(p);
addKeyListener ( this ) ;
setSize ( 200,100 );
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void keyTyped ( KeyEvent e ){
l1.setText("Key Typed");
}
public void keyPressed ( KeyEvent e){
l1.setText ( "Key Pressed" ) ;
}
public void keyReleased ( KeyEvent e ){
l1.setText( "Key Released" ) ;

Accord Info Matrix


Chennai
Java Faculty Guide 262

}
public static void main (String[]args ){
new KeyListenerTester ( "Key Listener Tester" ) ;
}
}

FAQ
1. What is event driven programming ?
2. Which package do you use in java for event driven progaming
3. What is a listener and an adapter
4. What are the components of event handling in java
5. What is event class
Task
Design a login window , when user click the login button after typing the userid and password,
verify the useid and password and move to the next screen. If the user is clicking the login
button with out typing in the userid or password, display an error message using a popup box.
In the screen, get student details like Name, mobile, mailed, course joined, date of join from the
user and send it to database.

Accord Info Matrix


Chennai
Java Faculty Guide 263

Day 20: Creating swing application using netbeans


Topic to Cover
 Introduction to Netbeans
 Why use an ide to develop an application
 What are the different ide available
 Different components of netbeans when we create GUI - Pallete , properties window,
Soruce view, design view

Create a simple application using database connectivity. Take an example like handling student
information. Create two forms one login form and the student’s details from. The user has to
login to access the student details form. In the second form get the details of the student using
different controls. Use DAO pattern to connect to database. Use components like text fields,
text area, combox box, radio buttons and buttons. Use JTable to populate the records form the
database table
Finally tell about how to create distributable jar.

Accord Info Matrix


Chennai
Java Faculty Guide 264

Core java project specification


Front end : Swing framework

Back end MySQL server

Use DAO Pattern for data base access

Form 1

Requirements :

User types the user id and password and clicks the login button. If user id or password
field is left blank then the error message should be prompted. If login is successful then next
screen as shown below. If login fails display a message

Accord Info Matrix


Chennai
Java Faculty Guide 265

Form 2

Requirements :

As the screen opens , then grid should be filled with the available data in the table.

User can save new record by entering the values in the corresponding fields and use the Save
Record Button. Student Id is auto generated.

Validation should be done when saving data

Student Id and Name are mandatory fields. Others can be updated later.

Search button is used to search a record by the student Id. When search button is clicked, the
student with the id that is given in the ‘Student Id ‘field should be retrieved and the data should
be displayed in the corresponding fields. If the searched id not found, message should be
displayed in a pop up box

Delete button and Update button remains disabled when the application starts

Accord Info Matrix


Chennai
Java Faculty Guide 266

Delete button and Update button are enabled only if the search is complete and the record is
found

After deletion or updating is complete then the button should again be disabled

On the Grid displayed below if a record is double clicked, then the corresponding record should
be loaded to the controls in the form, Update and delete button should be enabled. After
deletion or updating is complete then the button should again be disabled

Exit button terminates the application

Accord Info Matrix


Chennai

S-ar putea să vă placă și