java22
java22
Sc (4 th sem)
CORE JAVA
[P.Y.KUMAR]
1|P age
UNIT – I
Introduction to Java: Features of Java, The Java virtual Machine, Parts of Java
Naming Conventions and Data Types: Naming Conventions in Java, Data Types in
Java, Literals Operators in Java: Operators, Priority of Operators Control Statements
in Java: if... else Statement, do... while Statement, while Loop, for Loop, switch Statement,
break Statement, continue Statement, return Statement Input and Output: Accepting Input
from the Keyboard, Reading Input with Java.util.Scanner Class, Displaying Output with
System.out.printf(), Displaying Formatted Output with String.format() Arrays: Types of
Arrays, Three Dimensional Arrays (3D array), arrayname.length, Command Line Arguments
UNIT – II
Strings: Creating Strings, String Class Methods, String Comparison, Immutability of Strings
Introduction to OOPs: Problems in Procedure Oriented Approach, Features of Object-
Oriented Programming System (OOPS) Classes and Objects: Object Creation, Initializing the
Instance Variables, Access Specifiers, Constructors Methods in Java:Method Header or
Method Prototype, Method Body, Understanding Methods, Static Methods, Static Block,
The keyword „this‟, Instance Methods, Passing Primitive Data Types to Methods, Passing
Objects to Methods, Passing Arrays to Methods, Recursion, Factory Methods Inheritance:
Inheritance, The keyword „super‟, The Protected Specifier, Types of Inheritance
UNIT – III
Polymorphism: Polymorphism with Variables, Polymorphism using Methods,
Polymorphism with Static Methods, Polymorphism with Private Methods, Polymorphism
with Final Methods, final Class
Type Casting: Types of Data Types, Casting Primitive Data Types, Casting Referenced Data
Types, The Object Class Abstract Classes: Abstract Method and Abstract Class
Interfaces: Interface, Multiple Inheritance using Interfaces Packages: Package, Different
Types of Packages, The JAR Files, Interfaces in a Package, Creating Sub Package in a
Package, Access Specifiers in Java, Creating API Document Exception Handling: Errors in
Java Program, Exceptions, throws Clause, throw Clause, Types of Exceptions, Re – throwing
an Exception
2|P age
UNIT – IV
Streams: Stream, Creating a File using FileOutputStream, Reading Data from a File
uingFileInputStream, Creating a File using FileWriter, Reading a File using FileReader,
Zipping and Unzipping Files, Serialization of Objects, Counting Number of Characters in a
File, File Copy, File Class
Threads: Single Tasking, Multi Tasking, Uses of Threads, Creating a Thread and Running it,
Terminating the Thread, Single Tasking Using a Thread, Multi Tasking Using Threads,
Multiple Threads Acting on Single Object, Thread Class Methods, Deadlock of Threads,
UNIT – V
Applets: Creating an Applet, Uses of Applets, <APPLET> tag, A Simple Applet, An Applet with
Swing Components, Animation in Applets, A Simple Game with an Applet, Applet
Parameters
Java Database Connectivity: Database Servers, Database Clients, JDBC (Java Database
Connectivity), Working with Oracle Database, Working with MySQL Database, Stages in a
JDBC Program, Registering the Driver, Connecting to a Database, Preparing SQL Statements,
Using jdbc–odbc Bridge Driver to Connect to Oracle Database, Retrieving Data from MySQL
Database, Retrieving Data from MS Access Database, Stored Procedures and
CallableStatements, Types of Result Sets
BOOKS:
1. Core Java: An Integrated Approach, Authored by Dr. R. Nageswara Rao
&KogentLearning Solutions Inc.
2. E.Balaguruswamy, Programming with JAVA, A primer, 3e, TATA
McGraw-Hill Company.
3|P age
Fundamentals of Object oriented Programming
Object Oriented Program
The general concepts of OOP which form the heart of Java language are
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a
class.
Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type support.
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging
the tail, running.
If you compare the software object with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields and
behavior is shown via methods.
4|P age
EXAMPLE.
Person Object
Name Data
Basic Pay
Salary ( ) Methods
Tax ( )
F IGURE 1: R EPRESENTATION OF AN O BJECT
Data
Information “in” and Information “out”
Method
Abstraction refers to the act of representing essential features without including the
background details or explanation.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concept of hierarchical classification.
Bird
Attributes:
Feathers, Lay
Eggs
Flying Bird Non-Flying
Attributes: Bird
---------- Attributes:
----------
Robin Parrot Penguin Kiwi
Attributes: Attributes: Attributes: Attributes:
---------- ---------- ---------- ---------- 5|P age
Polymorphism
Polymorphism is another important OOP concept. Polymorphism means the ability to
take more than one form. For example, an operation may exhibit different behavior in
different instances. The behavior depends upon the types of data used in the operation.
Shape
Draw()
Object 1
Object 5 Object 2
6|P age
Object 4 Object 3
F IGURE 5: N ETWORK OF OBJECTS COMMUNICATING BETWEEN THEM
Q. What are the benefits and disadvantages of OOP and what are the applications
of OOP?
Principles or Advantages
1. Through inheritance, we can eliminate redundant code and extend the use of existing
class.
2. We can build a program from standing working modules that can communicate with
one another rather than having to start writing the code from scratch. This leads to
saving of development time and highs productivity.
3. The principles of data hiding helps programmer to build a secure program. This code
is not overrun other parts of programs.
4. It is possible to have multiple objects to co exists without an interference.
5. It is easy to partition the work in a project based on objects.
6. The data-centered design approach to capture more details of model in an
implementation form.
7. Object oriented systems can be easily upgraded from small to large systems.
8. Message passing techniques for communication between objects make the interface
descriptions, with external systems much simpler.
9. Software complexity can be easily managed.
Applications of OOP
The most popular application Of OOP has been in the area of user interface design
such as windows. OOP is useful in this type of applications because it can simplify complex
problem. The promising areas for application of OOP include:
Some disadvantages:
1) Steep learning curve: The thought process involved in oop’s may not be natural for
some people and it can take to get used to it. It is a programming techniques such as
inheritance and polymorphism can be challenging to a comprehend initially
3) Slower programs :
7|P age
JAVA EVOLUTION
Java History
Java is purely Object Oriented Language developed by James Gosling and his team
of Sun Microsystems of U.S.A. in 1991. Java was designed for the development of software
for consumer electronic devices like TVs and VCRs, toasters etc. The initial name of the
language is oak and later it was renamed as Java.
Year Development
The team came up for developing web applets (small programs) that
1993
could run on all types of computers connected to the Internet.
The team developed a web browser called Hot Java to locate and run
1994
applet programs on Internet.
Oak was renamed as Java. Many companies like Microsoft and Netscape
1995
announced their support to Java.
Sun Microsystems released JDK 1.1 (Java Development Kit) for general
1996
purpose object-oriented programming.
1999 Standard Edition (J2SE) and Enterprise Edition (J2EE) are released.
8|P age
q) Write about parts of java?
1. Java SE: It is the java standard edition that contains basic core java classes. This is
edition is used to develop standard applets and applications
2. Java EE: It is the java enterprise edition and it contains classes that are beyond java
SE. Infact java SE inorder to used many of the classes in java EE.java EE mainly
concentrates on providing business solutions on a network
3. Java ME: It standards for java Microedition.java ME is for developers who develop
code for portable devices. such as a PDA or a cellular phone code on these devices
needs to be small in size and should take less memory
Java is currently supported on Windows, Sun Solaris, Macintosh, and UNIX systems.
The minimum hardware and software requirements for windows version of Java are as
follows.
IBM 486 system.
Minimum 8MB memory.
Windows operating system.
Hard drive
CDROM drive
Mouse
C++
C Java
Simple
Java programming language is simple to use and easy to learn. It manages to handle
all of its concepts in a quite flexible manner. Moreover, it extracts all most all the features of
C and C++.
Secure
All the Java that provides the user is nothing but secured programming techniques.
Java implements a separate security manager so that the user can be benefited in
implementing the objects with ease of use.
10 | P a g
e
Robust
Strongly typed
Often saying, Java is strongly typed language, is absolute because it is very much
particular about type of the data. The user needs to be careful while dealing with data types.
Platform Independent and Portable
Java combines with both compiler and Interpreter. First java compiler translates the
source code into byte codes as intermediate files. In second, Java Interpreter generates the
byte code into machine code. It can be ported to any platform without any problem. I.e. Java
programs can be easily moved from one computer to another. This is the one of major
advantages of Java.
Object Oriented
Java is true Object Oriented Language. Java comes with a set of classes, which we
can use in our programs. The object model in Java is simple and easy to extend.
Dynamic
Dynamic nature of Java gives more comfort to the designer because dynamic
declaration and re-declaration of data member becomes easy at run time. This makes it
possible to dynamically link the code in a safe manner.
Distributed
Java is designed for distributed environments like Internet. Java objects are
distributed over the network and get executed remotely on demand.
Multithreaded
A thread can be defined as a process, a task, a path, to an execution or a block of
code. Simultaneous execution of two or more blocks of code within the same program is
referred to as multithreading. Java supports multithreading which allows to you to run many
tasks simultaneously. Java provides built in support for multithreading so that the user can
design such applications in most sophisticated way.
Scalability and Performance
Java increases in scalability and performance by improving startup time and reducing
the amount of memory used in Java to runtime environment.
Monitoring and manageability
Java supports a number of APIs, such as JVM Monitoring and Management API, Sun
Management Platform Extension, Logging, Monitoring and management Interface, and Java
Management Extension (JMX) to monitor and manage applications.
JDBC
It supports JDBC to send data in a tabular format between the remote components of
a distributed enterprise application.
Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method, etc.
But, it is not forced to follow. So, it is known as convention not rule. These conventions
are suggested by several Java communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language
are given according to the Java naming convention. If you fail to follow these
conventions, it may generate confusion or erroneous code.
By using standard Java naming conventions, you make your code easier to read for
yourself and other programmers. Readability of Java program is very important. It
indicates that less time is spent to figure out what the code does.
The following table shows the popular conventions used for the different identifiers.
Class It should start with the uppercase letter. public class Employee
It should be a noun such as Color, {
Button, System, Thread, etc. //code snippet
Use appropriate words, instead of }
acronyms.
Web Browser Program that access to WWW and runs Java applets.
13 | P a g
e
Q. Explain Java and World Wide Web?
1. The user sends a request for an HTML document to the remote computer’s web
server. The web server is a program that accepts a request, processes the request,
and sends the required document.
2. The HTML document is returned to the user’s browser. The document contains the
applet tag, which identifies the applet.
3. The corresponding applet byte code is transferred to the user’s computer. This byte
code had been previously created by the java compiler using the java source code file
for that applet.
4. Java enabled browser on the user’s computer interprets the byte code and provides
output.
Web browsers are used to navigate through the information found on the net. They
allow us to retrieve the information spread across the internet and display it using the HTML.
Hot Java
It is the web browser from sun micro system that enables to display the interactive
content on the web. It is available for SPARC/ Solaris platform as well as Windows. Hot
14 | Java
Pag
is written entirely in Java and demonstrates the capabilities of the Java programming
e
language. It is the first web browser to provide support for the Java language thus making
the web dynamic and interactive.
Netscape Navigator
Internet Explorer
Chrome,firefox,safari,opera,seamonkey,k-meleon,camino,amaya,kidzui
etc…
JIT Interpreter
compiler
Runtime Env.
To create a java program we need to create a source code using text editor. The source code
is compiled using a java compiler javac and executed using the java interpreter java. Java
debugger is used to find errors if any in the source code. A compiled java program can be
converted into source code with the help of javap java disassembler.
16 | P a g
e
17 | P a g
e
Overview of Java Language
1. Documentation Section
2. Package Statement
3. Import Statements
4. Interface Statements
5. Class Declarations
6. Main method class
{
7. Main method declaration
}
EXAMPLE
The documentation section comprises a set of comment lines giving the name of the
program, and other details. Java uses a special type of comment /**…..*/ known as
documentation comment.
Package statement
The first statement allowed in Java file is package statement. This statement declares
package name and informs the compiler that the classes defined here belong to this package.
Java provides built-in packages.
import statement
interface statement
An interface is like a class but includes a group of method declarations. It is used only
to implement the multiple inheritance.
Class definition
Class declaration
The first line declares a class. Class is a keyword and declares a new class; sample is kava
identifier that specifies name of the class.
The second line is open brace; every class definition in java begins with an open brace and
ends with a matching close brace.
Main line
The third line defines a method named main, which is similar to main () function in C. every
java application program must include the main () method. This is the starting point for the
interpreter to begin execution of program. A program may have any number of classes but
only one class must include main function.
The keyword public specifies that the main method is accessible to all other classes.
The main method must be declared as static since the interpreter uses these methods
before any objects are created.
The type modifier void states that the main method does not return any value.
19 | P a g
e
Output line
Smallest individual units in a program are known as tokens. Java language includes 5
types of tokens. They are reserved words or key words, Identifiers, Literals, Operators, and
Separators.
Note: Every java statement forms with set of tokens, forms with the java character set. The
characters are defined by the Unicode character set. The Unicode is a 16-bit character
coding system currently supports more than 34000, defined characters derived characters
from 24 languages.
Key words
Identifiers
The purpose of identifier is for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
Rules
1. Names of all public methods and instance variables start with a lowercase letter.
2. When more than one word is used in a name, the second and subsequent words are
marked with uppercase letters.
3. All private and local variables use only lowercase letters combined with underscore.
4. All classes and interfaces start with uppercase letter. 20 | P a g
5. Variables that represent constant values use uppercase letters. e
Literals or constants in java
Literals in Java are sequence of characters that represent constant values to be stores
in variables. Java specifies 5 major types of literals.
Integer literal.
Floating point literal.
Character literal.
String literal.
Boolean literal.
Separators
Separators are symbols used to indicate where groups of code are divided and
arranged.
Name Use
Operators
Operator is a symbol that takes one or more arguments and operates on them to
produce a result. Java supports a rich set of operators like arithmetic operators, relational
operators, logical operators, and bitwise operators.
Arithmetic operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
When one of the operand is real and other is integer then the operation is called
mixed mode arithmetic expression.
Relational operators
These are used to test for equality of expressions. These result either true or false
value.
Operator Meaning
== Equal to
!= Not equal to
Logical operators
Logical operators are used to form compound conditions by combining two or more
relational expressions.
Operator Meaning
|| Logical OR
! Logical NOT
Assignment operators
Variable op=exp;
Simple assignment operator is = (equal to). The general syntax of simple assignment
operator is
Java has two very useful operators not generally found in many other languages.
These are increment (++) and decrement (--) operators. The operators ++ adds 1 to the
operand while – subtracts 1 from the operand. Both are unary operators and are used in the
following form:
The exp1 is evaluated first. If it returns true, the exp2 is evaluated, else the exp3 is
evaluated.
Ex: c = (a>b? a : b );
Bitwise operators
Java has set of bitwise operators to manipulate data at bit level. Bitwise operators
may not be applied for float or double.
Operator Meaning
! Bitwise OR
^ Bitwise exclusive OR
Java supports special operators such as instanceof operator and member selection
operator.
Instanceof:
It is an object reference operator and returns true if the object on the left side is the
instance of the class given on right side otherwise it returns false.
The statement is true if the object sai belongs to the class student.
DOT operator:
The dot (.) operator is used to access the instance variables and methods of class
objects.
23 | P a g
e
q)Explain Operators and their precedence ?
1 . () L to R
3 *, /,% L to R
4 +,- L to R
7 ==, != L to R
8 to 10 &, ^, | L to R
11 , 12 && and || L to R
13 ?: R to L
14 = R to L
A data type defines the set of values that an expression produced or a variable can
contain. The data type of variable or expression also defines the operation that can be
performed on the variable or expression. The type of variable is established by the variable
declaration while the type of an expression is determined by the definitions of its operations
and the type of their operands.
Conceptually there are two types of data types in Java program primitive types
4 DATA TYPES
JAVA
Data
types
Non-
Primitive
Primitive
(Intrinsic)
(Derived)
Non -
Numeric Classes Interface Arrays
numeric
Floating
Integer Character Boolean
point 24 | P a g
e
Figure 7: Data Types in Java.
Primitive type
It is also called as built-in types or intrinsic data types. A primitive data type
represents a single value such as a number or character or a Boolean value. Java has
primitive types for arithmetic and Boolean.
Arithmetic
There are two types of arithmetic type’s integer and floating point.
Integer types are byte, short, int, long and char. Floating point types are float and double.
Floating point types Java provides two sizes of floating point number single precision,
double precision.
Sign mantissa 2 ^exp, where sign is +1 or -1. Mantissa is a +ve integer less than 2 24 and
exponent is an integer in the inclusive range -149 to 104.
Sign mantissa 2^exp, where sign is +1 or -1, mantissa is a +ve integer less than 253 and
exponent is an integer inclusive range -1045 to 1000.
-9223372036854775808 to
Long 64 bit signed
9223372036854775807
Boolean type
The Boolean data type represents two values true or false. These values are key
words in Java. Java provides the following kinds of operators for Boolean values.
Character type
25 | Pbut
Java provides a character data type called char. The char occupies two bytes ag
basically it can hold only a single character. e
Constants
Constants in java refer to fixed values that do not change during the program execution
of a program. Java supports several types of constants.
1. Numerical constants.
a. Integer constants.
b. Real constants.
2. Character constants.
a. Single character constants
b. String constants
Integer constants refer to a sequence of digits. There are three types of integer’s namely
decimal, octal and hexadecimal integers.
Real constants used to represent the numbers containing fractional parts. A real number
may also be expressed in exponential notation also.
Single Character constants contain a single character enclosed within a pair of single
quotation marks.
Java supports some special backslash character constants that are used in output
methods. These characters combinations are known as escape sequences.
Constant Meaning
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\’ single quote
\” double quote
\\ backslash
Symbolic Constants
Variables
The variables are the names of storage locations. A variable must be declared before
it is used in the program. A variable can be used to store a value of any data type. The
declaration statement defines the type of variable. The declaration of variable is:
26 | P a g
Type variable1, variable2, ……., variable N;
e
Scope of variables
Instance Variables
Class variables
Local variables
) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a method
declaration. They are Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These variables
should be initialized first, before the initialization of any instance variables.
Type casting
Type casting means represent a value of type into a variable of another type. Casting
into a smaller type may result in a loss of data. For some types java does the conversion of
the assigned value automatically; there is no need of cast. This is known as automatic type
conversion. Automatic type conversion is possible only if we are assigning values into higher
precision types.
Command line arguments are parameters that are supplied to the application program
at the time of invoking it for execution. It is also known as command line arguments.
Depending on the content hold by the variable, the variables are divided into two
types.
1. Reference variable
2. Primitive variable.
Reference variable:
String s=”java”;
int i=10;
Depending on the position at which the variable is declared, are divided into 3 types.
1. Instance variable
2. Static variable
3. Local variable
Instance variable:
1. If the value of variables is varied from instance to instance, such type of variables is
called instance variables.
2. We can declare instance variables within a block, but outside of any method or block.
3. These are also known as attributes / properties / member variables.
4. The instance variable will create whenever an object is created and destroyed
whenever garbage collector destroys the object.
5. Instance variables will get default values and no need to perform explicit initialization.
Ex:
class Test
{
int a;
public static void main(String args[])
{
Test obj=new Test();
System.out.println(obj.a);
}
}
Static variable:
1. A single copy of the static variable will maintain and shared by all instances.
2. The value of the static variable is the same for all instances.
3. The static variables will create whenever the class loaded into memory and destroy
whenever the class is unloaded from memory.
4. These variables are also known as fields.
5. Static variables will get default values and no need to perform explicit initialization.
6. Static variables we can access by using either class name or by using the object
reference.
28 | P a g
e
Local variables:
1. The variables which are declared inside a method or block or as method arguments
are called local variables.
2. Also known as temporary variables.
3. The local variables will create as the part of the method execution and will destroy
whenever the method termination.
4. The local variables never get default values and must be initialized before using those
local variables.
Q. What are the ways to scan the data from the standard input device?
1. System.in.read()
2. Scanner class
3. Command line arguments
4. Stream classes
System.in.read()
It behaves like a getch() in C language, which reads a single character only. It doesn’t
read a group of characters.
Ex:
Char ch;
Ch=(char)System.read();
Scanner Class
Scanner class is defined in java.util package. It is used to scan the primitive types
from input resources (jdk 1.5).
int nextInt()
float nextFloat()
boolean nextBoolean()
char nextChar()
String next()
string nextLine()
double nextDouble()
Long nextLong()
byte nextByte()
Short nextShort()
Ex:
Scanner sc= new Scanner(System.in);
int a =sc.nextInt();
Example:
import java.util.*;
class UserInputDemo
[ 29 | P a g
e
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
int c=a+b;
System.out.println("Total= " +c);
}
}
Example2:
import java.util.*;
class UserInputDemo1
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine(); //reads string
System.out.print("You have entered: "+str);
}
}
Stream class
A stream is a sequence of data. A program uses an input stream to read data from a
source, one item at a time. The DataInputStream available in java.io package is used to read
data from input stream and also from the file streams.
Ex:
DataInputStream in = new DataInputStream(System.in);
int x=Integer.parseInt(in.readLine());
Another method of using Stream classes to read input from the keyboard are using
the classes InputStreamReader and BufferedReader.
Ex:
import java.io.*;
class InputExample
{
public static void main(String args[]) throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
30 | P a g
int x;
e
x= Integer.parseInt(br.readLine());
System.out.println(“x value = “ + x);
}
}
Mathematical functions such as cos, sqrt, log etc. are frequently used in analysis of
real life problems. Java supports these basic math functions through Math class defined in
the java.lang package. These functions should be used as follows.
Math.function_name();
The various functions available with the Math class are listed below.
Function Action
In other words, the control statements are used to control the cursor in a program
according to the condition or according to the requirement in a loop. Further we can say,
changing the order of flow controls, these are required. There are mainly three types of
control statements or flow controls. These are illustrated as below:
1. Branching
2. Looping
3. Jumping
Branching statements
It is also called decision making statement. These are used when a condition arises in
32 | P a g
a statement. The various branching statements used are as:
e
1. If statement
2. Switch statement
3. Conditional operator
If statement:
The if statement is a powerful decision making statement which can handle a single
condition or group of statements. These have either true or false action. There are mainly
four types of if statements used in java are as:
1. Simple if statement
2. If else statement
3. Nested if statement
4. Else – if statement or multi condition if statement.
Simple if statement:
When only one condition occurs in a statement then simple if statement is used
having one block. The general syntax of
simple if statement is:
if (condition)
{
True statement block;
}
Statement –x;
If – else statement:
This statement also has a single condition with two different blocks. One is true block
and the other is false block. The general syntax is used as:
if (condition)
{
True statement block;
}
else
{
False statement block;
}
Statement –x;
When an if statement occurs within another if statement, then such type of statement
is called nested if statement. The general syntax of this statement is as:
if(condition1)
{
if(condition2)
St – 1;
else
St – 2;
}
else
{
if (condition3)
St – 3;
else
St – 4;
}
Statement – x;
First of all condition1 will be executed. If it is true, then further condition2 will be checked. If
condition2 is true, then st-1 will be executed and after execution of st-1, statement-x will be
executed. But if condition2 is false, then st-2 is executed. Similarly if condition1 is false, the
else block of condition1 is executed, in that first condition3 is executed, if it is true then st-3
otherwise st-4 is executed. In any case, after the execution of block, the statement-x is
followed.
In a complex problem, no. of conditions arise in a sequence, then we can use ladder if
or else if statement to solve the problem in a simple manner. In this statement 1 st condition
will be checked, if it is true then action will be taken, otherwise further next condition will be
checked and this process will continue till the end of the conditions. The general syntax is as:
If(condition1)
St-1;
Else if (condition2)
St-2;
Else if (condition3)
St-3;
.
.
.
.
Else if (condition n)
St – n;
Else
False statement;
Statement-x;
34 | P a g
e
Switch statement:
When no. of conditions occurs in a problem and it is very difficult to solve such type of
complex problem with the help of ladder if statement. Then there is need of such type of
statement which should have different alternatives or different cases to solve the problem in
simple and easy way. For this purpose switch statement is used. It is also called case
statement because it has different cases and different blocks. It is also called multi decision
statement having multiple blocks. The float type of values is not accepted in switch
statements. The general syntax of the switch statement is:
switch(e or v)
{
case value1: block1;
break;
case value2: block2;
break;
…………………….
case value n: block n;
break;
default: block n+1;
}
Statement –x;
35 | P a g
e
Conditional operator (?:):
Here first of all expr1 is computed, which is a conditional expression. If expr1 is true,
then expr2 will be executed. But if expr1 is false, then expr3 will be executed. Note that
expr2 and expr3 are either a single constant value or a single variable or an arithmetic
expression. For example, below is an if statement having a and b two variables as:
a=10; b=5;
if (a>b)
c=a-b;
else
c=b-a;
The above if statement can be write by using the conditional operator in a single statement
as:
36 | P a g
e
Decision Making and Looping
Q. Explain different looping statements available in Java?
Looping statement:
While statement:
Do statement or Do-loop:
do
{
block of statements;
} while (condition); 37 | P a g
statement-x; e
It a-looping statement, which repeat again and again till it satisfies the defined
condition. It is one step loop, which initialize, check the condition and increment decrement
the step in the loop in a single statement. The general syntax is as:
It is also entry controlled loop, where first condition is checked and the body of the
loop be executed. In this case, first we initialize the value, then in the loop we apply the
condition and further we increment or decrement the loop according to requirement. After
execution or completion of the body of the loop when the condition becomes false, the
statement-x will be executed.
When a for statement is executed within another for statement, then it is called
nested for statement. We can apply number of nested for statements. The general syntax is:
For one value of outer loop, inner loop will repeat n times. So inner loop will be
completed first and then outer loop will be completed. After completion of inner and outer
loop, statement-x will be executed.
The enhanced for loop, also called for each loop, is an extended language future
introduced with the J2SE 5.0. This for loop used to retrieve the array of elements efficiently
rather than using array indexes. The syntax is as follows:
for ( type identifier : expression)
{
Statements;
}
Where type represents the data type or object used; identifier refers to the name of a
variable; and expression is an array.
Consider the following the example
int a[3]={10, 20, 30};
for (int k=0;k<3;k++)
{ System.out.println(a[k]); }
Which is equivalent to the following code:
int array[3]={10, 20, 30};
for (int k:array)
{
System.out.println(k); 38 | P a g
} e
Q) What are the Jumping Statements:
Sometimes, when executing a loop it becomes want to skip a part of the loop or to
leave the loop as soon as a certain condition occurs. For example, consider the case of
searching for a particular number in a list containing, say, 100 numbers. A program loop
written for reading and testing the numbers a 100 times must be terminated as soon as the
desire number is found. Java permits a jump from one statement to the end or beginning of
a loop as well as a jump out of a loop.
while (……………)
{
……
if(condition)
break;
……
……
}
……
……
When the break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop. When the loops
are nested, the break would only exit from the loop containing it. That is, the break will exit
only a single loop.
Sk ip p in g a p a rt of a L oo p
During the loop operations, it may be necessary to skip a part of the body of the loop
under certain conditions. Unlike the break which causes the loop termination, the continue,
as the name implies, cause the loop to be continued with the next iteration (repetition) after
skipping any statement in between.
The continue statement is written simply as continue; .
while (……………)
{
……
if(condition)
continue;
……
……
}
La b e le d b r e ak an d c on t in u e
In Java, we can give a label to a block of statements. A label is any valid Java variable
name. To give a label to a loop, place it before the loop with a colon at the end.
label:
statement;
……
39 | P a g
……
e
……
goto label;
The label: can be anywhere in the program either before or after the goto label;
statement. During running of a program when a statement like goto label; is met, the flow
of control will jump to the statement immediately following the label;. This happens
unconditionally.
E.g:
outer: for(int m=1; m<11; m++)
{
for(int n=1; n<11; n++)
{
System.out.print(“ ” + m*n);
if(n == m)
continue outer;
}
}
Here, the continue statement terminates the inner loop when n=m and continues
with the next iteration of the outer loop (counting m).
E.g:
loop1: for(int i=0; i<10; i++)
{
loop2: while(x<100)
{
Y = i*x;
if(y>500)
break loop1;
………………
………………
Jumping out
}
……………… of both loops
}
………………
Here, the continue statement terminates the inner loop when n=m and continues
with the next iteration of the outer loop (counting m).
40 | P a g
e
Q) Explain about stream?
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
An array is a group of contiguous or related data items that share a common name. A
particular value is indicated by the number called index or subscript in brackets after the
array name.
A list of items given by one name using only one subscript and such variable is called
one-dimensional array.
Ex: if we want to represent set of 5 numbers say (10, 20, 30, 40, 50) by an array variable
num, then we may create the variable num as follows.
points
nowhere
int num[];
num [0]
num = new int [5];
num [1]
num [2]
num[3]
num [4]
41 | P a g
This would cause the array num to store the values as shown below. The elements may be
e
used in programs just like any other variable in Java.
num[0]=10, num[1]=20, num[2]=30, num[3]=40m and num[4]=50.
Like a variable, arrays must be declared and created in the memory before they are used.
The creation of array involves the following steps.
1. Declaration of Array
2. Creation of Array
3. Putting values into the memory locations.
Declaration of Array:
Creation of Array:
After declaring the array, we need to create it in the memory. Java allows you to
create array using new operator as shown below.
Initialization of Array:
The final step is to put values into the array created. This process is known as
initialization.
Syntax:
ex: num[1]=20;
Which stores the values as a[0]=10, a[1]=20, a[2]=30, a[3]=40, and a[4]=50.
In Java, the array index starts with 0 and ends with a value one less than the size
specified. In Java trying to access an array beyond its boundaries, it will generate an error
message.
Array Length:
In Java, all arrays store the allocated size in a variable named length. We can obtain
the length of the array a using a.length.
This information is useful in the manipulation of arrays when their sizes are not known.
class Testarray2
{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
Java supports two dimensional arrays, the array consisting of two subscripts which
the first one represents the rows and the second subscript represents column to represent a
table of items. The two dimensional arrays are created in the following manner.
Like one-dimensional arrays, two dimensional arrays may be initialized by following their
declaration with a list of initial values as follows.
The above declaration automatically initializes the elements into 3 rows and 2 columns in
each row starting index with 0 for row and column.
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
These statements create a two-dimensional array as having different lengths for each row as
shown in below:
x[0] x[0][1]
x[1] x[1][3]
x[2] x[2][2]
Strings
String manipulating is the most common part of many Java programs. Strings
represent the sequence of characters. The easiest way to represent a sequence of characters
in Java is using a character array.
Ex:
char name[]= new char[3];
name[0] = ‘s’;
name[1] = ‘a’;
name[2] = ‘i’;
In Java, strings are class objects and implemented using two classes, String and
StringBuffer; both are available in java.lang package. A Java string is an instantiated object
of the String class. A Java string is not a character array and is not terminated by NULL
character. In Java strings are declared and created as follows.
String <string_name>;
String_name= new String (“string constant”);
Ex:
String name;
name = new String (“yugandhar”);
or
String name = new String (“yugandhar”);
Note: The contents of the string instance cannot be changed after it has been 45 created.
|P ag
However, a variable declared as a string reference can be changed to point to another
e string
object at any time.
We can copy the character array into the string object, in that way also we can create a
string object.
Ex:
char name[]={‘s’,’a’,’I’,’r’,’a’,’m’);
Now that String object ‘S’ contains he string ‘sairam’. You can copy the particular
character sequence from the array into the String object in the following method of
declaration.
Here, starting from 3rd character, a total of three characters are copied into the String S.
String Arrays:
We can also create and use arrays that contain strings. The statement
Will creae an nameArray of size 5 to hold 5 string constants. We can assign the strings to the
array by using the indexes.
String Methods:
The String class defines a number of methods that allow us to accomplish a variety of
string manipulation tasks. Some most commonly used are as follows.
Function Action
A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In
Java, String objects are immutable. Immutable simply means unmodifiable or
unchangeable.
Once String object is created its data or state can't be changed but a new String object is
created.
Let's try to understand the concept of immutability by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a
new object is created with Sachin Tendulkar. That is why String is known as immutable.
47 | P a g
e
As you can see in the above figure that two objects are created but s reference variable
still refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.
For example:
Testimmutablestring1.java
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
StringBuffer Class:
StringBuffer is a peer (look closely) class of String. The difference between String and
StringBuffer classes is, the String creates the strings of fixed length, StringBuffer48creates
|P ag
strings of flexible length that can be modified in terms of both content and length.eWe can
insert characters and substrings in middle of a string (or) append another string to the end.
Commonly used StringBuffer methods are as follows.
Function Action
2) String is slow and consumes more memory StringBuffer is fast and consumes less
when we concatenate too many strings memory when we concatenate t strings.
because every time it creates new instance.
3) String class overrides the equals() method StringBuffer class doesn't override the
of Object class. So you can compare the equals() method of Object class.
contents of two strings by equals() method.
5) String class uses String constant pool. StringBuffer uses Heap memory
49 | P a g
e
Q) Explain StringTokenizer class
The java.util.StringTokenizer class allows an application to break a string into tokens.
This class is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code.
Its methods do not distinguish among identifiers, numbers, and quoted strings.
Class declaration
Following is the declaration for java.util.StringTokenizer class:
public class StringTokenizer
extends Object
implements Enumeration<Object>
Class constructors
S.N. Constructor & Description
StringTokenizer(String str)
1
This constructor a string tokenizer for the specified string.
Class methods
S.N. Method & Description
int countTokens()
1 This method calculates the number of times that this tokenizer's nextToken
method can be called before it generates an exception.
boolean hasMoreElements()
2
This method returns the same value as the hasMoreTokens method.
boolean hasMoreTokens()
3 This method tests if there are more tokens available from this tokenizer's
string.
Object nextElement()
4 This method returns the same value as the nextToken method, except that its
declared return value is Object rather than String. 50 | P a g
e
String nextToken()
5
This method returns the next token from this string tokenizer.
package com.myjava.stokenizerr;
import java.util.StringTokenizer;
Example Output
This
program
gives
sample
code
for
String
Tokenizer
51 | P a g
e
Wrapper Classes
A wrapper class is a class whose object contains a primitive data type. When we
create an object to a wrapper class, it contains a field and in this field we can store a
primitive data value. In other words, we can contain a primitive value to a wrapper class
object.
Wrapper classes convert primitive data types into objects and this is needed on
internal to communicate between two applications.
Primitive data types may be converted into object types by using the wrapper classes
contained in java.lang package. The wrapper classes have a number of unique methods for
handling primitive data types and objects. They are listed in the following table.
52 | P a g
e
Converting numbers to strings using toString() method:
53 | P a g
e
Classes, Objects and Methods
Defining a Class:
A class is a user defined data type that works to define its properties and methods.
Once the class type has been defined, we can create variables of that type using declarations
that are similar to the basic types declarations. These variables are called as instances of
classes, which are the actual objects. The basic form of a class definition is:
class <class_name>
{
Variable declarations;
Methods declarations;
}
Adding variables:
Data is encapsulated in a class by placing data fields inside the body of the class
definition. These variables are called instance variables because; they are created when
ever an object of the class is created. We can declare the instance variables as the same way
as we declare local variables.
Ex:
class Rect
{
int length;
int breadth;
}
The class Rect contains two integer type instance variables length and breadth.
Note: these variables are only declared and therefore no storage space has been created in
the memory.
Instance variables are also known as data members, member variables, properties or
fields.
Adding Methods:
A class with only data fields has no life. The objects created by such a class can not
respond to any messages. We must therefore add methods that are necessary for
maintaining the data contained in the class. Methods are declared inside the body of the
class but immediately after the declaration of instance variables. The general form of a
method declaration is:
The return_type specifies the type of the value the method would return. This could be a
simple data type such as int or as well as any class type. It could even be void, 54 |ifPthe
ag
function returns nothing. e
The method name is a valid identifier. The parameter list contains variable names and
types of all the values we want to give to the methods as input. N the case where no input,
data are required, the declaration must retain empty parenthesis.
Ex:
class Rectangle
{
int length;
int width;
void getData(int x, int y)
{
length = x;
width = y;
}
int rectArea( )
{
int area = length*width;
return(area);
}
}
Creating Objects:
An object in Java is essentially a block of memory that contains space to all the
instance variables. Objects in Java are created using the new operator. The new operator
creates objects of the specified class and returns a reference to that object.
Ex:
Rectangle rect1; // declare
rect1 = new Rectangle (); // instantiate
The first statement declares a variable to hold the object reference. And second one
actually assigns the object reference to the variable. The variable rect1 is now an object of
the Rectangle class. Both statements can be combined into one as shown below.
It is important to understand that each object has its own copy of the instance
variables of its class. This means that any changes to the variables of one object have no
effect on the variables of another object. It is also possible to create two or more references
to the same object.
Ex:
Rectangle rect1 = new Rectangle ();
Rectangle rect2 = rect1;
The class code along with method code is stored in method area of the JVM. When an
object is created, the memory is allocated on Heap. After creation of an object, JVM produces
a unique reference number for the object from the memory address of the object. This
reference number is also called Hash Code number.
55 | Pand
Since we are outside of the class, we cannot access the instance variables ag
e
methods directly, to do this, we must use the concerned objects and the dot operator as
shown below.
Object_name . variable_name
Object_name . method_name(arg_list);
Here object_name is the name of the object, variable_name is the name of the
instance variable inside the object that we wish to access, method_name is the method that
we wish to call and arg_list is the list of actual values separated by comma passing as input
to the method.
Example program:
class Rectangle
{
int length;
int width;
void getData(int x, int y)
{
length = x;
width = y;
}
int rectArea( )
{
int area = length*width;
return(area);
}
}
class RectArea
{
public static void main(String args[])
{
Rectangle rect1 = new Rectangle();
r.getdata(15,10);
int area = rect1.rectArea();
System.out.println("Area of rectangle = " + area);}}
Constructors
A constructor is similar to a method that is used to initialize the instance variables of
the objects of a class. The only purpose of a constructor is to initialize the instance variables.
A constructor has the following characteristics.
Parameterized Constructor:
Copy constructor:
A copy constructor is used to declare and initialize an object with the values of
another object.
Ex:
class Deposit
{
int p,t;
double r;
double interest;
Deposit(int a,int b,int c=0.12)
{
p=a;
t=b;
r=c; 58 | P a g
}
e
}
Deposit d=new Deposit(1000,2);
Here the two values 1000 and 2 for variables p and t are only passed to constructor.
The third argument is assigned the default value i.e. 0.12 for r instance variable.
Ex:
class Test
{
int a;
Test(int i)
{
a=i;
}
Test incr()
{
Test temp=new Test(10);
return temp;
}
}
class TestObj
{ 59 | P a g
public static void main(String args[]) e
{
Test obj1= new Test(2);
Test obj2;
obj2=obj1.incr();
System.out.println("obj 1 = " + obj1.a);
System.out.println("obj 2 = " + obj2.a);
}
}
A method can be called by using only its name by another function of the same class
is known as nesting of functions.
Ex:
class Nesting
{
int m,n;
Nesting(int x,int y)
{
m=x;
n=y;
}
int largest()
{
if(m>=n)
return m;
else
return n;
}
void display()
{
int l=largest();
System.out.println("largest value = " + l);
}
}
class NestingTest
{
public static void main(String args[])
{
Nesting n1=new Nesting(50,40);
n1.display();
}
}
Call by value:
class Test
{
void math(int i,int j)
{
i*=2;
j/=2;
}
}
class CallByValue
{
public static void main(String args[])
60 | P a g
{
e
Test ob=new Test();
int a=15,b=20;
System.out.println("before a= " + a + " b= " +b);
ob.math(a,b);
System.out.println("after a= " + a + " b= " +b);
}
}
Call by reference:
class Test
{
int a,b;
Test(int x,int y)
{
a=x;
b=y;
}
void math(Test x)
{
x.a*=2;
x.b/=2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob=new Test(10,20);
System.out.println("before a= "+ ob.a +" b="+ ob.b);
ob.math(ob);
System.out.println("after a= "+ ob.a +" b="+ ob.b);
}
}
Static Members
The variables and methods declared in the class are referred as instance members
because a new copy of each of them is created for each object.
If we want to create a member that is common to all the objects and accessed
without a particular object, those are declared using static keyword.
The members that are declared as static are referred as static members, and the
static variables, static methods are also referred as class variables, and class methods.
Class_name.method_name();
Static Block:
static
{
Statements;
}
JVM executes a static block on a highest priority bases. This means JVM first goes to static
block even before it looks for the main() method in the program.
Ex:
class Test
{
static
{
System.out.println("static block");
}
public static void main(String args[])
{
System.out.println("main block");
}
}
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We can
also easily modify code using methods. In this section, we will learn what is a method in
Java, types of methods, method declaration, and how to call a method in Java.
The most important method in Java is the main() method. If you want to read more about the
main() method,
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as62 we| P a g
have shown in the following figure. e
Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
63 |the
Pag
parentheses blank. e
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same class, it is
known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call
any of the predefined methods in our program, a series of codes related to the corresponding
method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max() method
is a method of the Math class that returns the greater of two numbers.
link and see the max() method signature, we find the following:
In the above method signature, we see that the method signature has access specifier public, non-
access modifier static, return type int, method name max(), parameter list (int a, int b). In the
above example, instead of defining the method, we have just invoked the method. This is the
advantage of a predefined method. It makes programming less complicated.
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
We have defined the above method named findevenodd(). It has a parameter num of type int. The
method does not return any value that's why we have used void. The method body contains the
steps to check the number is even or odd. If the number is even, it prints the number is even, else
prints the number is odd.
Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the called
method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[]) 66 | P a g
{ e
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output 1:
Output 2:
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers.
It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value
of a and b, respectively. Therefore, the method adds the value of a and b and store it in the
variable s and returns the sum.
Addition.java
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance method.
It is invoked by using the class name. The best example of a static method is the main() method.
Display.java
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the private
field.
Example
public int getId()
{ 69 | P a g
return Id; e
}
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data type
that depends on the field. It is used to set the value of the private field.
Example
public void setRoll(int roll)
{
this.roll = roll;
}
Example of accessor and mutator method
Student.java
public class Student
{
private int roll;
private String name;
public int getRoll() //accessor method
{
return roll;
}
public void setRoll(int roll) //mutator method
{
this.roll = roll;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void display()
{
System.out.println("Roll no.: "+roll);
System.out.println("Student name: "+name);
} 70 | P a g
} e
Abstract Method
The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It
means the class itself must be abstract if it has abstract method. To create an abstract method, we
use the keyword abstract.
Syntax
abstract void method_name();
A Factory Pattern or Factory Method Pattern says that just define an interface or
abstract class for creating an object but let the subclasses decide which class to
instantiate. In other words, subclasses are responsible to create the instance of the class.
71 | P a g
e
The Factory Method Pattern is also known as Virtual Constructor.
Advantage of Factory Design Pattern
o Factory Method Pattern allows the sub-classes to choose the type of objects to create.
o It promotes the loose-coupling by eliminating the need to bind application-specific
classes into the code. That means the code interacts solely with the resultant interface or
abstract class, so that it will work with any classes that implement that interface or that
extends that abstract class.
“this” is a keyword that refers to the object of the class where it is used. In other words
‘this’ refers to the object of the present class. Essentially, we write instance variable,
constructors and methods in a class and these members are referenced by ‘this’. When an
object is created to a class, a default reference is also created internally to the object. This
default reference is nothing but this. So this can refer to all the things of present object.
Ex:
class Sample
{
private int x;
Sample()
{
this(55); // present class para constructor and sent 55.
this.access();
}
Sample(int x)
{
this.x=x; // refer present class instance variable
}
void access()
{
system.out.println("x = " + x);
}
}
class ThisDemo
{
public static void main(String args[])
{
Sample s=new Sample();
}
}
Explanation:
Here 2 things will happen. First Sample class object is created and then its default
72 | P a g
constructor is executed. Hence the code this (55) and this.access () is executed.
e
In the first statement, present class (Sample) parameter constructor is called and 55 is
passed to it. This value is present class instance variable as this.x=x; here this.x represent
present class instance variable x and in the statement x is local variable to the constructor.
Similarly this.access () call to the present access() method which displays the x value as 55
as output.
Polymorphism in Java can be achieved in two ways i.e., method overloading and method
overriding.
Polymorphism variables?
During the execution of a program, a polymorphic variable is defined as a variable that can hold
values of several types. In other words, variables having different values under different
conditions or variables holding different values at the execution time are called Polymorphism
variables.
We can create methods that have the same name but different parameters list and
different data types. This is called method overloading. That is each parameter list should be
unique.
Method overloading is used when objects are required to perform similar tasks but
using different input parameters. When we call a method in an object, java matches up the
method name first and the number and type of arguments to execute, this process is known
as polymorphism.
To create an overloaded method, several different method definitions in the class all
have the same name but with different parameter lists. Hence ,this is also called runtime
polymorphism or dynamic binding
Whenever you call this method the method body will be bound with the method call based
73 | P aong
the parameters. e
Overloading private methods
Yes, we can overload private methods in Java but, you can access these from the same class.
Ex:
class Operation
{
int add(int x,int y)
{
return x+y;
}
float add(float x,float y)
{
return x+y;
}
}
class Arith
{
public static void main(String args[])
{
Operation obj=new Operation();
int a=obj.add(10,20);
float b=obj.add(1.2f, 2.3f);
System.out.println("addition of integers = " + a);
System.out.println("addition of floats = " + b);
}
}
Known as static binding or early binding. Known as dynamic binding or late binding.
In the following example, we have performed the narrowing type casting two
times. First, we have converted the double type into long data type after that
long data type is converted into int type.
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166Q
76 | P a g
e
Q) Explain casting referenced data types?
You can cast the reference(object) of one (class) type to other
widening in Referenced data types:
we take class One as super class and class Two is its sub class. We do widening
by using super class reference to refer to sub class object. In this case ,we
convert the sub class object type as super class type.
Example:
class One
{
void show1()
{
System.out.println(“super class”);
}
}
class Two extends One
{
void show2()
{
System.out.println(“sub class”);
}
class pyk
{
public static void main(String args[])
{
One x;
X=(One) new Two();
x.show1();
}
}
Narrowing in Referenced data types:
Converting super class type into sub class type.
class One
{
void show1()
{
System.out.println(“super class”);
}
}
class Two extends One
{
void show2()
{
System.out.println(“sub class”);
}
class pyk
{
public static void main(String args[])
{ 77 | P a g
e
Two x;
X=(Two) new One();
x.show1();
}
}
hashCode() Method.-> is a Java Integer class method which returns the hash
code for the given inputs.
equals(Object obj) Method.-> compares two strings, and returns true if the
strings are equal, and false if not
clone() method.-> in Java ... Object cloning refers to the creation of an exact
copy of an object. It creates a new instance of the class
Some methods support vector classes can be used to manipulate the vectors
created.
81 | P a g
e
INHERITANCE
Inheritance is a process by which object of one class acquire properties of object
of another class. The concept for inheritance provides the idea of reusability
that means we add additional features to an existing class without modifying it.
This is possible by developing new class from existing one.
The mechanism of deriving a new class from an old one is called Inheritance.
The old class is known as base class or super class or parent class and the new
class is called derived class or subclass or child class. We have combined the
features of both the classes in the derived class.
Inheritance allows the subclass to inherit all the variables and methods of their
parent classes. Inheritance may take different forms.
1. Single Inheritance.(only one super class)
2. Multiple Inheritance.(several super classes)
3. Multi level Inheritance.(derived from a derived class)
4. Hierarchical Inheritance.(one super class, many subclasses)
The keyword extends signifies that the properties of the super class are
extended to the subclass. The subclass will now contain its own variables and
methods as well as those of the super class. 82 | P a g
e
Single Inheritance:
A derived class with only one base class is called single inheritance.
In the above example class B is derived from class A. The class A is called as
Base class and class B is called as Derived class.
class A
{
------
------
}
class B extends A
{
------
------
}
Multilevel Inheritance:
The mechanism of deriving a new class from another derived class is
known as Multi level Inheritance.
In the example, class C is derived from the class B which is derived from the
class A.
class A
{
------
------
}
class B extends A
{
------
------
}
class C extends B
{
------
------
}
Hierarchical Inheritance:
One class may be inherited by more than one class is called hierarchical
inheritance.
In the example, class B, class C, and class D are all inherited from the class A.
class A
{
------
------
}
class B extends A
{
------
------
83 | P a g
} e
class C extends A
{
------
------
}
class D extends A
{
------
------
}
Multiple Inheritance:
The class derived with several base classes is called multiple inheritance. In the
example, class C is derived from the class A and class B. the classes A and B
are the base classes for class C.
Java does not directly implement multiple inheritance. However the concept is
implemented by using secondary inheritance path in the form of Interfaces.
Hybrid Inheritance:
This is the combination of both Multiple and Multi Level inheritances. Both
forms of inheritance features are included. Java does not support this type of
inheritance also.
Q. Write a short note on “super” keyword?
A subclass constructor is used to construct the instance variables of both the
subclass and the super class. The subclass constructor uses the keyword super
to invoke to constructor of the base class. The following conditions should be
satisfied.
1. super may only be used within a subclass constructor method.
2. The call to base class constructor must appear as the first statement
within the derived class constructor.
3. The parameters in the super call must match the order and type in the
super class.
Q. Explain Method Overriding concept in Inheritance?
When a function defining in the subclass by the same name, same arguments
and same return type as a method in the super class, this sort of function
definition in the derived class which is already defined in the base class is
known as Overriding.
When we want an object to respond to the same method but have different
behavior when the method is called, we should override the method defined in
the super class. Then when that method is called, the method defined in the
subclass is invoked and execute instead of the one in the super class. This is
known as overriding.
class Base
{
int x;
Base(int a) 84 | P a g
{ e
x=a;
}
void display()
{
system.out.println("x = " +x);
}
}
class Derived extends Base
{
int y;
Derived(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
system.out.println("x = " +x);
system.out.println("y = " +y);
}
}
class Overrid
{
public static void main(String args[])
{
Derived d1=new Derived(10,20);
d1.display();
}
}
Explain Access specifiers or visibility modes in java ?
For controlling the access to the various members of a class we use access
specifiers. Access specifiers determine how a member of the class can be
accessed. Java supplies a rich set of access specifiers, they are:
1. public
2. private
3. protected
4. default
Public:
When a member is specified by the public specifier, then that member can
be access by any other code i.e. from any other class or from any other package
( A package is nothing but a group of classes). We can access this member in
the same class also.
Private:
When the private specifier assigned to a member, then tat member can be
accessed by only the member of that class, it is accessed only within the class.
We cannot access the private data outside the class, with the class objects also.
Protected:
This type of members is accessed by all the members within the package
and classes in other package that are subclasses for the class. Generally
85 |they
Pag
are useful when inheritance involved. e
Default:
If no specifier is specified, then by default it taken as default specifier. Default
specifier acts as a public with in its own package, but cannot accessed outside
of its package. (default is not a keyword).
Object creation is not possible for abstract classes. (Since the class is
incomplete). Reference creation is possible abstract class reference can refer
their subclass objects.
Eg: Fan Demo
abstract class Fan
{
//every fan have a bearing (common feature)
public void bearing()
{
System.out.println("Every fan uses the ball bearing mechanism");
}
//fans are two types cealing fan and table fan.
abstract public void fantype();
}
class Cealing extends Fan
{
public void fantype()
{
Sytem.out.println("Fan type is cealing");
}
}
class Table extends Fan
{
public void fantype()
{
System.out.println("Fan type is table");
}
}
class FanDemo
{
public static void main(String args[])
{
Cealing s=new Cealing();
Table t=new Table(); 87 | P a g
e
Fan f;
f=t;
f.bearing();
f.fantype();
}
}
Eg:
abstract class Figure
{
abstract double area(int x, int y);
}
class Rectangle extends Figure
{
public double area(int a,int b)
{
return a*b;
}
}
class Triangle extends Figure
{
public double area(int a,int b)
{
return (a*b/2);
}
}
class Abstract1
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
Triangle r=new Triangle();
Figure ref;
Figure ref1;
ref=r;
/*abstract class reference(here reference is of) can refer all their implementation
class objects */
System.out.println(ref1.area(3,4));
}
}
INTERFACES
Interface is a mechanism where we can specify role of the class. That is what a
class must do but not how to do. Interfaces are syntactically similar to classes
but all the methods are declared without body. To declaring the interface
“Implements” is the keyword.
Once an interface is defined then any number of classes can implement this
interface. One class implements so many no. of interfaces to implement an
interface; it must define the complete set of methods declared in the interface as
shown below. 88 | P a g
e
interface iface1
{
void method1();
void method2();
}
class Demo123 implements iface1
{
public void method1()
{
some implementation code
}
public void method2()
{
some implementation code
}
}
By default all the methods in interface are public abstract. By default all the
variables in interface are public static final. The methods in interface that are
implemented in our class must be declared as public and also the type
signature must match exactly with the type signature specified in the interface
declaration.
Object creation is not possible for interfaces (it is incomplete that’s why).
Reference creation is possible. An interface reference variable can refer all their
implementation class objects.
If a class implements interface but does not fully implements all the methods
then that class must be declared as abstract.
In interface all the variables are by default they are public static final. Where are
in abstract classes we have to declare explicitly.
In interface all the methods are comes under public and abstract, where as in
abstract classes we explicitly declare the methods as abstract.
For declaring interfaces we use a keyword called interface where as for abstract
92 | P a g
classes we use keyword abstract. e
For writing code for the uncompleted method we have to create a class and give
the code in the class. In this, we use keyword “implements” as follows.
class <class_name> implements <interface_name>
An abstract class can contain the concrete methods (i.e. methods having body).
Whereas interfaces must contain only abstract methods. But in the interfaces
all the methods are abstract.
PACKAGES
A package is a container that holds a collection of an interface or a package is
an association of several classes and interfaces that are grouped together in a
directory on disk are said to be packages.
Benefits:
1. The classes contained in the packages of other program can be easily
reused.
2. In packages classes are unique. They are compares with classes in other
packages. i.e. two classes in two different packages can have the same
name that may refer by their fully qualified name, comprising the package
name and the class name.
3. Packages provide a way to hide classes. They prevent other programs or
packages from accessing classes that are meant for internal use only.
4. Packages can also provide a way for separating design from coding.
Java API provides a large number of classes grouped into different packages
according to functionality. Most of the time, we use the packages available with
the Java API.
Java
Example:
package sai;
public class Ram
{
public void show()
{
System.out.println("Hello");
}
}
Complie the file.(javac –d . Ram.java) 94 | P a g
e
import sai.Ram;
class Pack
{
public static void main(String args[])
{
Ram ob=new Ram();
ob.show();
}
}
javac pack.java
java pack
Accessing a package:
We used a import statement when they are many references to a particular
package.
Syntax: import package1.[package2][.package3].class_name;
Here package1 is the name of the top level of the package, package2 is the name
of package that is inside packag1 and so on. Finally the explicit (open) class
name is specified. Note that the statement must be end with semicolon.
import package_name.*;
Here the * indicates that the compiler will search this entire package hierarchy
when it encountered the class name.
Adding a class to a package:
package p1;
public class A
{
}
The package p1 contain one public class be name A. suppose we want to add
another class B to this package, the following steps are followed.
1. Define the class and make is public
2. Place the package statements.
public p1;
public class B
{
}
3. Store this class in B.java file under the directory p1.
4. Compile B.java file, this will create a B.class file and place it in the
directory p1.
96 | P a g
e
EXCEPTION HANDLING
A developer may also commit several errors while designing the project or
developing the code. These errors are also called "BUGS" and the process of
removing them is called "DEBUGGING"
There are basically three types of errors in the java program:
1. Compile-time errors
2. Run-time errors
3. Logical errors
Compile-time errors:
These errors are syntactical errors found in the code, due to which a
program fails to compile. For example, for getting a semicolon at the end of the
statement, or writing a statement without a proper syntax will result in compile-
time error.
Run-time errors:
These errors are representing inefficiency of the compiler system to
execute a particular statement. The errors which doesn't understand by the
compiler that errors displays only at the time of runtime ,these errors are
detected by the JVM. For example if we define the main() without defining string
args[] at run time it displays error.
Logical errors:
If we define the program with logically wrong that may cause to arise
Logical errors. These errors also happened at run time. For example if we define
the following statement sal=sal+sal*15/100,it may cause the wrong output.
Actually we should write as sal=sal+(sal*15/100).this is correct statement.
These type of errors are called Logical errors. These errors are not identified by
the compiler and not by the JVM.
Q. What is Error and Exception?
Programs executes successfully with wrong outputs known as Error.
Statements which may cause to terminate an application known as Exception.
Q. What is the importance of Exception Handling?
Or mechanism of Exception handling?
To avoid the abnormal termination in a program we use Exception
handlers that are try, catch, throw, throws, finally. Using these types we can
handle the exceptions. This mechanism is called Exception Handling. Java
supports Exception handling.
If the program has any runtime error JVM propagates an Exception
during execution. This exception is in the form of object. These Exception
classes are defined in java.lang package. If we did not handle the propagated
Exceptional objects immediately JVM terminates the application by displaying
the proper message of the raised exception.
Types of Java defined Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions
Checked Exceptions:
Exceptions which are checked at compilation time known as Checked
Exceptions.
97 | P a g
Unchecked Exceptions: e
Exceptions which are not checked at compilation time which may rise in
runtime by JVM known as Unchecked Exceptions.
Ex:
ArrayIndexOutOfBoundsException,
ArithmeticException,
NumberFormatException etc.
Throws
exception
object
Java uses a keyword try to preface a block of code that is likely to cause an
error condition and “throw” an exception. A catch block defined by the keyword
catch “catches” the exception “thrown” by the try block and handles it
appropriately. The catch block is added immediately after the try block. The
following example illustrates the use of simple try and catch statements.
Syntax:
try
{
<statements> 98 | P a g
} e
catch(<exception_type> <exception_object>)
{
<statements>
}
..
finally
{
<statements>
}
Ex:
catch(ArithmeticException e)
{
System.err.println("Zero divide error");
}
catch(NumberFormatException e1)
{
System.err.println("invalid type");
}
finally
{System.out.println("After exception proceding block");}
99 | P a g
e
Q) Different types of exceptions available in java (OR) Built –in Exceptions
ArithmeticException:
ex: Division by 0(zero)
IOException:
Which are frequently occurred at input and output operation time.
ArrayIndexOutOfBoundsException:
Occurs when you are trying to access the element whose index is greater
than the length of the given array.
StringIndexOutOfBoundsException:
Same as array index out of bounds.
NullPointerException:
Occurs when you are trying to perform operations on the values not yet
initialized.
FileNotFoundException:
If you are trying to access the file which is not available.
NumberFormatException:
Occurs when you are trying to assign values to the variable which is of
different types.
ClassNotFoundException:
If the accessing class is not available in the current directory.
NosuchMethodException:
Occurs when you call the method which is not available in the current class
StackOverFlowException:
Caused when the system runs out of stack space
OutOfMemoryException:
Caused when there's not enough memory to allocate a new object
Q. What is Throwable?
Throwable is a super class for all errors and the exception classes that
represent all errors and exceptions which may occur in java.
Q. What is the super class for all exceptions?
Exception is the super class for all exceptions in JAVA.
Q. What is try, catch blocks?
try:
try is a monitoring block used to monitor the Unchecked Exceptions. Once it
monitors it propagates the exception to its related handling block.
Syntax:
try
{
//exceptional statements to monitor
}
Catch:
It is the handling block for the raised exceptions. It should be followed by try.
Syntax:
catch
{ 100 | P a g
//handling statements e
}
MULTIPLE CATCH STATEMENTS
It is possible to have more than one catch statements in the catch block as
illustrated below:
.. .. .. .. ..
.. .. .. .. ..
try
{
statement(s); //generates an exception
}
catch(Exception-type-1 e)
{
statement(s); //processes an exception type 1
}
catch(Exception-type-2 e)
{
statement(s); //processes an exception type 2
}
..
..
catch(Exception-type-N e)
{
statement(s); //processes an exception type N
}
.. .. .. .. ..
.. .. .. .. ..
105 | P a g
e
APPLETS
Q. What are the differences between Applets and Standalone application
program?
Although both the Applets and standalone application are java programs,
these are not full feature application programs. It is designed for Internet. There
are certain limitations and restrictions in their design.
Applets don't use the main method for initiating the execution of the code.
Applets when loaded automatically called certain methods of the Applet
class to start and execute the code.
Applet cannot run independently but they run from inside a webpage
using HTML Tags.
Applets cannot read from or write to the files in the local computer.
Applets cannot communicate with other servers on the network.
Applet cannot run program from the local computer.
Q. Explain Applet lifecycle?
Every java Applet inherits a set of default behaviors from the applet class.
As a result when an Applet is loaded it undergoes a series of changes in its state
as shown in the figure below.
Initialization State:
Applet enters the initialization state when it is first loaded. This is
achieved by calling init() method of Applet class. The Applet is born at this
stage. we must do the following steps:
1. create objects needed by Applet
2. Setup initial values
3. load images or font
4. setup colors
Begin Initialization
Begin
(Load Applet)
Start ()
Stop ()
Paint () Destroy ()
<HTML>
<!
............. Comment
............. Section
>
<HEAD>
Head
Title Tag
Section
</HEAD>
<BODY>
</HTML>
Head Section
The head section is defined with a starting <HEAD> tag and closing
</HEAD> tag. This section usually contains a title for the Web page as shown
below:
<HEAD>
<TITLE> Welcome to Java Applets </TITLE>
</HEAD>
The text enclosed in the tags <TITLE> and </TITLE> will appear in the
title bar of the Web browser when it displays the page. The head section is also
optional.
Note that tags <……> containing HTML commands usually appear in pairs
such as <HEAD> and </HEAD>, and <TITLE> and </TITLE>. A slash (/) in a
tag signifies the end of that tag section.
Body Section
After the head section comes the body section. We call this as body
section because this section contains the entire information about the Web page
and its behavior. We can set up many options to indicate how our page must
appear on the screen (like colour, location, sound, etc.). Shown below is a
simple body section:
<BODY>
<CENTER>
<H1> Welcome to the World of Applets </H1>
</CENTER>
<BR>
<APPLET ... >
</APPLET>
</BODY>
<APPLET
CODE = helloJava.class
WIDTH = 400
HEIGHT = 200 >
</APPLET>
<HTML>
<! This page includes a welcome title in the title bar and also displays a
welcome message. Then it specifies the applet to be loaded and executed.
>
<HEAD>
<TITLE>
Welcome to Java Applets
</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> Welcome to the World of Applets </H1>
</CENTER>
<BR>
<CENTER>
<APPLET
CODE = HelloJava.class
WIDTH = 400
HEIGHT = 200 >
</APPLET>
</CENTER>
</BODY>
</HTML>
//home
import java.awt.*;
import java.awt.event.*;
class MyFrame8 extends Frame
{
MyFrame8()
{
this.addWindowListener(new WindowAdapter())
{ 116 | P a g
public void WindowClosing(WindowEvent e) e
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
int x[]={375,275,475};
int y[]={125,200,200};
int n=3;
this.setBackground(Color.gray);
g.setColor(Color.yellow);
g.fillRect(300,200,150,100);
g.setColor(Color.blue);
g.fillRect(350,210,50,60);
g.drawLine(350,280,400,280);
g.setColor(Color.darkgray);
g.fillPolygon(x,y,n);
g.setColor(Color.cyan);
g.fillOval(100,100,60,60);
g.setColor(Color.green);
g.fillArc(50,250,150,100,0,180);
g.fillArc(150,250,150,100,0,180);
g.fillArc(450,250,150,100,0,180);
g.drawString("my Happy Home",275,350);
}
public static void main(String args[])
{
MyFrame8 h=new MyFrame8();
h.setSize(500,400);
h.setTitle("My Home");
h.setVisible(true");
}
}
118 | P a g
e
Introduction to AWT Package
AWT means “Abstract Window Toolkit”. It enables the programmers to
create GUI (Graphical User Interface) based applications. It contains a no. of
classes that help to implement the common Windows based tasks, such as
manipulating windows, adding scroll bars, buttons, list items, text boxes etc.
All these classes are contained in java.awt package. These classes are
hierarchically arranged inside the awt package. AWT provides support to both
standard and applet windows.
Component
Container
Window Panel
Applet
Frame Dialog
Component: - Component class is the super class to all the other classes
from which various GUI elements. It is primarily responsible for effecting the
display of a graphic object on the screen. It also handles the various keyboard
and mouse events (like Action Listeners) of the GUI application.
Container: - The Container object contains the other AWT components. It
manages the layout and placement of the various AWT Components within the
container. A container object can contain other containers objects as well i.e.,
nesting of containers.
Window: - The Window object is a top level window but without any border or
menu bar. It just specifies the layout of the window. A typical window that you
would want to create in your application is not normally derived from the
119 | P a g
window class but from its subclass Frame. e
Panel: - The super class of applet, Panel represents a window space on
which the applications output is displayed. It is just like a normal window
having no border, title bar, menu bar etc. A Panel can contain within itself
other panels as well.
Frame: - The Frame object is also a top level window complete with border
and menu bar. It supports common window related events such as close, open,
activate, deactivate, minimize, maximize etc. Almost all the programs that we
created while discussing applets and graphics programming used one or more
classes of the AWT package.
SWING Package: -
SWING is also a GUI toolkit as AWT that facilitates the creation of highly
interactive GUI applications. However, Swing is more flexible and robust when
it comes to implementing Graphical components. One of the main difference
between Swing and AWT is that Swing will always generate similar type of
output irrespective of the underlying platform. AWT on the other hand, is more
dependent on the underlying Operating System for generating the graphic
components. So, output may vary from one platform to another.
Swing can be regarded as more graphically rich than AWT not only because
they provide some entirely new graphical components as tabbed window and
tree structure etc. Some of the Key Swing Classes are:
Multi-Threading
Q. Write a short note on threading?
A thread is a process or execution of a task performing only one task is
called a single thread.
In multi tasking there are two types:
Process based multitasking:
Executing more than one program simultaneously is called process based
multitasking.
Thread based on multitasking:
Executing the different parts of the same program simultaneously is called
thread based multitasking.
Round robin:
Executing the first program after the second program is called round
robin system. 123 | P a g
Threads are useful in two ways: e
1. Creating of animation and games
2. Threads are used in an interesting server to server. to serve several clients
simultaneously.
124 | P a g
e
5. Dead state
A thread is always in one of these 5 states
New Thread
Newborn
Stop
Start
Active Stop
Running Runnable Dead Killed
Thread
Thread
Yield
Suspend Resume
sleep Stop
notify
wait
Idle Thread
(Not Runnable) Blocked
New born
Start Stop
Runnable State:
Runnable Dead
The runnable state means that the thread is ready for execution and is
state State
waiting for the availability of processed i.e., the thread has joined the queue of
threads that are waiting for execution. All threads are executed in round robin
fashion. the thread that relinquishes control joins the queue at the end and
again waits for its turn. This process of assigning a time is known as time
slicing.
However if you want a thread to relinquish control to another thread of
equal priority before its turn comes, we can do so by yield() method.
125 | P a g
e
Yield
Resume
Suspend():
Running
Suspend() method can be revived by usingSuspend
Runnable the resume()method. This
approach is useful when we want to suspend a thread for sometime due to
Sleep(t)
After (t)
notify
EXPLANATION:
Java supports two types of threads creation one is for create a class that
extends thread class implements runnable interface both the thread class or
runnable interface are found in java.lang package
Syntax:
class myclass extends Thread
(or)
class myclass implements Runnable
Create an object to empty so that the run method()is available 128 | for
Pag
execution. e
empty ob=new empty();
Now create an object to thread t and attatch the thread through the object
ob
Thread t=new Thread(ob);
In order to run the thread we should use start()method of thread class
t.start()
Now thread will start execution on the object of the empty class.Hence it
will be execute the statements inside the run()method.
Explanation:
When two tasks are assigned to two threads(t1 and t2)with different
priorities (1,5). the thread t2 with priority number 5 will be given more JVM
time and hence it will be complete the task earlier than the thread with priority
number 1 .
Thread Group:
A thread group represents several threads as a single group. The main
advantage of taking several threads as a group is that by using a single method
we will be able to control all threads in the groups.
To create a thread group Syntax:
ThreadGroup tg=new ThreadGroup("groupname");
To add a thread to this group(tg) syntax:
Thread t1=new Thread(tg,targetobj,"ThreadName");
Here t1 thread is created and added to the thread group tg. This thread act on
target obj
To add another thread group(tg1) to this group(tg) Syntax:
ThreadGroup tg1=new ThreadGroup(tg,"groupname");
To know the parent of the thread or thread group we can use getParent()
To know the parent Threadgroup of a thread we can use getThreadGroup()
To know the no.of threads actively running in a thread group using
activeCount()
Example:
class it12
{
Public Static void main(String args[])throws Exception
Reservation res=new Reservation();
Cancellation can=new Cancellation();
ThreadGroup tg=new ThreadGroup("first group") 135 | P a g
Thread t1=new Thread(tg,res,"first thread"); e
Thread t2=new Thread(tg,res,"second thread");
ThreadGroup tg1=new ThreadGroup(tg,"second group");
Thread t3=new Thread(tg1,can,"thrid thread");
Thread t4=new Thread(tg1,can,"four thread");
System.out.println("parent of tg1="+tg1.getParent());
tg1.SetMaxPriority(7);
System.out.println("threadgroup of t1="+t1.getThreadGroup());
System.out.println("threadgroup of t3="+t3.getThreadGroup());
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println("number of thread active in tg="+tg.activeCount());
}
}
class reservation extends Thread
{
public void run()
{
System.out.println("i am in reservation thread");
}
}
class Cancellation extends Thread
{
public void run()
{
System.out.println("i am in cancellaton ");
}
}
Q) What is a DAEMON THREADS:?
A Daemon thread is a thread that executes continuously. Daemon threads
are service providers for other threads or objects. It generally provides a
background processing.
Daemon thread is a low priority thread (in context of JVM) that runs in
background to perform tasks such as garbage collection (gc) etc., they do not
prevent the JVM from exiting (even if the daemon thread itself is running) when
all the user threads (non-daemon threads) finish their execution. JVM
terminates itself when all user threads (non-daemon threads) finish their
execution, JVM does not care whether Daemon thread is running or not, if JVM
finds running daemon thread (upon completion of user threads), it terminates
the thread and after that shutdown itself.
1. A newly created thread inherits the daemon status of its parent. That’s
the reason all threads created inside main method (child threads of main
thread) are non-daemon by default, because main thread is non-daemon.
However you can make a user thread to Daemon by using setDaemon() 136 | P a g
method of thread class. e
Just a quick note on main thread: When the JVM starts, it creates a
thread called “Main”. Your program will run on this thread, unless you
create additional threads yourself. The first thing the “Main” thread does
is to look for your static void main (String args[]) method and invoke it.
That is the entry-point to your program. If you create additional threads
in the main method those threads would be the child threads of main
thread.
2. Methods of Thread class that are related to Daemon threads:
public void setDaemon(boolean status): This method is used for making
a user thread to Daemon thread or vice versa. For example if I have a user
thread t then t.setDaemon(true) would make it Daemon thread. On the
other hand if I have a Daemon thread td then by calling
td.setDaemon(false) would make it normal thread(user thread/non-
daemon thread).
public boolean isDaemon(): This method is used for checking the status
of a thread. It returns true if the thread is Daemon else it returns false.
3. setDaemon() method can only be called before starting the thread. This
method would throw IllegalThreadStateException if you call this method
after Thread.start() method. (refer the example)
Example 1: DaemonThreadExample1.java
This example is to demonstrate the usage of setDaemon() and isDaemon()
method.
public class DaemonThreadExample1 extends Thread{
Output:
Daemon thread executing
user(normal) thread executing
q) Dead lock of thread?
Thread Group:
A thread group represents several threads as a single group. The main
advantage of taking several threads as a group is that by using a single method
we will be able to control all threads in the groups.
To create a thread group Syntax:
ThreadGroup tg=new ThreadGroup("groupname");
To add a thread to this group(tg) syntax:
Thread t1=new Thread(tg,targetobj,"ThreadName");
Here t1 thread is created and added to the thread group tg. This thread act on
target obj
To add another thread group(tg1) to this group(tg) Syntax:
ThreadGroup tg1=new ThreadGroup(tg,"groupname");
To know the parent of the thread or thread group we can use getParent()
To know the parent Threadgroup of a thread we can use getThreadGroup()
To know the no.of threads actively running in a thread group using
activeCount() 138 | P a g
Example: e
class it12
{
public static void main(String args[])throws Exception
{
Reservation res=new Reservation();
Cancellation can=new Cancellation();
ThreadGroup tg=new ThreadGroup("first group")
Thread t1=new Thread(tg,res,"first thread");
Thread t2=new Thread(tg,res,"second thread");
ThreadGroup tg1=new ThreadGroup(tg,"second group");
Thread t3=new Thread(tg1,can,"thrid thread");
Thread t4=new Thread(tg1,can,"four thread");
System.out.println("parent of tg1="+tg1.getParent());
tg1.SetMaxPriority(7);
System.out.println("threadgroup of t1="+t1.getThreadGroup());
System.out.println("threadgroup of t3="+t3.getThreadGroup());
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println("number of thread active in tg="+tg.activeCount());
}
}
class reservation extends Thread
{
public void run()
{
System.out.println("i am in reservation thread");
}
}
class Cancellation extends Thread
{
public void run()
{
System.out.println("i am in cancellaton ");}}
139 | P a g
e
Managing I/O Files in Java
Introduction: -
So far we have used variables and arrays for storing data inside the
programs. This is a temporary memory storage and posses a following:
The data is lost when we use variables and arrays when the program
terminated.
It is difficult to handle large volumes of data using the variables and
arrays.
We can overcome these problems by storing data on secondary storage
devices such as floppy disks or hard disks. The data is stored in these devices
using the concept of Files. Data stored in files is often called as Persistent
Data. A File is a collection of related records placed in a particular area on the
disk. A record is composed of several fields and a field is a group of characters.
Characters in Java area Unicode characters composed of two bytes, each byte
containing 8 binary digits. i.e., 0 or 1.
Storing and managing data using files is known as File Processing which
includes tasks such as creating files, updating files and manipulation of data.
The Reading and Writing of data in files can be done at the level of Bytes or
Characters or fields depending on the requirements of a particular application.
It provides capability to read and write class objects directly. It is called as
Object Serialization
Concept of Streams: -
In file processing, input refers to the flow of data into a program and
output means the flow of data out of a program. Input to a program may come
from the keyboard, the mouse, the memory, the disk, a Network, or another
program. Similarly output from a program may go to the screen, the printer,
the memory, the disk, a Network or another program.
Java uses the concept of Streams to represent the ordered sequence of
data, a common characteristics by all Input / Output devices. A stream
presents a uniform, easy to use, object oriented interface between the program
and the I/O devices. A stream is a path along which data flows from a source to
140 | P a g
destination. We can build a complex file processing sequence using a series
e of
simple stream operations. This feature can be used to filter data along the
pipeline of streams. Java streams are classified into two types. They are:
Input Streams and Output Streams. An input stream extracts (reads) data
from a source file and sends it to the program. The Output stream takes the
data from the program and sends (writes) it to the destination file. The program
connects and opens an input stream on the data source and then reads the
data serially, similarly the program connects and opens an output stream to the
destination and place / writes the data out.
Input Stream
Reads
Source Program
Output Stream
Writes
Using Program Destination
Java Stream
Classes
142 | P a g
e
Object
InputStream
FileInputStream SequenceInputStrea
m
PipeInputStream ObjectInputStrea
m
ByteArrayInputStream StringBufferInputStream
FilterInputStrea
m
BufferInputStream PushbackInputStrea
m
DataInputStream
DataInput
Method Description
Read( ) Reads a byte from the input stream
Read(byte b[]) Reads an array of bytes into b
Read(byte b[], int n, Reads n bytes into b starting from nth
int m) byte.
Gives the no. of bytes available in the
Available( )
input
Skip(p) Skips over p bytes from the input stream
Reset( ) Goes back to the beginning of the stream
Close( ) Closes the Input Stream
Object
OutputStream
FileOutputStrea ObjectOutputStream
m 144 | P a g
e
PipedOutputStre ByteArrayOutputStream
am
FilterOutputStre
am
The DataOutputStream is similar to DataInputStream which implements the
interface DataOutput and contains the following methods
WriteShort( ) WriteDouble( )
WriteInt( ) WriteBytes( )
WriteLong( ) WriteChar( )
WriteFloat( ) WriteBoolean( )
WriteUTF( )
Character Stream Classes: -
The Character Stream Classes can be used to read and write 16 bit
Unicode characters. In this there are two kinds of stream classes they are,
Reader Stream Classes and Writer Stream Classes.
Reader Stream Classes: -
Reader Stream Classes are designed to read characters from the files.
Reader class is the base class for all other classes. These classes are
functionally very similar to the input stream classes, except input streams use
byte as their fundamental unit of information, while reader streams are uses
characters
Object
Reader
CharArrayReader PipeReader
InputStreamReader FilterReader
Writer Stream Classes: -
The Output Stream Classes have another type of Streams called Writer
Stream Classes. These are designed to perform all output operations on files.
Only difference is that while output stream classes are designed to write bytes,
the writer stream classes are designed to write characters. The writer class is
an abstract class which acts as a base class for all the other stream classes. It
provides support for all output operations by defining the methods that are
identical to those in OutputStream class. These classes are known as I/O
Classes and not all of them are used to reading and writing operations only.
Using Stream: -
These input and Output stream classes are used for handling both the 8
bit bytes and 16 bit characters. Although all the classes are known as I/O
classes. Both the character stream group and the byte stream group contain
parallel pairs of classes that perform the same kind of operations but for the
different data type.
Object
Writer
BufferedWriter PrintWriter
CharArrayWriter StringWriter
FilterWriter PipeWriter
146 | P a g
e
OutputStreamWriter
FileWriter
List of Classes Implementing and Purpose: -
Character Stream
Task Byte Stream Classes
Classes
Reading from files FileInputStream FileReader
Writing to a file FileOutputStream FileWriter
Reading Premitive
DataInputStream None
Types
Performing I/P
InputStream Reader
operations
Performing O/P
OutputStream Writer
operations
Buffering input BufferedInputStream BufferedReader
Keeping track of Line
LineNumberInputStream LineNumberReader
no’s
Reading from an Array ByteArrayInputStream CharArrayReader
Convert Byte Char
None InputStreamReader
Stream
Filtering the Input FilterInputStream FilterReader
Pushing back Char’s /
PushbackInputStream PushbackReader
Bytes
Reading from a Pipe PipedInputStream PipedReader
Reading from a String StringBufferInputStream StringReader
Writing to Pipe PipedOutputStream PipedWriter
Writing to a String None StringWriter
147 | P a g
e
Other Useful I/O Classes: -
The java.io package supports many other classes for performing certain
specialized functions. They include:
1. Random Access Files
2. Stream Tokenizer
1. Random Access Files: -
The RandomAccessFile enables us to read and write bytes, text and java
data types to any location in a file (randomly). This class extends object class
and implements DataInput and DataOutput interfaces. This forces the
RandomAccessFile to implement the methods in both the interfaces. By using
this stream we can read and write the data at a time into the files and we can
start reading and writing at any position given in the file. i.e., it starts from 0th
location.
Files can be used either for read only or for write only operations and
not for both purposes simultaneously. These files are read or written only
sequentially and therefore are known as Sequential Files. The
RandomAccessFile classes allows us to create files that can be used for reading
and writing the data with random access. A file can be created and opened for
random access by giving a mode string as a parameter to the constructor when
we open a file. We can use one of the following two modes of Strings:
“r” for reading only
“rw” for reading and writing.
Object
Interface Interface
DataInput DataOutput
RandomAccessFile 148 | P a g
2. Stream Tokenizer: - e
The class StreamTokenizer, is a subclass of Object can be used for
breaking up a stream of text from an input text file into meaningful pieces called
tokens. The behaviour of the StreamTokenizer class is similar to that of
StringTokenizer class that breaks a string into its component tokens.
Using the File Classes: -
The java.io package contains the File class, which is used to creating files
and directories. This class includes several constructors for instantiating the
File Objects. This class also contains several methods for the following
operations.
1. Direct Method: -
FileInputStream fis; // Declare a File Stream Object
Try
{// Assign the Filename to the File Stream Object
Fis = new FileInputStream(“test.dat”);
…………………..;
}
Catch(IOException e)
{ ……………….
………………..
}
2. Indirect Method: -
File infile // Declare a File Object;
Infile = new File(“test.dat”); // Assign the File name to the Object
FileInputStream fis;
Try
{ // Gives the Value of the File Object to the File Stream Object
Fis = new FileInputStream(infile);
…………………………………..
}
Catch(IOException e)
{ ………………….
……………………
}
InputPipe OutputPipe
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
class zip
{
public static void main(String[] args) throws IOException {
//Assign the original file : file to
//FileInputStream for reading data
FileInputStream fis=new FileInputStream("file1");
}
}
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following
SerializeDemo program instantiates an Employee object and serializes it to a
file.
When the program is done executing, a file named employee.ser is created. The
program does not generate any output, but study the code and try to determine
what the program is doing.
Note − When serializing an object to a file, the standard convention in Java is to
give the file a .ser extension.
Example
import java.io.*;
public class SerializeDemo {
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} 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 −
Example
import java.io.*;
public class DeserializeDemo {
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
} 157 | P a g
} e
This will produce the following result −
Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Q) Explain about counting number of characters in a file?
Sample.txt
Pykumar
Sairam is god
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try
{
//Creating BufferedReader object
lineCount++;
158 | P a g
//Getting number of words in currentLine e
String[] words = currentLine.split(" ");
currentLine = reader.readLine();
}
The File class have several methods for working with directories and files such
as creating new directories or files, deleting and renaming directories or files,
listing the contents of a directory etc.
161 | P a g
e
import java.io.*;
class FileProperty
String fname=args[0];
System.out.println(“Filename”+f.getName());
System.out.println(“path”+f.getpath());
System.out.println(“absolute path”+f.getAbsolutePath());
System.out.println(“parent”+f.getParent());
System.out.println(“exists”+f.exists());
if(f.exists())
{ System.out.println(“is writeable”+f.canWrite());
System.out.println(“is readable”+f.canRead());
System.out.println(“is a directory”+f.isDirectory());
}}
Output
C:\>javac FileProperty.java
exists true
is writable true
isreadable true
is a directory false
162 | P a g
file size in bytes 61 e
The software side of a database server, or the database instance, is the back-
end database application.
The hardware side of a database server is the server system used for database
storage and retrieval.
Database workloads require a large storage capacity and high memory density
to process data efficiently. These requirements mean that the machine hosting
the database is usually a dedicated high-end computer.
The database server stores the Database Management System (DBMS) and the
database itself. Its main role is to receive requests from client machines, search
for the required data, and pass back the results.
The DBMS provides database server functionality, and some DBMSs (e.g.,
MySQL) provide database access only via the client-server model. Other
DBMSs (such as SQLite) are used for embedded databases.
The ODBC (Open Database Connectivity) standard provides the API allowing
clients to call the DBMS. ODBC requires necessary software on both the client
163 | P a g
and server sides. e
In a master-slave model, the database master server is the primary data
location. Database slave servers are replicas of the master server that act as
proxies.
Statement parses a statement before its execution on the database. This parsing
is done every time the statement is executed, and hence it may take more time
when the same statement gets executed repetedly. Preapared statement
conducts parsing only once when the same statement is executed repeatedly
and hence it gives better performance.
Callable statements is useful to call stored procedure and functions which run
at a database server and get the results into the client.
JDBC
Introduction:
4. JDBC-ODBC Bridge
The Java Software Bridge provides JDBC access via ODBC drivers. Note that
you need to load ODBC binary code onto each client machine that uses this
driver. As a result, the ODBC driver is most appropriate on a corporate
network where client installations are not a major problem, or for
application server code written in Java in a three-tier architecture.
165 | P a g
e
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for
databaseaccess.
167 | P a g
e
rowsets. The JDBC API is also what allows access to a data source from a Java
middle tier.
JDBC Driver
A JDBC driver is a software component enabling a java application to interact
witha database. JDBC requires drivers for each database. The JDBC driver gives
out theconnection to the database and implements the protocol for transferring the
query and result between client and database. JDBC drivers are client side
adaptors that convert request from java program to a protocol that that the DBMS can
understand.There are four types of driver
1. JDBC-ODBC Bridge Driver (Type 1)
2. Native API Driver (Type 2/Partially Java Driver)
3. Network Protocol Driver (Type 3/Fully Java Driver)
4. Thin Driver (Type 4/Fully Java Driver)
168 | P a g
e
Advantages
Easy to connect
Directly connected to database
Disadvantage
Does not support the complete java command set and are limited by
thefunctionality of the ODBC driver.
Needs to be installed on client machine.
Slow, as compared to other drivers.
2. Native API Driver (Type 2/Partially Java Driver)
It uses client side libraries of the database.
The driver converts the JDBC method call into native call.
Native drivers must be installed on client machines.
Vendor client libraries need to be installed on client machine.
It is not written entirely in java.
Advantage
Better performance as compared to Type 1 driver.
169 | P a g
e
Disadvantage
Driver is platform dependent.
The vendor client library needs to be installed.
Native driver needs to be installed on each machine.
Advantage
No client side library is required.
Disadvantage
Network support is required on client machine.
Database specific coding is done in middleware.
170 | P a g
e
Advantage
Performance is good as compared to other drivers.
No software is required for client or server side.
Disadvantage
Different types of drivers required for different database.
Steps to connect to database
1. Register the driver class.
2. Create connection.
3. Create Statement.
4. Execute queries.
5. Close the connection.
Package for JDBC connection
1. java.sql.*;
Provides the API for accessing and processing data stored in a data sourceusing Java.
2. javax.sql.*;
Purpose of JDBC
Enterprise applications that are created using the JAVA EE technology need to
interact with databases to store application-specific information. So, interacting with
a database requires efficient database connectivity which can be achieved by using
the ODBC(Open database connectivity) driver. This driver is used with JDBC to
interact or communicate with various kinds of databases such as Oracle, MS Access,
Mysql and SQL server database.
171 | P a g
e
Q)Architecture of JDBC
The JDBC API: The JDBC API allows Java programs to execute SQL statements and
retrieve results. Some of the important classes and interfaces defined in JDBC API are
as follows:
DriverManager
Connection
Statement
PreparedStatement
ResultSet
172 | P a g
e
Programs
try
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Sql important
//step5 Queries
close the connection object
con.close();
System.out.println(e);
1. Select ---- To display required columns from
table Syntax:
SELECT COLUMN1,COLUMN2,... FROM TABLENAME;
Ex :
Note : Need all columns of table then use '*' for all columns
table Syntax :
insert into tablename values(value1,value2,value2,. );
Ex :
insert into emp values(1342,'GOWTHAM','MANAGER',. );
table Syntax :
Ex :
174 | P a g
e
delete from employee where
empno=6763;
175 | P a g
e
4 . update ----> To modify column values
Syntax :
update tablename set columnname=expr or value where
<condition>
Ex :
update emp set sal=sal+1000;
JDBC program connect to oracle database and retrieve rows form
import java.sql.*;class
OracleCon
{
public static void main(String args[])
{
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
177 | P a g
e
Import java.sql.*
class UpdateExample
{
public static void main (String args [])
{
try
{
// Load the Oracle JDBC driver Class.forName("oracle.jdbc.driver.OracleDriver");
178 | P a g
e
Write a JDBC example to delete a employee record
import java.sql.*;
class DeleteExample
{
public static void main (String args [])
{
try
{
// Load the Oracle JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
class PreparedStatementExample
{
public static void main (String args [])
{
try
{
// Load the Oracle JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
180 | P a g
e
// Close the statement
pstmt.close();
// Close the connecion
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
A JDBC Application to create a GUI Form accept Data and save the Datato Table
}
class FormData
{
public static void main(String[] args)
{
Frame f=new Frame();
Label label1=new Label("First Name: ");Label
label2=new Label("Last Name: "); Label
label3=new Label("Email: "); Label label4=new
Label("Address: "); Label label5=new
Label("Contact No: ");
final TextField text1=new TextField(20); final TextField
text2=new TextField(20); final TextField text3=new
TextField(20); final TextField text4=new TextField(20);
final TextField text5=new TextField(20); Button b=new
Button("Save"); b.addActionListener(new
ActionListener()
181 | P a g
e
{
public void actionPerformed(ActionEvent e)
{
String v1=text1.getText(); String
v2=text2.getText(); String
v3=text3.getText(); String
v4=text4.getText(); String
v5=text5.getText();try
{
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection
con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); Statement
st=con.createStatement();
int i=st.executeUpdate("insert into student(fname,lname,email,address,telephone)
values('"+v1+"','"+v2+"','"+v3+"','"+v4+"','"+v5+"')");
JOptionPane.showMessageDialog(null,"Data is insertedsuccessfully");
}
catch(Exception ex){ System.out.println(ex);
}
}
});
Panel p=new Panel(new GridLayout(6,2));p.add(label1);
p.add(text1);
p.add(label2);
p.add(text2);
p.add(label3);
p.add(text3);
p.add(label4);
p.add(text4);
p.add(label5);
p.add(text5);
p.add(b);
f.add(p);
f.setVisible(true);
182 | P a g
e
f.pack();
}
}
184
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
tnsnames.ora file.
Than click on OK
186
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Example:
import java.sql.*;
public class Collegeek_JDBC1_example {
public static void main(String[] args) {
try{
// Load and register the driver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e) {
e.printStackTrace();
}
//Driver myDriver = new
sun.jdbc.odbc.JdbcOdbcDriver();
//DriverManager.registerDriver(myDriver);
// Create a statement
Statement st = cn.createStatement();
187
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
}
}
188
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Program:
Import java.sql.*;
Class MysqlData
{public static void main(String args[])throws Exception
{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con
DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?user=root&passwo
rd=student”);
Statements stmt=con.createStatement();
ResultSet rs=stmt.ExecuteQuery(“select * from emp”);
While(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getFloat(3));
}
Con.close();
}
}
Output:
C:\>set classpath=c:\jars\mysql.jar;.;
C:\>javac MysqlData.java
C:\>java MysqlData
101
Pykumar
6000
102
Sairam
5000
189
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Although you are free to use any of the Microsoft Access version that is convenient for
you, I would recommend you to try out the latest one steps involved in creating MS
Access database.
To connect our Java application with Microsoft Access Database, we need to add some
JAR files to our program,
Open Eclipse IDE and click on the Java Project under the new section of File Menu
(File>>New>>Java Project).
Now give a name to your project (AccessConnect in this example) and click on
“Finish”.
Now right click on the project and create a new Java class (New>>Class).
Now give a name to your class(AccessConnectivity in this Example), tick mark on
the public static void main(String[] args), and then click on the Finish button
//Creating Class
public class AccessConnectivity {
190
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
}
Step #2 -> Adding UCanAccess Jar Files to Java Program in
Eclipse
To connect your java program with the MS Access database in Eclipse IDE, you need to
include UCanAccess Jar files to the Eclipse.
I have given the download link of the zip file in the above.
Extract the zip archive and you will get the Jar files.
Right-click on the project, go to the properties section, select Java Build Path, and click
on the Add External JARs button.
After clicking on the button, a pop-up window will appear to select and open the
Jar files.
You can see the added Jar files as shown in the figure below. Now click on
the Apply and Close button.
Step #3 -> Connecting Java Program with the MS Access
Database
Since we have already finished adding Jar files, now we are ready to connect our Java
program with MS Access Database.
import java.sql.Connection;
import java.sql.DriverManager;
191
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
System.out.println("Connected Successfully");
}catch(Exception e){
System.out.println("Error in connection");
}
}
}
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you
will automatically get one that is TYPE_FORWARD_ONLY.
192
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the
result set is not sensitive to changes made by others to
the database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the
result set is sensitive to changes made by others to the
database that occur after the result set was created.
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any
Concurrency type, you will automatically get one that is
CONCUR_READ_ONLY.
Concurrency Description
193
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Moves the cursor the given number of rows forward or backward, from
where it is currently pointing.
Moves the cursor to the previous row. This method returns false if the
previous row is off the result set.
Moves the cursor to the next row. This method returns false if there are
no more rows in the result set.
Moves the cursor to a special row in the result set that can be used to
insert a new row into the database. The current cursor location is
remembered.
194
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Moves the cursor back to the current row if the cursor is currently at the
insert row; otherwise, this method does nothing
Returns the int in the current row in the column named columnName.
Returns the int in the current row in the specified column index. The
column index starts at 1, meaning the first column of a row is 1, the
second column of a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of
the eight Java primitive types, as well as common types such as
java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date,
java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob.
Check the documentation for more information about using these SQL
data types.
For a better understanding, let us study Viewing - Example Code.
195
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
There are update methods for the eight primitive data types, as well as
String, Object, URL, and the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current
row in the ResultSet object, but not in the underlying database. To
update your changes to the row in the database, you need to invoke
one of the following methods.
Refreshes the data in the result set to reflect any recent changes in the
database.
196
P.Y.Kumar M.C.A,M.Tech,M.Phil..,
Inserts a row into the database. This method can only be invoked when
the cursor is pointing to the insert row.
197