Final Java Faculty Guide
Final Java Faculty Guide
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
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.
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.
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.
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.
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.
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.
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);
}
}
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.
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, operators, separators, and
keywords.
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;
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
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
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;
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;
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.
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) );
}
}
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) );
}
}
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 + 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 );
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 );
}
}
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 :
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.
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");
}
}
}
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");
}
}}
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.
}
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");
} } }
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);
}
}
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");
}
}
}
do
{
//Statements
}while(Boolean_expression);
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 );
}
}
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
for(int x : numbers ){
if( x == 30 ){
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
continue;
Example:
for(int x : numbers ){
if( x == 30 ){
continue;
}
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
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.
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.
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
}
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.
Syntax
<class_name>()
{
//initialization
}
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.
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).
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.
Lab Assignment
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
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
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);
}
}
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
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.
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
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.
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%)
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");
Output
Name Rajesh
Current Address Chennai
Mobile 9843156732
Calculate for 28 working days
Salary per day 1200 rupees
Salary is:1228.0
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
class TestIntf
{
public static void main(String args[])
{
MyInterfaceobj=new XYZ();
obj.method1();
}
}
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.
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
FAQ
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
40.0
30
60
}
}
Output
SBI Rate of Interest:8
ICICI Rate of Interest:7
AXIS Rate of Interest:9
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.
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.*;
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
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 ?
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
1. Single Dimensional
Syntax:
Datatype <varname>[]={val1,val2,……valN};
Datatype[] <varname>={val1,val2,……valN};
class Testarray{
course[0]=”JAVA”;//initialization
course[1]=”J2EE”;
course[2]=”PHP”;
course[3]=”DOT NET”;
course[4]=”ANDROID”;
{ System.out.println(course[i]); }
for(String temp:course)
System.out.println(temp);
}}
Syntax:
dataType []Varname[];
class Testarray3{
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();
} }}
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.
o By string literal
o By new keyword
1) String Literal
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";
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.
2) By new keyword
Example
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.
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.
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 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.
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.
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.
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.
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 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.
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
**
***
****
*****
b.
*****
****
***
**
c. *
* *
* * *
* * * *
* * * * *
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?
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;
int num;
num = scan.nextInt();
if(num%2 == 0)
else
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;
num = scan.nextInt();
if(num%i == 0)
count++; break;
if(count == 0)
else {
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;
char ch;
ch = scan.next().charAt(0);
else
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;
char ch;
ch = scan.next().charAt(0);
ch=='u' || ch=='U')
System.out.print("This is a Vowel");
else
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;
int yr;
yr = scan.nextInt();
else if(yr%100 == 0)
else if(yr%400 == 0)
else
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;
num = scan.nextInt();
orig=num;
while(num>0)
rem = num%10;
num = num/10;
if(orig == rev)
else
Source Code
import java.util.Scanner;
int a, b, res;
a = scan.nextInt();
b = scan.nextInt();
res = a + b;
res = a - b;
res = a * b;
res = a / b;
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;
num = scan.nextInt();
temp = num;
while(num>0)
rem = num%10;
sum = sum+rem;
num = num/10;
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;
n = scan.nextInt();
arr[i] = scan.nextInt();
armean = sum/n;
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.
Source Code
import java.util.Scanner;
int i;
mark[i] = scan.nextInt();
avg = sum/5;
if(avg>80)
System.out.print("A");
System.out.print("B");
System.out.print("C");
else
System.out.print("D");
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;
num = scan.nextInt();
tab = num*i;
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;
n = scan.nextInt();
num = scan.nextInt();
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;
int a, b, temp;
System.out.print("A = ");
a = scan.nextInt();
System.out.print("B = ");
b = scan.nextInt();
temp = a;
a = b;
b = temp;
}}
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;
num = scan.nextInt();
while(num != 0)
rem = num%10;
num = num/10;
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;
arr[i] = scan.nextInt();
if(arr[i] < 0)
countn++;
else if(arr[i] == 0)
countz++;
else
countp++;
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.
Source Code
import java.util.Scanner;
start = scan.nextInt();
end = scan.nextInt();
System.out.print("Prime Numbers Between " + start + " and " +end+ " is :\n");
count = 0;
if(i%j == 0)
count++;
break;
if(count == 0)
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;
int a, b, c, big;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
big = a;
if(big<b)
if(b>c)
big = b;
else
big = c;
else if(big<c)
if(c>b)
big = c;
else
big = b;
else
big = a;
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.
Source Code
import java.util.Scanner;
num = scan.nextInt();
fact = fact*i;
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.
Source Code
import java.util.Scanner;
x = scan.nextInt();
y = scan.nextInt();
a = x;
b = y;
while(b != 0)
t = b;
b = a%b;
a = t;
hcf = a;
lcm = (x*y)/hcf;
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;
len = scan.nextInt();
bre = scan.nextInt();
area = len*bre;
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;
float r;
r = scan.nextFloat();
area = 3.14*r*r;
circum = 2*3.14*r;
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;
float fah;
double cel;
fah = scan.nextFloat();
}}
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;
float cen;
double fah;
cen = scan.nextFloat();
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
String ch;
int i;
ch = new Character((char)i).toString();
}}}
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;
limit = scan.nextInt();
c = a + b;
limit = limit - 2;
while(limit>0)
a = b;
b = c;
c = a + b;
limit--;
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 :
Source Code
import java.util.Scanner;
n = scan.nextInt();
nu = n;
while(nu != 0)
rem = nu%10;
nu = nu/10;
if(num == n)
System.out.print("Armstrong Number");
else
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;
num1 = scan.nextInt();
num2 = scan.nextInt();
temp = i;
n = 0;
while(temp != 0)
rem = temp%10;
n = n + rem*rem*rem;
temp = temp/10;
if(i == n)
if(count == 0)
count++;
if(count == 0)
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;
int fact=1, i;
fact = fact*i;
return fact;
int n, r;
n = scan.nextInt();
r = scan.nextInt();
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.
Source Code
int i, j, n=1;
n++;
System.out.println();
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.
Source Code
import java.util.Scanner;
int n, c, k, space=1;
n = scan.nextInt();
space = n-1;
System.out.print(" ");
space--;
System.out.print("*");
System.out.println();
space = 1;
System.out.print(" ");
space++;
System.out.print("*");
System.out.println();
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;
range = scan.nextInt();
System.out.println();
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;
int r, i, k, number=1, j;
r = scan.nextInt();
for(i=0;i<r;i++)
System.out.print(" ");
number = 1;
for(j=0;j<=i;j++)
System.out.println();
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;
int n, i;
n = scan.nextInt();
arr[i] = scan.nextInt();
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;
size = scan.nextInt();
arr[i] = scan.nextInt();
large = arr[0];
large = arr[i];
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;
size = scan.nextInt();
arr[i] = scan.nextInt();
while(i<j)
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
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;
size = scan.nextInt();
arr[i] = scan.nextInt();
del = scan.nextInt();
if(arr[i] == del)
arr[j] = arr[j+1];
count++;
break;
if(count==0)
else
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.
Source Code
import java.util.Scanner;
row = scan.nextInt();
col = scan.nextInt();
arr[i][j] = scan.nextInt();
System.out.println();
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;
int i, j;
mat1[i][j] = scan.nextInt();
mat2[i][j] = scan.nextInt();
System.out.println();
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;
int i, j;
mat1[i][j] = scan.nextInt();
mat2[i][j] = scan.nextInt();
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;
int i, j;
arr[i][j] = scan.nextInt();
System.out.print("Transposing Array...\n");
arrt[i][j] = arr[j][i];
System.out.println();
}}
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;
int m, n, p, q, sum = 0, c, d, k;
m = in.nextInt();
n = in.nextInt();
first[c][d] = in.nextInt();
p = in.nextInt();
q = in.nextInt();
if ( n != p )
else
second[c][d] = in.nextInt();
multiply[c][d] = sum;
sum = 0;
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;
String strOrig;
strOrig = scan.nextLine();
System.out.print("Copying String...\n");
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;
int i, len;
orig = scan.nextLine();
len = orig.length();
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.
Source Code
import java.util.Scanner;
strOrig = scan.nextLine();
System.out.print(strNew);
Source Code
import java.util.Scanner;
String str, r;
str = scan.nextLine();
r = removeVowels(str);
System.out.print(r);
int i;
if (!isVowel(Character.toLowerCase(s.charAt(i))))
return finalString;
int i;
if(c == vowels.charAt(i))
return true;
return false;
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;
strOrig = scan.nextLine();
word = scan.nextLine();
System.out.print(strOrig);
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;
char c, ch;
str=scan.nextLine();
i=str.length();
k=0;
ch = str.charAt(j);
if(ch == c)
k++;
if(k>0)
System.out.println("The character " + c + " has occurred for " + k + " times");
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;
int count = 1;
count++;
return count;
String sentence;
sentence = scan.nextLine();
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;
int i;
str = scan.nextLine();
System.out.println(strWithoutSpace);
sb.append(strArray[i]);
System.out.println(sb);
}}
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;
int i, j;
String temp;
names[i] = scan.nextLine();
if(names[j-1].compareTo(names[j])>0)
temp=names[j-1];
names[j-1]=names[j];
names[j]=temp;
for(i=0;i<5;i++)
System.out.println(names[i]);
Source Code
import java.util.Scanner;
char ch;
int temp;
ch = scan.next().charAt(0);
ch = (char) temp;
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;
str1 = scan.nextLine();
str2 = scan.nextLine();
strtemp = str1;
str1 = str2;
str2 = strtemp;
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;
str1 = scan.nextLine();
str2 = scan.nextLine();
len1 = str1.length();
len2 = str2.length();
if(len1 == len2)
len = len1;
found = 0;
if(str1.charAt(i) == str2.charAt(j))
found = 1;
break;
if(found == 0)
not_found = 1;
break;
if(not_found == 1)
else
else
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;
len = scan.nextInt();
System.out.print("\nGenerating " + len + " Random Numbers in the range 0...999 \n");
randnum = rn.nextInt(1000);
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.*;
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
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
4 Errors are mostly caused by the Exceptions are mainly caused by the
environment in which application is application itself
running
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.
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.
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.
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.
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;
}
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
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
}
Try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
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.
InvalidAgeException(String s){
super(s);
class TestCustomException1{
if(age<18)
else
System.out.println("welcome to vote");
try{
validate(13);
Lab Assignment
FAQ
1. How the exceptions are handled in java? OR Explain exception handling mechanism 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?
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?
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?
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?
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
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
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.
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");
}
}
}
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
{
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{
}
}
while((ch=(char)ob.read())!='x')
fout.write(ch);
}
fout.close();
}
}
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 {
else{
System.out.println("File does not exists!");
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
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)
{
System.exit(0);
else {
}
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.");
}
}
switch(args.length){
System.exit(0);
case 1: deletefile(args[0]);
System.exit(0);
System.exit(0);
}
}
}
Reading Bytes from File
import java.io.*;
public class bytes2 {
public static void main(String[] aaaa)throws IOException
{
FileInputStream infile=null;
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
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.
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:
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:
Marking the field transient prevents the state from being written to the stream and from being
restored during deserialization.
Serializing an Object:
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.
import java.io.*;
e.number = 101;
try
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.*;
Employee e = null;
try
e = (Employee) in.readObject();
in.close();
fileIn.close();
catch(IOException i)
{ i.printStackTrace();
return;
catch(ClassNotFoundException c)
System.out.println("Deserialized Employee...");
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.
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?
Topics to Cover
What is Database
Importance of Database
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.
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
Create
Alter
Drop
Insert
Update
Delete
Grant
Revoke
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);
Syntax
alter table <tblname> change column <old column name> <new column name>
<datatype>;
Eg:
Syntax
eg:
Syntax
eg:
Rename Table
Syntax
eg:
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.
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’
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
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
Topics to Cover
1. Primary key
2. Foreign key.
3. Sub Queries
4. Aggregate functions.
5. Joins and types of joins.
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));
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 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.
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
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.
count()
eg:
select count(*) from tablename conditions; // count of records , get from select query
with condition;
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
eg:
select sum(salary) from empsalary; // get total sum amount of salary column.
avg()
The avg() function calculates the average value of a set of values. It ignores NULL values in the
calculation.
Syntax
eg:
min()
Syntax
eg:
max()
Syntax
eg:
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.
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
ON table1.column = table2.column;
Visual Illustration
In this visual diagram, the MySQL INNER JOIN returns the shaded area:
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
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:
If we run the MySQL SELECT statement (that contains an INNER JOIN) below:
FROM suppliers
ON suppliers.supplier_id = orders.supplier_id;
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
SELECT columns
FROM table1
ON table1.column = table2.column;
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
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:
FROM suppliers
ON suppliers.supplier_id = orders.supplier_id;
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
SELECT columns
FROM table1
ON table1.column = table2.column;
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:
FROM suppliers
ON suppliers.supplier_id = orders.supplier_id;
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
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
To create above all tables and insert records. Write queries for below task.
Task List
Topic to Cover
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.
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 −
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 −
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.
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 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 −
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.
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.
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.
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.
Step 1:
You need to do this registration only once in your program. You can register a driver in
one of two ways.
try{
}catch(ClassNotFoundException ex){
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)
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.
Example
try{
}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.
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”);
Statement statement=conn.createStatement();
}catch(Exception ex){
System.out.println(e);
}
try{
PreparedStatement statement=conn.prepareStatement(“query”);
}catch(Exception ex){
System.out.println(e);
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{
PreparedStatement statement=conn.prepareStatement(“query”);
ResultSet result=statement.executeQuery();
}catch(Exception ex){
System.out.println(e);
Or
try{
Statement statement=connection.createStatement();
}catch(Exception ex){
System.out.println(e);
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.
while(result.next()) {
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.
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:
while(result.next()) {
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
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.
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:
while(result.next()) {
int age=result.getInt(ageIndex);
FAQ
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.
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 ?
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.
What is protocol?
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.
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.
Method Description
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");
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.
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.
The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests.
Attempts to create a server socket bound to the specified port. An exception occurs if the port
is already bound by another application.
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.
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.
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.
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.
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.
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.
Returns the input stream of the socket. The input stream is connected to the output stream of
the remote socket.
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();
}
}
}
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.
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
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.
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
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.
Output
Output
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?
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.
The above statement will create an array of string that can hold ten names.
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:
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.
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.
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:
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.
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.
Collection
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.
import java.util.*;
public class VectorDemo {
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.");
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);
}
}
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.
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;
}
}
}
}
}
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());
}
}
}
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 {
// 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();
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.
Topics to Cover
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.
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.
list.add("hello");
Example
import java.util.*;
class TestGenerics1{
list.add("rahul");
list.add("jai");
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
import java.util.*;
class TestGenerics2{
map.put(1,"vijay");
map.put(4,"umesh");
map.put(2,"ankit");
Set<Map.Entry<Integer,String>> set=map.entrySet();
Iterator<Map.Entry<Integer,String>> itr=set.iterator();
while(itr.hasNext()){
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.
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.
public void sort(List list): is used to sort the elements of List. List elements must be of
Comparable type.
Comparable Example
int rollno;
String name;
int age;
this.rollno=rollno;
this.name=name;
this.age=age;
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
TestSort.java
import java.util.*;
import java.io.*;
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){
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;
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.*;
Student s1=o1;
Student s2=o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
} }
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.*;
Student s1=o1;
Student s2=o2;
return s1.name.compareTo(s2.name);
} }
Simple.java
import java.util.*;
import java.io.*;
class Simple{
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("sorting by age...");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=itr2.next();
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.
FAQ
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.
Topic to Cover
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.
GUI applications are more user- friendly. That is, it gives an easy and interactive interface for
the user.
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.
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
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
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 {
frame.setSize(400,600);
frame.setResizable(false);
frame.setVisible(true)
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
MyFrame(){
setSize(400,600);
setResizable(false);
setVisible(true)
new MyFrame();
}
}
The above class extends the JFrame class. So there is no need for creating the object for the
JFrame class.
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:
JButton btn;
MyFrame(){
setSize(400,600);
setResizable(false);
setVisible(true)
add(btn);
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.
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.
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,
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.
import java.awt.*;
import javax.swing.*;
JFrame f;
MyFlowLayout(){
f=new JFrame();
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
new MyFlowLayout();
import java.awt.*;
import javax.swing.*;
JFrame f;
MyGridLayout(){
f=new JFrame();
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));
f.setSize(300,300);
f.setVisible(true);
new MyGridLayout();
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.
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
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.
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");
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 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.
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.
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
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.
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
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