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

java22

The document is a comprehensive course outline for a B.Sc. Core Java curriculum, covering key topics such as Java fundamentals, object-oriented programming principles, exception handling, and Java database connectivity. It details various units including data types, control statements, inheritance, polymorphism, and threading, along with practical applications like applets and file handling. Additionally, it discusses the evolution of Java, its parts, and comparisons with other programming languages like C and C++.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java22

The document is a comprehensive course outline for a B.Sc. Core Java curriculum, covering key topics such as Java fundamentals, object-oriented programming principles, exception handling, and Java database connectivity. It details various units including data types, control statements, inheritance, polymorphism, and threading, along with practical applications like applets and file handling. Additionally, it discusses the evolution of Java, its parts, and comparisons with other programming languages like C and C++.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 197

II YEAR B.

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,

Thread Communication, Thread Priorities, thread Group, Daemon Threads, Applications of


Threads, Thread Life Cycle

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 major objective of object oriented approach is to eliminate some flaws


encountered in the procedure oriented approach. OOP treats data as a critical element in the
program development and does not allow to flow freely around system. It ties data more
closely to the functions that operate on it and protects it from external functions. By
unintentional modifications by OOP allows us to decompose a problem into a number of
entities called “objects” and then build data and functions or methods.

Some Features of OOP

1. Emphasis on data rather than procedure.


2. Programs are divided into what are known as “objects”.
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together in the data structures.
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through methods.
7. New data and methods can be added whenever necessary.
8. Follows bottom to top approach in program design.

Q. What are the basic concepts of Object Oriented Programming?

The general concepts of OOP which form the heart of Java language are

Objects and Classes


Classes and Objects.

 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 Abstraction and Encapsulation


The wrapping up of data and methods into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world and only these methods, which are wrapped in the class, can
access it. These methods provide the interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding.
Encapsulation makes it possible for objects to be treated like ‘black boxes’.

Data
Information “in” and Information “out”
Method

F IGURE 2: E NCAPSULATION – O BJECTS AS “ BLACK BOXES ”

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

F IGURE 3: P ROPERTY I NHERITANCE


In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined features of
both the classes.

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()

Circle Object Triangle Oval Object


Draw Object Draw (Oval)
(Circle) Draw
F IGURE 4: P OLYMORPHISM

Dynamic Binding (Triangle) Local Data


Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at runtime.
Message Communication
An object-oriented program consists of a set of objects that communicate with each
other. The process of programming in an object-oriented language, therefore, involves the
following basic steps:
1) Creating classes that define objects and their behavior.
2) Creating objects from class definitions.
3) Establishing communication among objects.
Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another.

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:

 Real time Systems.


 Simulation and modeling.
 Object oriented databases.
 Hypertext, hypermedia and expert text.
 Artificial Intelligence (AI) and expert systems.
 Neural networks and parallel programming.
 Decision support and office automation systems.
 CIM / CAD / CAM systems.

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

2) Lager program size

3) Slower programs :

4) Not suitable for all types of problems

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.

Java is the first programming language that supports a complete Platform


Independency that is not tied to any particular hardware or operating system. Programs
developed in Java can be executed on any system.

We can develop two types of applications one is Standalone Application and


another one is Web Applets. Standalone applications can execute by their own where as the
Applets are small java programs developed for Internet applications and needs a separate
environment to execute.

Q. What are the important Milestones in the development of Java?

Year Development

Sun Micro Systems decided to develop software that could used to


1990 manipulate consumer electronic devices. A team of James Gosling
known as Green Project team came into work.

1991 The team announced a new language oak.

The team demonstrated the application using a hand-held device with a


1992
tiny touch-sensitive screen.

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.

1997 JDK 1.1

1998 Java 2 with version SDK 1.2 was released.

1999 Standard Edition (J2SE) and Enterprise Edition (J2EE) are released.

2000 J2SE with SDK 1.3 was released.

2002 J2SE with SDK 1.4 released.

2004 J2SE with JDK 5.0 (JDK 1.5) was released.

8|P age
q) Write about parts of java?

Sun Microsystems has divided into 3 parts

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

q) Requirements for Hardware and Software

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

Q. Explain Difference between Java and C AND C++?

Differences between C, C++ and Java


Metrics C C++ Java

Programming Object-Oriented Pure Object Oriented


Procedural language
Paradigm Programming (OOP) Oriented
Based on assembly
Origin Based on C language Based on C and C++
language
Dennis Ritchie in Bjarne Stroustrup in
Developer James Gosling in 1991
1972 1979
Interpreted language
Translator Compiler only Compiler only (Compiler +
interpreter)
Platform Dependency Platform Dependent Platform Dependent Platform Independent
Executed by JVM
Code execution Direct Direct (Java Virtual
Machine)
Approach Top-down approach Bottom-up approach Bottom-up approach
File generation .exe files .exe files .class files
Pre-processor Support header files Supported (#header,
Use Packages (import)
directives (#include, #define) #define)
keywords Support 32 keywords Supports 63 keywords 9|P age
50 defined keywords
Datatypes (union,
Supported Supported Not supported
structure)
Supported except
Inheritance No inheritance Supported
Multiple inheritance
Support Function
Operator overloading
Overloading No overloading overloading
is not supported
(Polymorphism)
Pointers Supported Supported Not supported
Allocation Use malloc, calloc Use new, delete Garbage collector
Exception Handling Not supported Supported Supported
Templates Not supported Supported Not supported
No constructor neither
Destructors Supported Not supported
destructor
Multithreading/
Not supported Not supported Supported
Interfaces
Database connectivity Not supported Not supported Supported
Supported ( auto, Supported ( auto, extern
Storage Classes Not supported
extern ) )

C++

C Java

F IGURE 6: O VERLAPPING OF C, C++ AND J AVA

Q. Explain Features of 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

To provide better reliability, Java has to implement applications on variety of


platforms. Java is robust language. It concentrates on areas like identifying errors i.e.
exception handling and memory management problems.

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.

Core, XML supports


Java support XML (extensible markup language) feature, Java contain some special
packages for interface to instantiate simple API fro XML and document Object Model (DOM)
to transform and validate the content of an XML document.
11 | P a g
e
Q)write a Java Naming Conventions?

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.

Advantage of Naming Conventions in Java

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.

Identifiers Naming Rules Examples


Type

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.

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as {
Runnable, Remote, ActionListener. //code snippet
Use appropriate words, instead of }
acronyms.

Method It should start with lowercase letter. class Employee


It should be a verb such as main(), {
print(), println(). // method
If the name contains multiple words, void draw(){
start it with a lowercase letter followed //code snippet
by an uppercase letter such as }
actionPerformed(). }
12 | P a g
Variable It should start with a lowercase letter class Employee e
such as id, name. {
It should not start with the special //variable
characters like & (ampersand), $ (dollar), int id;
_ (underscore). //code snippet
If the name contains multiple words, }
start it with the lowercase letter followed
by an uppercase letter such as
firstName, lastName.
Avoid using one-character variables such
as x, y, z.

Package It should be a lowercase letter such as //package


java, lang. package com.javatpoint;
If the name contains multiple words, it class Employee
should be separated by dots (.) such as {
java.util, java.lang. //code snippet
}

Constant It should be in uppercase letters such as class Employee


RED, YELLOW. {
If the name contains multiple words, it //constant
should be separated by an underscore(_) static final int MIN_AGE = 18;
such as MAX_PRIORITY. //code snippet
It may contain digits but not as the first }
letter.

Q. Explain Java Support Systems available?

Support System Description


Internet Connection Local computer should be connected to the Internet.

Program that accepts request for information and sends


Web Server
the required documents.

Web Browser Program that access to WWW and runs Java applets.

HTML A language for creating hypertext for the web.

Java Code Java code is used for defining Java applets.

Compiled Java code that is referred to in the APPLET tag


Byte code
and transferred to the user computer.

13 | P a g
e
Q. Explain Java and World Wide Web?

World Wide Web is an open-ended information retrieval system designed to be used in


Internet’s distributed environment. This system contains what are known as web pages that
provide both information and controls. Java was meant to be used in distributed environment
such as internet. Java communicates with webpage through a special tag called applet. The
web pages are made with the help of HTML. The incorporation of Java into web pages has
made it capable of supporting animation, graphics, games etc. The figure shows the following
communication steps.

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.

Q. Explain different Web browsers?

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.

Ex: Hot Java, Netscape Navigator, Internet Explorer.

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

Netscape Navigator from the Netscape communication corporation is a general


purpose browser that can run Java applets. It supports java script used in HTML documents.
The advantages are visual display about downloading process and indicator of the no. of
bytes the downloaded.

Internet Explorer

It is another popular web browser developed by windows. Explorer uses a just-in-time


(JIT) compiler which greatly increases the speed of execution. Both the Navigator and
Explorer use tool bars, icons, menus and dialog boxes to navigate.

Chrome,firefox,safari,opera,seamonkey,k-meleon,camino,amaya,kidzui
etc…

Q. What is Java Development Kit JDK? Or Q. Explain about Java Environment?


Java environment includes a large number of development tools and hundreds of
classes and methods called Java Development Kit (JDK).
Java Development Kit (JDK)
JDK comes with a collection of tools that are used for developing and running a Java
programs. They include:
Javac – Java Compiler
Java – Java Interpreter
jdb – Java Debugger
Javadoc – for Creating HTML documents
Javah – for C header files
Appletviewer – for viewing java applets
Javap – java disassembler

Q. Why is Java known as platform-neutral language?

The concept of platform independency makes java as architecture neutral language.


To provide better portability, Sun Microsystems concentrated on a new language and the
result was Java. It can produce code that would run on a variety of CPUs under different
environments. Once java code is produced it can be run anywhere on any environment.
Moreover, as the java code runs on any platform, it can be adapted to internet too because
internet programming does require the same kind of approach. Platform independency is
achieved by java through its JVM (Java Virtual Machine).

Java Virtual Machine

The Java achieves architecture neutrality because Java compiler produces an


intermediary code known as byte code for a machine that does not exist. This machine is
called the Java Virtual Machine. Following fig illustrates the process of compiling of java
program.

Java Program Java Compiler Virtual Machine

Source Code Byte Code


Byte Code Java Interpreter Machine Code

Virtual Machine Real Machine 15 | P a g


e
The virtual machine code is not machine specific. The machine specific code is
generated by the Java interpreter by acting as an intermediary between the virtual machine
and real machine. JVM is a tool that provides platform independency to the language. Java
compiler is machine dependent and the JVM is machine dependent, it is the only byte code
that is machine independent. The byte codes are the intermediate codes manage in a class
file. All the components of JVM provide flexibility to the user. The components of JVM are
shown below.

Java virtual Machine


Internet Server Additional class files
consisting of Class Loader needed by the
java byte codes program are also
in a class file loaded.
Byte code verifier

JIT Interpreter
compiler

Runtime Env.

Application Programming Interface (API)


The Java Standard Library or API includes hundreds of classes and methods
grouped into several functional packages. They are:

 Language Support Package


 Utilities Package
 Input/ Output package
 Networking Package
 AWT Package (Abstract Window Toolkit)
 Applet Package

Q. How to run Java application program?

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

Q. Explain structure of Java Program?

1. Documentation Section
2. Package Statement
3. Import Statements
4. Interface Statements
5. Class Declarations
6. Main method class
{
7. Main method declaration
}

EXAMPLE

/* Program for Square root */


import java.lang.Math;
class SquareRoot
{
public static void main(String args[ ])
{
double x = 5; //Declaration and initialization
double y; //Simple declaration
y = Math.sqrt(x);
System.out.println(“y = ”+ y);
}
}
Documentation section

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.

Ex: /** This is the first program */

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.

Syntax: package <package name>;

Java.util (random, number, date, vector)

Java.io (input, output support classes)

Java.awt (include classes for windows, menus, buttons)


18 | P a g
Java.net (for networking) e
Java.lang (for primitive types strings, math functions, threads, exceptions)
Java.applet (classes for creating and implementing applets).

import statement

This statement is similar to #include statement in c. This statement instructs the


interpreter to load the class contained in the package name using import statement, we can
have access to classes that are part of packages.

Syntax: import <package name>.<class name>;

interface statement

An interface is like a class but includes a group of method declarations. It is used only
to implement the multiple inheritance.

interface <interface name>


{
Variable declarations;
Method declarations;
}

Class definition

Simple Java Program

public class sample


{
public static void main(String args[])
{
System.out.println(“Java is better than C++”);
}
}

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.

This line contains no. of keywords, public, static and void.

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

System.out.println (“welcome”). It is similar to printf () statement in C. The println is


member of out object which is a static data member of system class. The method println
always apply a new line character to the end of the string.

Every java statement must be ended with semicolon.

Q. Explain Java Tokens?

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

abstract boolean break byte byvalue*


case cast* catch char class
const* continue default do double
else extends false** final finally
float for future* generic* goto*
if implements import inner* instanceof
int interface long native new
null** operator* outer* package private
protected public rest* return short
static super switch synchronized this
threadsafe* throw throws transient true**
try var* void volatile while

Identifiers

The purpose of identifier is for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.

Rules

1. They must not begin with a digit.


2. Uppercase and lowercase letters are different.
3. They can be of any length.
4. They can have alphabets, digits and the underscore and dollar sign characters.

Various naming conventions have to follow when declaring identifiers.

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.

Ex: final int x=10; final float pi=3.14f;

Separators

Separators are symbols used to indicate where groups of code are divided and
arranged.

Name Use

It is used in method and expression and surrounding


Parenthesis ( )
cast types.

It is used to automatically initialize values of an array,


Braces { }
define block of code for classes and methods.

Square brackets [ ] It is used to declare array type and values.

Semicolon ; Used to separate statements

Used to separate consecutive identifiers in variable


Comma ,
declaration.

Period . Used to separate package name from sub packages.

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

These operators are used to perform arithmetic operations on variables and to


construct mathematical expressions.

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo division (remainder)


21 | P a g
e
Mixed Mode

When one of the operand is real and other is integer then the operation is called
mixed mode arithmetic expression.

Ex: 15 / 10.0 = 1.5 where as 15/10 = 1

Relational operators

These are used to test for equality of expressions. These result either true or false
value.

Operator Meaning

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== 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 AND

|| Logical OR

! Logical NOT
Assignment operators

Assignment operator is used to assign the value of an expression to a variable. Java


has a set of shorthand assignment operators which are used in the form:

Variable op=exp;

Simple assignment operator is = (equal to). The general syntax of simple assignment
operator is

Variable = constant or expression;

Increment and decrement operators

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:

++m or m++; --m or m--; 22 | P a g


e
Conditional operator

The ? : is a ternary operator available in Java. The operator is used to construct


conditional expression in Java.

Syntax: exp1 ? exp2 : exp3;

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 AND

! Bitwise OR

^ Bitwise exclusive OR

~ Bitwise one’s complement

<< Shift left

>> Shift right

>>> Shift right with zero fill


Special operators

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.

Ex: sai instanceof student;

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.

Ex: sai.age; sai.total_marks ();

23 | P a g
e
q)Explain Operators and their precedence ?

Priority Operator Associativity

1 . () L to R

2 -, ++, --, !, ~, (type) R to L

3 *, /,% L to R

4 +,- L to R

5 << , >> , >>> L to R

6 <, <=, >, >=, instanceof 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

Q. Explain different data types available in Java?

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.

Normally non-zero float values are represented as:

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.

Non-zero double values are represented as:

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.

The representation of primitive types and its ranges as follows.

Data type Representation size range

Byte 8 bit signed -128 to 127

Short 16 bit signed 132768 to 32767

Int 32 bit signed -2147483648 to 2147483647

-9223372036854775808 to
Long 64 bit signed
9223372036854775807

Char 16 bit unsigned Unicode Holds a single character

Float 32 bit 3.4 e -38 to 3.4 e +38

Double 64 bit 1.7 e -308 to 1.7 e +308

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.

1. Equality and inequality operations


2. Boolean logical operators.
3.

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.

Ex: 123, -321, O37 (octal), Ox2, Ox9f (hexadecimal).

Real constants used to represent the numbers containing fractional parts. A real number
may also be expressed in exponential notation also.

Ex: 215.65, 0.65e4, 12e-2

Single Character constants contain a single character enclosed within a pair of single
quotation marks.

Ex: ‘a’. ‘5’, ‘\n’

Backslash character constants

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

String constant is a sequence of characters enclosed between double quotes. The


characters may be alphabets, digits, special characters, and blank spaces.

Ex: “sai”, “2010”, “5+3”

Symbolic Constants

The constants may appear repeatedly in a number of places in the program. A


constant is declared as follows.

Ex: final float pi=3.14f;

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

Java variables are generally classified into three types.

 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.

Syntax: type variable = (type) value;

Ex: int m=60; byte n=(byte) m;

Q. Explain Command Line arguments in Java?

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.

/**example of command line arguments */


class ComLine
{
public static void main(String args[])
{
int count,i=0;
count=args.length;
System.out.println("number of arguments = " +count);
while(i<count)
{
System.out.println(argument " + i + " = " + args[i]);
i++;
}
}
}
27 | P a g
In the above program, args declared as a array of strings, each individual element
e is
accessed by using an index like args[i], the index starts from 0.
Q. Explain different types of variables?

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”;

Here s is a string object.

Primitive can be used to hold primitive values.

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);
}
}

Q) How to display formatted output with string format()?

public class FormatExample3


{
public static void main(String[] args)
{
String str1 = String.format("%d", 101);
String str2 = String.format("|%10d|", 101); // Specifying length of integer
String str3 = String.format("|%-10d|", 101); // Left-
justifying within the specified width
String str4 = String.format("|% d|", 101);
String str5 = String.format("|%010d|", 101); // Filling with zeroes
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}
101
101
101
101
0000000101
Q. Explain various Mathematical functions available in Java?

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();

Ex: double y= Math.sqrt();

The various functions available with the Math class are listed below.

Function Action

sin(x) Returns the sine of the single x in radians


31 | P a g
cos(x) Returns the cosine of the angle x in radians e
Function Action

tan(x) Returns the tangent of the angle x in radians

asin(y) Returns the angle whose sine is y

acos(y) Returns the angle whose cosine is y

atan(y) Returns the angle whose tangent is y

pow(x,y) Returns x raised to y (xy)

exp(x) Returns e raised to x (ex)

log(x) Returns the natural logarithm of x

sqrt(x) Returns the square root of x (double precision)

abs(x) Returns the absolute value of x

max(a,b) Returns the maximum of a and b

min(a,b) Returns the minimum of a and b


Returns the smallest whole number greater than or equal
ceil(x)
to x.
floor(x) Returns the largest whole number less than or equal to x.

rint(x) Returns the truncated value of x.

round(x) Returns the integer closest to the argument.

Decision Making and Branching


Q. Explain different branching statements available in Java?

In the term software or computer programming, it has a set of instructions called


program. These instructions are also called statements, which occurs sequentially or in either
conditional way or in the iterative way. To handle such types of statements, some flow of
controls required. These flow controls are called control statements.

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;

Here first of all condition will be


checked. If condition is true, then the
true statement block will be executed
and after execution, statement –x will be
executed. Note that both the times
statement –x will be executed.

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;

In this statement block,


first of all condition will be
checked. If condition is true then
true statement block will be
executed and after execution of
the block, statement – x will be
executed. If the condition is
33 | P a g
false then the false statement block is executed followed by statement –x. note that in both
e
the cases statement –x will be executed.
Nested – if statement:

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.

Ladder if statement of if else if statement:

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;

Where e is an arithmetic expression and v is a variable.

35 | P a g
e
Conditional operator (?:):

Conditional operator or also called as ?: operator or ternary operator. This operator is


used instead of block if statement. The general syntax of conditional operator is as:

expr1? expr2: expr3;

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:

c= (a>b)? a-b: b-a;

36 | P a g
e
Decision Making and Looping
Q. Explain different looping statements available in Java?

( or) iterative stetments?

Looping statement:

When a single statement or group of


statements will be executed again and again
in a program (in an iterative way), then such
type of processing is called loop.

Entry Control Loop:

In entry control loop first of all


condition is checked, if it is true, then body of
loop is executed, otherwise the control is
moved out of the loop i.e. we can exit from
the loop, when the condition becomes false.
The while loop and for loops are the example
of the entry controlled loop. The flow symbol for entry control loop is as:

Exit Control loop:

In the exit control loop, first body of


loop is executed and then condition is
checked. If condition is true, then again
body of the loop is executed. If the
condition is false, then control will move out
from the loop. Example of exit control loop
is do statement. The general flow symbol is:

While statement:

While statement or while loop is an


entry control loop. In this, first of all
condition is checked and if it is true, then
group of statements or body of loop is
executed. It will execute again and again till condition becomes false. The general syntax is:

while (test condition)


{
block of statements;
}
statement-x;

Do statement or Do-loop:

Do statement is exit control loop. It is also called do-while statement. In this


statement, first body of the loop is executed and then the condition is checked. If condition is
true, then the body of the loop is executed. When condition becomes false, then it will exit
from the loop. The syntax of do-loop is as follows:

do
{
block of statements;
} while (condition); 37 | P a g
statement-x; e

Note that semicolon must be at the end of the while condition.


c) For statement or for loop:

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:

for (initial value; test condition; increment/ decrement)


{
body of the loop;
}
statement-x;

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.

d) Nested for statement:

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 (initial value1; test condition1; increment1/decrement1)


{
for (initial value2; test condition2; increment2 /decrement2)
{
inner- body of the loop;
}
outer-body of the loop;
}
statement-X;

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

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?

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a


stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Q. Explain about Arrays?

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.

One dimensional Arrays

A list of items given by one name using only one subscript and such variable is called
one-dimensional array.

In Java, single subscripted variable xi can be expressed as

X[0], X[1], X[2],…..The subscript begins with 0.

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.

int num[] = new int [5];

And the computer reserves 5 storage locations as shown below.

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:

In Java Arrays are declared in two forms.

1. Type <array name>[];


2. Type []<array name>;

Ex: int a[]; or int []a;

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.

Syntax: array_name = new type [size];

Ex: a = new int [5];

Initialization of Array:

The final step is to put values into the array created. This process is known as
initialization.

Syntax:

Arrayname [subscript] = value;

ex: num[1]=20;

Type array_name []= {list of values};

Ex: int a[]={10, 20, 30, 40, 50};

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.

Ex: int asize=a.length;

This information is useful in the manipulation of arrays when their sizes are not known.

Passing Array to a Method in Java


42 | P a g
We can pass the java array to method so that we can reuse the same logic on any earray.
Let's see the simple example to get the minimum number of an array using a method.

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);
}

public static void main(String args[])


{
int a[]={9,8,3,1};//declaring and initializing an array
min(a);//passing array to method
}
}

Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.

public class TestAnonymousArray


{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[])
{
printArray(new int[]{1,2,3,4});//passing anonymous array to method
}
} 43 | P a g
e
Two Dimensional Arrays

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.

Type array_name [][];

array_name= new type [row_size][col_size];

Ex: int x[][] = new int [3][2];

Like one-dimensional arrays, two dimensional arrays may be initialized by following their
declaration with a list of initial values as follows.

Type array_name[][] = {list of values};

int x[][]= {{1,2},{3,4},{5,6});

The above declaration automatically initializes the elements into 3 rows and 2 columns in
each row starting index with 0 for row and column.

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In
other words, it is an array of arrays with different number of columns.

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++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
44 | P a g
} e
System.out.println();//new line
}
}
output
012
345
678
Variable sized Arrays

Java treats multidimensional array as “array of arrays”. It is possible to declare a two


dimensional array as follows.

int x[][] = new int [3][];


x[0]= new int[2];
x[1]= new int[4];
x[2]= new int[3];

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’);

String S = new String(name);

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.

String S = new String(name, 3,3);

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

String nameArray[]= new String[5];

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

S1.toLowerCase() Converts the string s1 to lowercase

S1.toUpperCase() Converts the string s1 to uppercase

S1.length() Gives the length of string s1.

S1.charAt(n) Gives nth character of s1.


Gives the position of the first occurrence of ‘x’ in
S1.index(‘x’)
the string s1.
Gives the position of ‘x’ that occurs after nth
S1.index(‘x’, n)
position in the string s1.
S1.equals(s2) Returns ‘true’ if s1 is equals to s2.
Returns ‘true’ if s1=s2, ignoring the case of
S1.equalsIgnoreCase(s2)
characters.
Returns –ve if s1<s2, +ve if s1>s2 and 0 if
S1.compareTo(s2)
s1=s2.
Compares the strings by ignoring the case and
S1.compareToIgnoreCase(s2)
returns above values.
S1.concat(s2) Concatenates s1 and s2, returns new string.s

S1.subString(n) Gives substring from nth character.


46 | P a g
Gives substring from nth character, upto mth
e
S1.subString(n,m)
character.
Function Action

S1.replace(‘x’,’y’) Replaces all appearances of x with y.


Remove white spaces at beginning and end of
S1.trim()
the s1.
p.toString() Creates a string representation of object p.
Converts the parameter value p to string
String.valueOf(p)
representation.

Q) Explain Immutability of strings?

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

S1.setCharAt(n, ’x’) Modifies the nth character to x.

S1.append(s2) Appends the string s2 to the end of string s1.

S1.insert(n, s2) Inserts the string s2 at the position n of string s1.


Sets the length of the string s1 to n. if n<s1 length, s1
S1.setLength(n)
is truncated. If n>s1 length, zeros are added to s1.
This method reverses the character sequence in
S1.reverse()
StringBuffer.

Creating StringBuffer Objects:


There are two ways to create a StringBuffer object and fill the object with a string.
StringBuffer s = new StringBuffer(“sairam”);
Or
StringBuffer s= new StringBuffer();
s.append(“sairam”); (don’t use s=”sai” which gives error, since sai is a string)
Q) Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

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.

4) String class is slower while performing StringBuffer class is faster while


concatenation operation. performing concatenation operation.

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.

 This class methods do not even recognize and skip comments.

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.

StringTokenizer(String str, String delim)


2
This constructor constructs string tokenizer for the specified string.

StringTokenizer(String str, String delim, boolean returnDelims)


3
This constructor constructs 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.

String nextToken(String delim)


6
This method returns the next token in this string tokenizer's string.

package com.myjava.stokenizerr;

import java.util.StringTokenizer;

public class MyStringTokenizer {


public static void main(String a[]){
String msg = "This program gives sample code for String Tokenizer";
StringTokenizer st = new StringTokenizer(msg," ");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}

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.

Needs of the wrapper class:

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.

List of Wrapper Classes:

Primitive data type Corresponding wrapper class


boolean Boolean
char Character
double Double
float Float
int Int
long Long
Ex:
If we create an object ‘C’ to Character wrapper class, it contains a single field char
and it is possible to store a character like ‘A’. So ‘C’ character is a wrapper class of char data
type.

Converting primitive types to Objects using constructor methods:

Constructor calling Conversion Action


Integer Intval= new Integer(v); Primitive integer to Integer object
Float Fltval= new Float(v); Primitive float value to Float object
Double Dbval= new Double(v); Primitive double value to Double object
Long lngval = new Long(v); Primitive long to Long Object

Converting Objects to primitive types using typeValue() method:

Method Calling Conversion Action


int v = Intval.intValue(); Object to primitive integer
float v = Fltval.floatValue(); Object to Primitive float
double v = Dbval.doubleValue(); Object to Primitive double
long v = lngval.longValue(); Object to Primitive long

52 | P a g
e
Converting numbers to strings using toString() method:

Method Calling Conversion Action


Str = Integer.toString(v); Primitive integer to String
Str = Float.toString(v); Primitive float to String
Str = Double.toString(v); Primitive double to String
Str = Long.toString(v); Primitive long to String

Converting string objects to numeric objects using static method valueOf():

Method Calling Conversion Action


Intval = Integer.valueOf(Str); Converts string to integer object
Fltval = Float.valueOf(Str); Converts string to float object
Dbval = Double.valueOf(Str); Converts string to double object
Lngval = Long.valueOf(Str); Converts string to long object

Converting numeric strings to primitive types using parsing method:

Method calling Conversion Action


int v = Integer.parseInt(Str); Converts string to primitive integer
float v = Float.parseFloat(Str); Converts string to Primitive float
double v = Double.parseDouble(Str); Converts string to Primitive double
long v = Long.parseLong(Str); Converts string to Primitive long

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:

return_type method_name (arguments list)


{
Method body;
}

Method declarations have four basic parts:

1. The name of the method.


2. The type of the value, the method returns.
3. A list of parameters (arguments list).
4. The body of the method.

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.

Rectangle rect1 = new Rectangle (); //declare + instantiate

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;

Here both rect1 and rect2 refers to the same object.

Q. How to create an object by the JVM?

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.

Accessing class members:

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.

Ex: rect1.length = 15;


rect1.width = 10;

Rectangle rect1 = new Rectangle( ); //Creating an object


rect1.getData(15,10); // Calling the method using the object

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.

1. Constructor name and class name must be same.


2. Constructor does not return any value. They do not specify a return type, even we
should not write void also.
3. A constructor may or may not have parameters. Parameters are variables to receive
data from outside into the constructor. If a constructor does not have any
parameters, it is called default constructor.
4. If a constructor has one or more parameters, it is called parameterized
constructor.
5. Constructor is automatically called & executed at the time of creating an object.
56 | P a g
6. A constructor is called and executed only once for each object. e
Ex:
class Con1
{
int i,j;
Con1() // constructors without parameters
{
i=20;
j=30;
}
Con1(int a,int b) // constructors with parameters
{
i=a;
j=b;
}
void display()
{
System.out.println(" i value = " + i);
System.out.println(" j value = " + j);
}
}
class MainCon1
{
public static void main(String args[])
{
Con1 abc=new Con1();
con1 xyz=new Con1(10,15);
abc.display();
xyz.display();
}
}

This example demonstrates the default constructor, parameterized constructor and


constructor overloading.

Parameterized Constructor:

The compiler creates a default constructor if we do not specify any constructor. A


constructor can also have certain parameters or arguments; such a constructor is called as
parameterized constructor.

Example for parameterized constructor:


class Test
{
int x;
float y;
Test(int a, float b)
{
x=a;
y=b;
}
void display()
{
System.out.println("values of x and y are = "+x+" "+y);
}
}
public class Demo 57 | P a g
{ e
public static void main(String args[])
{
Test t = new Test(12,11.45f); // instance for class test is created
t.display();
}
}

Copy constructor:
A copy constructor is used to declare and initialize an object with the values of
another object.

Example for copy constructor:


class Rect
{
int l,b;
Rect(int x,int y)
{
l=x;
b=y;
}
Rect(Rect r)
{
l=r.l;
b=r.b;
}
int area()
{
return l*b;
}
}
class CopyCon
{
public static void main(String args[])
{
Rect r1=new Rect(10,4);
Rect r2=new Rect(r1);
System.out.println("rect1 area = " + r1.area());
System.out.println("rect2 area = " + r2.area());
}
}

Constructors with default arguments:

A constructor can also have default arguments. The default arguments of a


constructor will be specified on the right side of the constructor. Whenever an object contains
less number of arguments then the default arguments will be substituted.

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.

How to passing objects to methods?


class Sai
{
int a,b;
Sai(int i,int j)
{
a=i;
b=j;
}
boolean equal(Sai x)
{
if(x.a==a) && (y.b==b))
return true;
else
return false;
}
}
public class Demo
{
public static void main(String args[])
{
Sai p=new Sai(10,22);
Sai k=new Sai(10,22);
Sai q=new Sai(1,2);
System.out.println("object p == object k :" +p.equal(k));
System.out.println("object p == object q :" +p.equal(q));
}
}

Functions returning Objects:


A function can receive arguments and return a value. Functions can receive and
return objects also as a primitive data type. A function returning an object should have the
return type as the class name of the object which it returns.

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);
}
}

Nesting of member functions:

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.

static int count;


static int max(int x, int y);

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.

1. Both variables and methods can be declared as static.


2. Static members can be accessed before any object of the class is created.
3. The variables declared as static are essentially global variables. All instances of the
class share the same static variable.

Methods declared as static have several restrictions.

1. They can only call other static methods. 61 | P a g


2. They must only access static data. e
3. They cannot refer to this or super in any way.
4. We can access the static member by any object or with the class name itself.
The general form of calling static methods is as follows:

Class_name.method_name();

Static Block:

A static block is a block of statements declared as static, something like this:

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");
}
}

Q) Explain Methods in java ?

In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We can
also easily modify code using methods. 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.

What is a method in Java?

A method is a block of code or collection of statements or a set of code grouped together to


perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.

The most important method in Java is the main() method. 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:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

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.

Let's see an example of the predefined method.


Demo.java
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
} 64 | P a g
e
}
Output:
The maximum number is: 9

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

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.

How to Create a User -defined Method


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

//user defined method


public static void findEvenOdd(int num)
{ 65 | P a g
//method body e

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.

How to Call or Invoke a User -defined Method

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:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

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

public class Addition


{
public static void main(String[] args)
{ 67 | P a g
e
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}
Output:
The sum of a and b is= 24

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

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

Example of static method

Display.java

public class Display


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

It is an example of a static method.


Instance Method
The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object of its
class. Let's see an example of an instance method.
InstanceMethodExample.java
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25
There are two types of instance method:
o Accessor Method
o Mutator Method

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();

Example of abstract method


Demo.java
abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}
Output:
Abstract method...
Q) what are factory method in java?

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.

Usage of Factory Design Pattern


o When a class doesn't know what sub-classes will be required to create
o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.

Q. Explain this keyword?

“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.

Q) what is polymorphism? Explain polymorphism with variables?


Polymorphism is one of the main aspects of Object-Oriented Programming(OOP). The word
polymorphism can be broken down into “Poly” and “morphs”, as “Poly” means many and
“Morphs” means forms. In simple words, we can say that ability of a message to be
represented in many forms
Example: A lady can have different characteristics simultaneously. She can be a mother, a
daughter, or a wife, so the same lady possesses different behavior in different situations.

Polymorphism in Java can be achieved in two ways i.e., method overloading and method
overriding.

Polymorphism in Java is mainly divided into two types.


 Compile-time polymorphism
 Runtime polymorphism

Compile-time polymorphism can be achieved by method overloading, and Runtime


polymorphism can be achieved by 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.

Q)Explain Method Overloading or Dynamic polymorphism? Or polymorphism with


private methods?

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

Polymorphism with private methods

Overloading is a one of the mechanisms to achieve polymorphism where, a class contains


two methods with same name and different parameters.

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);
}
}

Q)Explain static polymorphism?

Polymorphism that is resolved during compiler time is known as static polymorphism.


Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same
name, if the parameters of methods are different in number, sequence and data types of
parameters. We have already discussed Method overloading here:
Example of static Pol ymorphism
Method overloading is one of the way java supports static polymorphism. Here we have
two definitions of the same method add() which add method would be called is determined
by the parameter list at the compile time. That is the reason this is also known as compile
time polymorphism.
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo 74 | P a g
{ e
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
Output:
30
60
Q)What is the difference between Static & Dynamic Polymorphism?

Static Polymorphism Dynamic Polymorphism


It is achieved through method overloading. It is achieved through method overriding.

It is called compile-time polymorphism. It is called runtime polymorphism.

Known as static binding or early binding. Known as dynamic binding or late binding.

It has a high execution speed. It has a low execution speed.

Q) Explain about casting primitive data types?


Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type casting.
It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes place
when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is
not done automatically. Also, the char and Boolean data types are not
compatible with each other. Let's see an example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type 75 | P a g
long y = x; e
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a long
type. After that, the long type is converted into the float type.
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting.
It is also known as explicit conversion or casting up. It is done manually by
the programmer. If we do not perform casting then the compiler reports a
compile-time error.
double -> float -> long -> int -> char -> short -> byte

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.

public class NarrowingTypeCastingExample


{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}

Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 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();
}
}

Q Explain about object class with example?


There is a class with name ‘Object’ in java.lang package which is the super
class of all classes.
Object class has below methods
toString() Method.-> returns the String representation of the object.

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

getClass() method.-> returns the runtime class of this object.

finalize() method.->T his method is called just before an object is garbage


collected. finalize() method overrides to dispose system resources, perform
clean-up activities and minimize memory leaks.

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

wait(), -> is a part of java.lang.Object class. When wait() method is called,


the calling thread stops its execution until notify()

notify()-> If many threads are waiting on this object

notifyAll() Methods.->this method sends a notification for all waiting threads


for the object.
Q. Write short notes on Vectors?
The feature can also be achieved in J2SE 5.09 version use the vector class
contained in the Java.util package. Vectors can hold only objects of array type
and any number not a primitive type (int). The objects do not have to be
homogeneous. Vectors are created like arrays as follows.

Vector v = new Vector() // declaring without size.


Vector list = new Vector(10); // declaring with size.

Vectors possess a no. of advantages over arrays.

1. It is convenient to use vectors to store objects.


2. A vector can be used to store a list of objects that may vary in size. 78 | P a g
e
3. We can add and delete objects from the list as and when required.
4. We can’t directly store simple data type in a vector.
5. We can only store objects. Therefore we need to convert simple types to
objects. This can be done by using wrapper class.

Some methods support vector classes can be used to manipulate the vectors
created.

Method Call Task performed


list.addElement(item) Adds the specified item to the list at end
List.elementAt(10) Gives the name of the 10th object.
List.size() Gives the no. of objects present.
List.removeElement(item) Removes the specified item from the list
removes the item stored in the nth position of
List.removeElementAt(n)
the list
List.removeAllElements() Removes all the elements in the list
List.copyInto(array) Copy all the items from list to array
List.InsertElementAt(item,n) Inserts the item at nth position.
Ex: convert a string vector into array of strings.
import java.util.*;
class Lang
{
public static void main(String args[])
{
Vector list = new Vector();
int length = args.length;
for (int i=0; i<length; i++)
{
list.addElement(args[i]);
}
list.insertElementAt("COBOL",2);
int size = list.size();
String a[] = new String[size];
list.copyInto(a);
System.out.println("list of languages");
for (int i=0;i<size;i++)
System.out.println(a[i]);
}
}

Q. Explain Enumerated Data Types?


J2SE 5.0 allows us to use the enumerated type in Java using enum keyword.
The enum type is a type whose fields consist of a fixed set of constants. This
keyword can be used similar to the static, final constants. The advantages of
enumerated data types are
1. Compile time type safely.
2. We can use the enum keyword in switch statement.
79 | P a g
e
Ex:
public class workingdays
{
enum Days
{
sunday,
monday,
wednesday,
thursday,
friday,
saturday
}
}
private static void weekend(Days d)
{
if (d.equals(Days.sunday))
System.out.println("value " + d + " is a Holiday");
else
System.out.println("value " + d + " is a working day");
}

public static void main(String args[])


{
for(Days d:Days.values())
{
weekend(d);
}
}
Q. What is Inner class and Outer classes?
Inner classes called as the nested classes. Inner classes are classes which are
declared in another class. They are also used to implement details of an
implementation that should not be shared by any other class.
public class Outer
{
int i;
void method1()
{
--------
--------
}
public class Inner
{
int p;
void method2()
{
--------
--------
} 80 | P a g
} // inner class close e
}// outer class close
The outer class declares a variable ‘i’, the inner class declares a variable ‘p’. ‘i’
can refer from the inner class, but ‘p’ cannot be referred by outer class.
Some properties of Inner Classes:
1. We can use the class name only within the defined scope. The name of the
inner class must differ from the outer class.
2. The inner class can use both class and instance variable of enclosing
classes and final local variables of enclosing blocks.
3. The inner class can be defined as abstract.
4. The inner class can have of any access specifier.
5. The inner class can act as an interface implemented by another inner
class.
Ex:
class Outer
{
int i=30;
int j=90;
void display()
{
System.out.println("outer j value = " + j);
}
void create()
{
Inner obj= new Inner();
obj.show();
}
class Inner
{
int r=43;
void show()
{
System.out.println("inner r value = " + r);
System.out.println("outer i value = " + i);
display();
}
}//inner close
}//outer close
class MainClass
{
public static void main(String args[])
{
Outer x=new Outer();
x.create();}}

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)

Java does not directly implement multiple inheritance. However,


this concept is implemented using Interfaces.
Defining a Subclass:
class subclass_name extends superclass_name
{
Variables;
Methods;
}

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

Q. Explain Final variables?or polymorphism with final methods?


Final Variable:
Final variable value can never change when the program executed it is
similar to constant. A final keyword can be used to the variable that variable
value maintains the fixed value throughout the entire program.
Ex: final double PI = 3.14;
Final Method:
Making a method final ensures that the functionality defined in this
method will never be altered in any way. That is this functions cannot be
overridden by derived classes.
final void show()
{
------
------
}
Final classes: A class that cannot be sub classed or it cannot be inherited
by any other classes, the class should be defined as final class.
Ex:
final class Aclass
{
Variables;
Methods;
}
Q. Write about Abstract Classes and Abstract Methods?
Methods which are incomplete, then those methods are called abstract
methods. A class that which contains this type of methods is known as Abstract
class. This type of classes should be specified with abstract keyword.
86 | P a g
Abstract Method Declaration e
abstract return_type method_name(parameters);
he declaration of abstract methods in the abstract class must be specified with
the keyword abstract as follows.
abstract class A
{
abstract void m1();
void m2()//concrete method
{
some code;
}
}
If there is at least one single abstract method in a class then the class must be
declared as abstract class.

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.

Ex: Display date and time


import java.util.*;
interface Inte
{
void display();
}
class Class1 implements Inte
{
public void display()
{
Date d= new Date(); // Date is an abstract class in java.util package
//object d contains the system date and time
System.out.println(d);
}
} 89 | P a g
e
class Interface
{
public static void main(String args[])
{
Inte abc;
Class1 c= new Class1();
abc=c;
abc.display();
}
}
Ex: polymorphism using interface.
This also explains how to create reference to interface and use that reference on
objects.
interface Inte
{
void show(int n);
}
class Class1 implements Inte
{
public void show(int n)
{
System.out.println("square value = " + n*n);
}
}
class Class2 implements Inte
{
public void show(int n)
{
System.out.println("cube value = " + n*n*n);
}
}
class Ip
{
public static void main(String args[])
{
Inte ref;
Class1 c1=new Class1();
Class2 c2=new Class2();
ref=c1;
ref.show(5);
ref=c2;
ref.show(6);
}
}
//Multiple Inheritance through Interface
interface Father
{
int fp=300000; 90 | P a g
e
float fht1=6.5f;
void property();
void height();
}
interface Mother
{
int mp=250000;
float mht2=5.5f;
}
class Child implements Father, Mother
{
public void property()
{
System.out.println("child property = " + (fp+mp));
}
public void height()
{
System.out.println("child height = " + (fht1+mht2)/2);
}
}
class M1
{
public static void main(String args[])
{
Father f1;
Child ch=new Child();
f1=ch;
f1.property();
f1.height();
}
}
//Hybrid Inheritance
class Student
{
int no;
void getno(int n)
{
no=n;
}
void show()
{
System.out.println(no);
}
}
class Test extends Student
{
float p1, p2;
void getm(flaot m1, float m2)
{
p1=m1; 91 | P a g
p2=m2; e
}
void showm()
{
System.out.println(p1);
System.out.println(p2);
}
}
interface sports
{
float s=6.0f;
void putw();
}
class Result extends Test implements Sports
{
float total;
public void putw()
{
System.out.println(s);
}
void display()
{
total=p1+p2+s;
show();
showm();
putw();
System.out.println(total);
}
}
class Hybrid
{
public static void main(String args[])
{
Result s1=nwe Result();
s1.getno(11);
s1.getm(37.8f, 45.7f);
s1.display();
}
}
Q. Write the difference between Interface and Abstract classes.
All the methods in interface are abstract methods. Abstract class contains
abstract methods and concrete methods.

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>

Similarly for abstract classes, we use the keyword “extends” as follows.


class <class_name> extends <abstract_class_name>
We can not create object for both interfaces and abstract classes, rather than we
can create reference for that. By using this references, we can refer the objects
for corresponding classes.

Multiple inheritance can be achieved by using interfaces. But by using abstract


classes we can’t achieve this goal.

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 packages are classified into two types.


1. Java API packages.
2. User defined packages.

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

lang util io awt net applet


93 | P a g
F IGURE 8: F REQUENTLY USED API P ACKAGES e
T ABLE 1:J AVA S YSTEM P ACKAGES AND T HEIR C LASSES
Package name Contents
Language support classes. These are classes that Java
compiler itself uses and therefore they are automatically
java.lang imported. They include classes for primitive types,
strings, math functions, threads and exceptions.
Language utility classes such as vectors, has tables,
java.util
random numbers, data etc.
Input/output support classes. They provide facilities for
java.io
the input and output of data.
Set of classes for implementing graphical user interface.
java.awt They include classes for windows, buttons, list, menus
and so on.
Classes for networking. They include classes for
java.net communicating with local computers as well as with
internet servers.
java.applet Classes for creating and implementing applets.

A package is to be included in the user application so that the predefined


classes can be used to achieve this. One can use a keyword called “import”.

Syntax: import package_name.*;


A user defined package may be created by using the keyword “package”.
Syntax: package <package_name>;
Creating a package involves the following steps:
1. Declare the package at the beginning of the file using the form package
<package_name>;
2. Define the class that is to be put in the package and declared in public.
3. Creating the sub directory under the directory where the main source of
files is stored.
4. Store the listing as the class_name.java files in the sub directory created.
5. Compile the file. This creates class file in the sub directory.

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.

Hiding classes in Package:


package p1;
public class X
{
}
class Y
{
}
Here the class Y which is not declared as public, it is hidden from outside of the
package p1. 95 | P a g
import p1.*; e
X obj1;//it is ok
Y obj2;// it is not ok because Y is not a valuable
/* write a Java program to create two packages to import to one class */
package p1;
public class Sri
{
public void show()
{
System.out.println("sri class");
}
}
package p2;
public class Sai
{
public void display()
{
int m=420;
System.out.println("Sai class");
System.out.println(m);
}
}
import p1.Sri;
import p2.Sai;
class Pack
{
public static void main(String args[])
{
Sri ob=new Sri();
ob.show();
Sai ob1=new Sai();
ob1.display();
}
}

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.

We should handle these types of exceptions using Exception Handler blocks.


Based on Exception statement JVM creates an object internally for unchecked
exceptions and it propagates. We should handle the propagated exceptions
using Exception handler blocks. Otherwise it terminates the application. To
handle the Unchecked Exceptions Java provides 5 keywords.
1. try
2. catch
3. finally
4. throw
5. throws

The General Form of Exception Handling mechanism


The basic concepts of exception handling are throwing an exception and
catching it. This is illustrated in the following figure.

try Block Exception object


creator
Statement that causes
an exception

Throws
exception
object

catch Block Exception


handler
Statement that handles
the exception

F IGURE : E XCEPTION HANDLING MECHANISM

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
}
.. .. .. .. ..
.. .. .. .. ..

Program for using try and catch for exception handling


class Error4
{
public static void main(String args[ ])
{
int a[ ] = {5,10};
int b = 5;
int x,y;
try
{
x = a[2]/b-a[1];
}
catch (ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch (ArrayStoreException e)
{ 101 | P a g
System.out.println(“Wrong data type”); e
}
y = a[1]/a[0];
System.out.println(“y = “+y);
}
}
Output:
Array index error
y=2

Q. What is the tostring()?


This is the generalized method defined in Object class. Object is the super class
for all classes. This object contains some methods. toString() is one of the
method in that Object class. Using toString() we can define our own class
descriptions. By overriding this in our class we can write our own descriptions
for our class unless it returns the hash code of the object.
Ex:
class Emp
{
public String toString()
{
return"This is Emp Class";
}
};
class ExOnToString
{
public static void main(String args[])
{
Emp e=new Emp();
System.out.println(e); //this is Emp class
}
}
Q. What is Final, Finally and Finalize and throws?
Final:
When we declare a subclass as final the compiler will give error as "cannot
define subclass as final". Final is used to prevent the inheritance and method
overriding.
 Final class cannot have static methods
 Final class cannot have abstract methods
 Final class can have a final method
Finally:
Finally create a block of code that will be executed after try catch block
has completed. Finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch
statement match the exception.
Finalize:
Sometimes an object need to perform some actions when it is going to
destroy, if an object holding some non java resource such as file handle(or)
window character font, these resources are freed before the object is going
102 | Pto
ag
destroy. e
Throws:
If we not handle runtime exceptions, the java compiler will not give any error
related to runtime exceptions. But the rule is that we must handle checked
exceptions in case if we not interest to handle the checked exceptions, we can
throw them using throws keyword. Otherwise, there will be an error flagged by
Java compiler.
Ex:
import java.io.*;
class ExOnThrows
{
public static void main(String args[])throws IOException
{
int a,b,c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a,b values:");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println("sum is:"+c);
}
}
Q. What is the difference between throw and throws?
'throws' class is used when the programmer does not want to handle the
exception and throw it out of a method. 'throw' class is used when the
programmer wants to throw an exception explicitly and wants to handle it using
catch block. Hence, throw and throws are contradictory (quite opposite).

Q) Explain Re- throwing an Exception with examples?


when an exception occurs in try block, it is caught by catch block. This means
that the thrown exception is available to the catch block.
class sai
{
void show()
{
try
{
String str=”sairam”;
char ch=str.charAt(3);
}
catch(StringIndexOutOfBoundsException e)
{System.out.println(“please see the index is with in the range”);
throw e;
}
}
103 | P a g
e
class baba
{
public static void main(String args[])
{
sai x= new sai();
try
{
x.show();
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(“I caught re throw exception”);
}
}
}

Q) Write short notes on Hashmap and Hash Table?


Hash map is a collection that store elements in the form of key value pairs . if
key is provided later, its corresponding value can be easily retrieved form the
hash map key should be unique. this means we can't use duplicate data for key
in the hash map however, hash map is not synchronized and hence while using
multiple threads on hash map objects ,we get unreliable results we can write
hash map class are:
class hashmap<k,v>
where k is represents the type of key element and v is represent the type of
value element.

Hashmap class methods:


1)put(key value): This method stores key value pairs into the hashmap.
2)get (object,key): This method returns the corresponding value when key is
given. if key is not value it retuns null.
3)Set<k>keySet():This method when applied on a hashmap coverts it into a set
where only keys will be stored.
4)collection <v> values():This method when applied on a hashmap o0bject
returns all values of the hashmap into a collection objects
5) remove (object,key): Removes the key and corresponding value from the
hashmap .
6)void clear(): Removes all the key value pairs form map.
7)boolean is empty(): It returns true if there are no key value pairs in the
hashmap.
8)int size(): It returns number of key value pairs in the hashmap.
104 | P a g
e
hash table class:
hash table is similar to hash map which can store elements in the form of key
value pairs but hash table is synchronized assuming proper results even if
multiple threads act on it simultaneously.
Declare:
class hashtable <k,v>
where k is represents tha type of key element and v represents the type of value
elements.
Q)What is the difference between hashmap and hashtable?

hashmap hash table


1)hashmap object is not synchronized 1)hash table object is synchronized
by default by default
2)It is single thread 2)It is multi threads
3)faster 3)slow
4)hashmap allows null keys and null 4)hash table not allowed null
values and null keys values to be stored
5)iterator in the hashmap is fail fast 5)enumeration for the hashtable is
not fail fast

3)what is the difference between set and list?


set list
1)A set represents a collection of elements, 1)ordered collection of elements
list order of elements may change
in the set the order of elements in
which they are enterd

2)Not allowed duplicate values 2)allow duplicate values

3)not allow null elements 3)allow null elements to be stored

4)accessing elements by their index is not 4)accessing elements by their


index is possible possible

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 ()

Running Idle Stopped


Display Start ()

Paint () Destroy ()

Destroyed Dead End


106 | P a g
e
Initialization State:
The initialization occurs only once in the applets life cycle to provide any of
the behavior as mentioned above. We must override the init() method
public void init()
{
........
........(action)
}
Running State:
Applet enters the running state when the system calls the start() method
of applet class. This occurs automatically after the applet is initialized. Starting
can also occur if the applet is already stopped (idle) state. For ex:-we may leave
the webpage containing the applet temporarily to another page and return back
to this page. This again starts the applet running note that unlike init() method.
The start() method may be called more than once. We may override the start()
method to create a thread to control the applet.
public void start()
{
.........
.........(action)
}
idle or stopped state:
An applet becomes idle when it is stopped from running. stopping occurs
automatically when we leave the page containing the currently running applet.
We can also do so by calling the stop() method to terminate the Thread we can
achieve this by overriding the stop() method.
public void stop()
{
........
........(action)
}
Dead state:
An Applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when we quit the browsers like
initialization destroying stage occurs only once in the applets lifecycle if the
applet has created any resources, like threads. We may override the
destroy()method to clean up these resources
public void destroy()
{
.......
.......(Action)
}
Display State:
Applet moves to the display state whenever it has to perform some output
operation on the screen.This happens immediately after the applet enters into
the running state.The paint()method is called to accomplish this task.Almost
every applet will have a paint() method like other method in the life cycle.The
default version of paint() method does absolutely nothing we must therefore 107 | P a g
override this method if we went anything to be displayed on the screen. e
public void paint(Graphics g)
{
.......
.......(Display Statements)
}
It is to be noted that the display state is not considered as a part of the
applets lifecycle. In fact the paint() method is defined in the applet class. It is
inherited from the component class, a super class of applet.
//Write a simple java applet program
import java.awt.*;
import java.applet.*;
public class Myapp extends Applet
{
public void init()
{
setBackground(Color.yellow);
}
public void paint(Graphics g)
{
g.drawString("baba is great",50,100);
}
}
Compile the java program:
<html>
<applet code="Myapp.class"height=300 Width=500>
</applet>
</html>
Q. What are the steps involved in developing, testing in applets?
1. Building an applet code
2. Creating an execute applet(class file)
3. designing a web using HTML tags
4. preparing an applet tags
5. Incorporating applet tag into the web page
6. Creating HTML file
7. Testing the applet code with the applet viewed(file name,HTML)
Animations in Applet:
Image img=getImage(SetDocumentBase(),"a.gif");
Here image class belongs to java.awt package and getImage method
belongs to applet class. get document Base() is a method of an applet class that
gives directory path. Where the image is located.
g.drawImage(img,x,y,obj);
x and y represents the coordinates starting from where the image should be
displayed.obj represents image observer which stores into the memory. Since
this is not needed we can pass in its place.
//program
import java.awt.*;
import java.applet.*;
public class Animate extends Applet 108 | P a g
{ e
public void paint(Graphics g)
{
Image img=getImage(getDocumentBase(),"a.gif");
for(int x=0;x<800;x++)
{
g.drawImage(img,x,0,null);
try
{
Thread.sleep(20);
}
catch(InterruptedException e){}
}
}
}

compile: javac Animate.java


<html>
<applet code="Animate class"height=300,width=500>
</applet>
</html>
appletviewer Animate html
Q. What are the uses of applets?
1. Applets can be used for multiple purpose.
2. Applets are used on internet for creating a dynamic web pages.(These are
of two types of webpages one is static and dynamic)User cannot interact
with the page dynamic.
3. Applets are used for creating animations and games.
Q. What are Applet parameters?
Applet tag can be used param tag to pass information’s to applet to
recieve the values of the parameters. An applet uses get parameters.
Ex:
import java.applet.*;
import java.awt.*;
public class Tax extends Applets
{
String name,str;
float sal,tax;
public void init()
{
name=getParameter("t1");
str=getParameter("t2");
sal=Float.parseFloat(str);
cal(sal);
}
public void cal(float sal)
{
if(sal<=1000000)
tax=0.0f;
else 109 | P a g
if(sal<=200000) e
tax=sal*0.1f;
else
tax=sal*0.2f;
}
public void paint(Graphics g)
{
g.drawString("Hello"+name,20,100);
g.drawString("your salary:"+sal,20,120);
g.drawString("pay the Tax:"+tax,20,140);
}
}
compile: javac Tax.java
<html>
<applet code="Tax.class"height=300,width=200>
<param name ="t1"value="kumar">
<param name ="t2"value="15000">
</applet>
</html>
Q. What is Abstract Window tool kit?
It represents a class library to develop applications using graphical user
interface. The java.awt package got a classes and interface to develop GUI and
let the user interact in a more friendly way with the application.
//Write a program to create a frame by creating an object to Frame class
import java.awt.*;
class MyFrame
{
public static void main(String args[])
{
Frame f=new Frame("My AWT Frame");
f.setSize(300,500);
f.setVisible(true);
}
}
//Write a program to create a frame by creating an object to subclass of
Frame class
import java.awt.*;
class MyFrame2 extends Frame
{
MyFrame2(String str)
{
super(str);
}
public static void main(String args[])
{
MyFrame2 f=new MyFrame2("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
}
} 110 | P a g
e
Q)HOW TO DESIGNING A WEB PAGE
Recall that Java applets are programs that reside on Web pages. In order
to run a Java applet, it is first necessary to have a Web page that references
that applet.
A web page is basically made up of text and HTML tags that can be
interpreted by a Web browser or an applet viewer. Like Java source code, it can
be prepared using any ASCII text editor. A Web page is also known as HTML
page or HTML document. Web pages are stored using a file extension .html
such as MyApplet.html. Such files are referred to as HTML files. HTML files
should be stored in the same directory as compiled code of the applets.
Web pages include both text that we want to display and HTML tags
(commands) to Web browsers. A Web page is marked by an opening HTML tag
<HTML> and closing HTML tag </HTML> and is divided into the following three
major sections:

1) Comment section (Optional)


2) Head section
3) Body section

<HTML>

<!
............. Comment
............. Section
>

<HEAD>
Head
Title Tag
Section
</HEAD>

<BODY>

Applet Tag Body


Section
</BODY>

</HTML>

F IGURE 9: A W EB PAGE TEMPLATE

Comment Section 111 | P a g


This section contains comments about the Web page. It is important
e to
include comments that tell us what is going on in the Web page. A comment line
begins with a <! and end with a >. Web browsers will ignore the text enclosed
between them. Although comments are important, they should be kept to a
minimum as they will be downloaded along with the applet. Note that comments
are optional and can be included anywhere in the Web page.

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>

The body shown above contains instructions to display the message


Welcome to the World of Applets
followed by the applet output on the screen. Note that the <CENTER> tag makes
sure that the text is centered and <H1> tag causes the text to be of the largest
size. We may use other heading tags <H2> to <H6> to reduce the size of letters
in the text.
112 | P a g
APPLET TAG e
<APPLET> tag discussed above specifies three things:
1) Name of the applet
2) Width of the applet (in pixels)
3) Height of the applet (in pixels)

<APPLET
CODE = helloJava.class
WIDTH = 400
HEIGHT = 200 >
</APPLET>

ADDING APPLET TO HTML FILE

<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>

Q. What is event delegation model?


Event delegation model represents that when an event is generated by the
user on a component, it is delegated to a listener, and interface and listener
calls a method in response to the event. Finally the event is handled by the
method.
Ex: 113 | P a g
WindowListener interface calls the public void windowClosing() method
e
when the Frame is being closed.
Syntax:
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
//Write a program which first creates a frame and then closes it on
clicking the close button
import java.awt.*;
import java.awt.event.*;
class MF3 extends Frame
{
public static void main(String args[])
{
MF3 f=new MF3();
f.setTitle("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new Myclass());
}
}
class Myclass implements WindowListener
{
public void WindowActivated(WindowEvent e)
{
}
public void WindowClosed(WindowEvent e){}
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
public void WindowDeactivated(WindowEvent e){}
public void WindowDeiconified(WindowEvent e){}
public void WindowIconified(WindowEvent e){}
public void WindowOpened(WindowEvent e){}
}
Q. What are the advantages of event delegation model?
The components and action part can be developed in two
Ex:
1. We can create the components in java and action logical can be developed
in visual basic.
2. We can modify the code for creating the component without modifying the
code for action part of the component. Similarly we can modify the action
part without modifying the code for the component.
Q. What is an adapter class?
An adapter class is an implementation class of a listener interface which
contains all methods implemented with empty body.
Ex:
WindowAdapter is an adapter class of WindowListener interface. Adapter
classes reduce overheads on programming while working with listener interface.
114 | P a g
Syntax: e
MyFrame f;
f.addWindowListener(new WindowAdapter)
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
});
//Write a program to close the frame using window adapter class
import java.awt.*;
import java.awt.event.*;
class MyFrame3 extends Frame
{
public static void main(String args[])
{
MyFrame3f=new MyFrame3();
f.setTitle("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new Myclass());
}
}
class Myclass extends WindowAdapter
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
}
In the above program the code of myclass can be copied directly into
addWindowListener method
import java.awt.*;
import java.awt.event.*;
class MyFrame3 extends Frame
{
public static void main(String args[])
{
MyFrame3f=new MyFrame3();
f.setTitle("My AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new Myclass());
}
}
f.addWindowListener(new WindowAdapter)
{
public void WindowClosing(WindowEvent e)
{
System.exit(0); 115 | P a g
} e
});
//Write a program that allows you to fill the shapes with some colours
//drawing a smiling face in a frame with filled colours
import java.awt.*;
import java.awt.event.*;
class MyFrame6 extends Frame
{
MyFrame6()
{
this.addWindowListener(new WindowAdapter())
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(40,40,200,200);
g.setColor(Color.yellow);
g.fillOval(90,70,80,80);
g.setColor(Color.black);
g.fillOval(110,95,5,5);
g.fillOval(145,95,5,5);
g.drawLine(130,95,130,115);
g.setColor(Color.red);
g.fillArc(113,115,35,20,0,-180);
}
public static void main(String args[])
{
MyFrame6 d=new MyFrame6();
d.setSize(400,400);
d.setTitle("My drawing");
d.setVisible(true);
}
}

//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");
}
}

//push buttons -version2


import java.awt.*;
import java.awt.event.*;
class Mybuttons1 extends Frame implements ActionListener
{
Button b1,b2,b3;
Mybuttons1()
{
setLayout(new FlowLayout());
b1=new Button("Yellow");
b2=new Button("Blue");
b3=new Button("Pink");
add(b1);
add(b2); 117 | P a g
add(b3); e
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
addWindowListener(new WindowAdapter())
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
setBackground(Color.yellow);
if(ae.getSource()==b2)
setBackground(Color.blue);
if(ae.getSource()==b3)
setBackground(Color.pink);
}
public static void main(String args[])
{
Mybuttons1 mb=new Mybuttons1();
mb.setSize(400,400);
mb.setTitle("Mybuttons");
mb.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:

 JApplet: An extension of Applet class, it is the Swings version of Applet.


 JFrame: An extension of java.awt.Frame class.
 JButton: Helps to a push button in Swings.
 JTabbedPane: Helps to a tabbed pane in Swings
 Jtree: Help to a hierarchical (tree) structure in Swing.
 JComboBox: Helps to a combo boxes in Swing.

Q. How many layout managers in the awt package?


1. Border Layout: The container area will be divided into 5 parts
2. Flow Layout: The container will be divided into rows and columns
depending upon the components and their sizes.
3. Grid Layout: The container is divided into specific number of rows and
columns of equal size. Only one component can be added to grid and the
120 | P a g
component occupies entire the grid. e
4. Card Layout: It helps us to add the components to a frame i.e., one
component behind the other.
5. Panel: It can add any number of components to the panel.
Q. Why should we use applets, when we have an easy alternative?
Whenever it is required to hide the source code, the we prefer applets to
display the gui(Graphical user interface) rather than using HTML.
In other words the disadvantage in HTML is that in browser if we click
view source option then the HTML code will be visible to the user but applets
code could not be visible.
Q. What are the disadvantages of AWT?
1. AWT programs increases the overhead on the JVM.
2. They make java to be platform dependent.
3. The above disadvantage of overcoming in swings(light weightcomponent)
AWT(heavy weight component).
Q. What is an event?
An event is an unexpected external happening in the context of hardware.
For example, when we press a key the electronic deviser inside the keyword
interrupt the system to send the key code. So that the system responds
immediately by halting what event it was doing.
Q. What is event delegation and Listeners?
The process of assigning an object to handle the event is called event
delegation, the event handling objects are called Listeners. There are two ways
of delegation an event to the listener
1. Delegation an event to the external object.
2. Delegation to some object
Q. What are different Listeners?
1. ActionListener
2. TextListener
3. ItemListener
4. WindowListener
5. KeyListener
6. FocusListener
7. AdjustementListener
8. MouseListener
9. MousemotionListener
//Write a program to close the Frame using anonymous inner class
//creating a frame and closing it
import java.awt.*;
import java.awt.event.*;
class Myframe5 extends Frame
{
public static void main(String args[])
{
MyFrame5 f=new MyFrame5();
f.setTitle("MY AWT Frame");
f.setSize(300,250);
f.setVisible(true);
f.addWindowListener(new WindowAdapter())
{
public void WindowClosing(WindowEvent e) 121 | P a g
{ e
System.exit(0);
}
});
}
}
//Write a java applet program interact input to an applet
import java.awt.*;
import java.awt.event.*;
public class some extends Applet
{
TextField t1,t2;
public void init()
{
t1=new TextField(8);
t2=new TextField(8);
add(t1);
add(t2);
t1.setText("0");
t2.setText("0");
}
public void paint(Graphics g)
{
int x=0,y=0,z=0;
String s1,s2,s3;
g.drawString("enter input numbers in each block ",10,50);
try
{
s1=t1.getText();
x=Integer.parseInt(s1);
s2=t2.getText();
y=Integer.parseInt(s2);
}
catch(Exception e){}
z=x+y;
s3=String.valueOf(z);
g.drawString("The sum is",10,80);
g.drawString(s3,100,80);
}
public Boolean action(Event event,Object object)
{
repaint();
return true;
}
}
<HTML>
<appletcode="Some.class"width=300height=200>
</applet>
</HTML>
//write a marquee command using HTML 122 | P a g
<html> e
<head>
<title>
using marquee command
</title>
</head>
<body>
<marquee
align="top"loop="infinite"behaviour="bounce"bgcolor="red"direction="LEFT">
<h2>
ABHYUDAYA COLLEGE
</h2>
</marquee>
<center>
<h1>
KUMAR
</h1>
</center>
<marquee align="left"loop="infinite"behaviour="scroll"bgcolor="blue"height=40
width=30 direction="down">
<h2>
SAI DURGA
</h2>
</marquee>
<marquee align="top"loop="infinite"behaviour="slide"bgcolor="green"
width=100% direction="right">
<h2>
VIJAYA DURGA
</h2>
</marquee>
</body>
</html>

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.

 A thread is a sequential flow of control within a program. Every program


has at least one thread i.e., called primary thread
 *Applications having only one thread is called single thread module.
 *The current thread( )method retrieves the reference of the current thread.
 *multi thread applications have more than one thread.
 *The thread class is used to create and manipulate the threads in a
program.
 *You can use the thread class or the runnable interface to implement the
thread
A THREAD CAN HAVE THE FOLLOWING STATES:
New thread:
When an instance of thread class is created the thread enters into the new
thread state.
Runnable:
When the start()method is invoked the thread enters into runnable state.
Not runnable:
The thread is said to be not runnable state if it is in:
 sleeping
 waiting
 being blocked by another thread(yielding)
Dead:
 A thread can be either dead naturally or killed a natural death when the
loop in the run() method is completed.
 the start()method of the thread class is used to start the thread
 The run()method contains the code which the thread executes
 The thread can be put to sleep using the sleep()method
 The threads are scheduled based on the priorities.
 The synchronized keyword is used to ensure that no threads access the
same object simultaneously
 The methods wait(),yield(),notify(),notifyAll() are used for inter-thread
communication
Mutex:
It is an object that is locked till a thread completes execution.
Q. Explain the life cycle of threads?
During the life time of a thread there are many states .they include :
1. New born state
2. Runnable state
3. Running state
4. Blocked state

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 state:


When we create a thread object then the thread is said to be new born state.
The thread is not yet scheduled for running. At this state we can do only one of
the following things.
1. One is scheduled it for running using start() method.
2. Kill it using stop() methods.

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

Running Thread Runnable Threads


Running state:
Running means that the processor has given its time to the threads for its
execution the thread runs until it relinquishes control on its own (or) it is
prompted by a higher priority thread.
Suspend

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)

Running Runnabl Suspend


e
certain reason. But do not want to kill it.
We can put a thread to sleep for a specified time period using the method
sleep() sleep(time)
Here time is milliseconds; the thread reenters the runnable state as soon
as time period is collapsed.
wait

notify

Running Runnable Suspend


The wait() method that the thread can be scheduled to run again using
notify() method.
BLOCKED STATE:
A thread is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running state this happens when the
thread is suspended. Sleeping or waiting in order to satisfy certain
requirements.
A blocked thread is considered "not runnable" but not dead and therefore
fully qualified to run again.
DEAD STATE:
Every thread has a life cycle. A running thread ends its life when it has
completed executing its run() method. It is naturally death. However we can kill
it by sending stop message to it at any state. Thus causing a premature death to
it.
126 | P a g
A thread can be killed as soon it is born or while it is running ore even
when it is in "not runnable" condition.
**********************
//WRITE A PROGRAM TO CREATE A MyThread class with run() method.
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<10;i++)
{
System.out.println(i);
}
}
}
class Demo1
{
public static void main(String args[])
{
MyThread obj=new MyThread();
Thread t=new Thread(obj);
t.start();
}
}
//2. PROGRAM
class th1
{
public static void main(String args[])
{
thread t=Thread.currentThread();
System.out.println(t);
System.out.println(t.getname());
}
}
//3. PROGRAM
class Th2
{
public static void main(String args[])
{
try
{
for(int i=0;i<10;i++)
{
Thread.sleep(1000);
System.out.println (i);
}
}
catch(Exception e)
{
e.printStackTrace();
} 127 | P a g
} e
}
//write a program to find a thread used by JVM to execute the statement
class it1
{
Public static void main(String args[])
{
System.out.println ("current thread");
Thread t=Thread.currentThread();
System.out.println (t);
System.out.println ("its name is ="+t.getname());
}
}
current thread()is a static method in a thread class. so we call it as
Thread current Thread. this method gave an object t of Thread class we display
this object t.
Thread[main,5,main]
Here 5 is a no.priority.1st main indicates the of the thread running the current
code.
The next main indicates the main Thread belongs to the main thread group. its
name can be known using t.getName().
//write a program to create empty class with run method and then
attached to thread to this empty class object
class empty extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
System.out.println (i);
}
}
class it2
{
Public static void main(String args[])
{
System.out.println ("current Thread");
empty ob=new empty();
Thread t=new Thread(ob);
t.start();}}

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.

//Write a program to terminate the thread by passing the button


import java.io.*;
import java.lang.*;
class empty1 extends Thread
{
boolean stop=false;
public void run()
{
for(int i=1;i<1000;i++)
{
System.out.println (i);
if(stop)
return;
}
}
}
class it3
{
p.s.v.m(String args[])
{
System.out.println ("current thread");
empty1 ob=new empty1();
Thread t=new Thread(ob);
t.start();
ob.stop=true;
}
}
Explanation:
In the above program,we create a boolean type variable and initialize it to false.
boolean stop=false
*If we want to terminate the thread by pressing the enter key
stop=true;
Check this variable in run() mathod when it is true make the thread return from
the run() method
public void run()
{
if(stop==true)
return;
}
// Write a java program for execution of multitask with a single thread 129 | P a g
class e2 implements Runnable e
{
public void run()
{
task1();
task2();
task3();
}
void task1()
{
System.out.println ("Hai");
}
void task2()
{
System.out.println ("hello");
}
void task3()
{
System.out.println ("welcome");
}
}
class it4
{
public static void main(String args[])
{
System.out.println ("Current thread");
e2 ob=new e2();
Thread t= new Thread(ob);
t.start();
}
}
NOTE:
Whatever method is executed by Thread default
public void run()
Q. What is the difference between extends thread and implements
runnable. Which has more advantages?
Extends thread and implement runnable both has same functionality.But
when we write extends thread there is no scope to extend another class,as
multiple inheritance is not supported in java.If we write implements Runnable
there is a scope to extend another class.
Syntax:
class myclass extends another class implementsRunnable
this is definitely advantaged when the program wants to use threads and
also wants to access the features of another class.
Multitasking threads:
in multi tasking several tasks are executed at a time.For this purpose we need
more than one thread.to perform two task we can take two threads and
attaching 2 threads. using more than 1 thread is called multi threading task.
//Write a java program that two threads working simultaneously upon two
objects: 130 | P a g
class myt implements Runnable e
{
String str
myt(String str)
{
this.str=str;
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println (str+" "+i);
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class its
{
Public static void main(String args[])
{
myt ob1 =new myt("cut the ticket");
myt ob2=new myt("show the seat");
Thread t1=new Thread(ob1);
Thread t2=new Thread(ob2);
t1.start();
t2.start();
}
}
Explanation:
In the above program, we have taken a string variable in myt class. Then
we passed two strings cut the ticket and show the seat into that variable from
it5 when t1.start() is executed. It starts execution on run() method showing "cut
the ticket" just behind it5 there is another t2.start() will make thread t2 also
execute on run() method simultaneously here sleep() is a static method in a
thread class which is used to suspend execution of a thread for some specified
milliseconds (2000milli seconds=2seconds) if any indirect exception is thrown, it
is caught by the catch block.
//Write a java program for 2 threads acting upon single object
class reserve implements Runnable
{
int av=1;
int wan;
reserve(int i) 131 | P a g
{ e
wan=i;
}
public void run()
{
System.out.println("available berth="+av);
if(av>=wan)
{
String name=Thread.currentThread().getName();
System.out.println(wan+"berth reserved for"+name);
try
{
Thread.sleep(2000);
av=av-wan;
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
else
System.out.println("sorry"):
}
}
class it6
{
public static void main(String args[])
{
reserve ob1=new reserve(1);
Thread t1=new Thread(ob1);
Thread t2=new Thread(ob1);
t1.setName("first person");
t2.setName("second person");
t1.start();
t2.start();
}
}
Explanation:
in the above program we use two threads on a single object. But in this
case unreliable results will occur. In this program already we have taken
available berths as '1' when threads t1 enters the run()method it sees available
no. of berths as "1" and hence it allots to 1st person. Then it enters into try
block. Inside run()method it will sleep for2 seconds. In this time the ticket will
be. Printed on the printer .In this sleeping time Thread t2 will enters the run()
method. It will also see that there is one berth is available and it allots the same
berth to the second person. Thus Thread t2 will be in sleep state for
2seconds.Thread t1 wake up first and then it updates the available no. of berths
will become'0'. so both the threads are acting on the same object simultaneously
leads unreliable results.
132 | P a g
e
Q) SYNCHRONIZATION OF THREADS:
When an thread is already acting on an object preventing any other
thread acting on the same object is called Thread synchronization(or)Thread
safe.
The object on which the threads are synchronized is called synchronized
object Thread synchronization is recommended when multiple Threads are used
on the same objects.
A thread also locks the object after entering it .then the next Thread can't
enter it till the first thread comes out. This means
Object is locked. When will mutually exclusive locks so these objects are called
mutex.
(Mutually exclusive locks)
1. synchronized block
2. synchronized keyword
SYNCHRONIZED BLOCK:
We can emboded a group if a statement of the object within the
synchronized block as shown here.
synchronized(object)
{
.........
.........no statements
}
The statements inside the synchronized block are all available to only one
Thread at a time. They are not available to more than on Thread
simultaneously.
SYCHRONIZED KEYWORD:
we can synchronize an entire method by using synchronized keyword.
for example :
If we want to synchronize the code of display() .The method name is show
synchronized void display()
{
..........
.........
}
Now the statement inside the display() method is not available to more
than one thread at a time.
The difference between synchronized block and synchronized key word :
sychronized block is useful to synchronize a block of a statement .Synhronized
keyword is used to synchronized a entire method.
Example for synchronized block:
class reserve implements Runnable
{
int av=1;
int wan;
reserve(int i)
{
wan=i;
} 133 | P a g
public void run() e
{
synchronized(this)
{
System.out.println("available berth="+av);
if(av>=wan)
{
String name=Thread.currentThread().getName();
System.out.println(wan+"berth reserved for="+name);
try
{
Thread.sleep(2000);
av=av-wan;
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
else
System.out.println("sorry");
}
}
}
class it7
{
public Static void main(String args[])
{
reserve ob1=new reserve(1);
Thread t1=new Thread(ob1);
Thread t2=new Thread(ob1);
t1.setName("first person");
t2.setName("second person");
t1.start();
t2.start();
}
}
Q) Explain about priority of Threads
When a Threads are created and started a thread scheduler program in
JVM will load them in to memory and execute then. this scheduler will allot
more JVM time to those Threads which are having higher priorities. the prority
numbers of Threads will change from 1 to 10. The minimum priority
(Thread.MIN_PRIORITY)of a Thread is 1.and the maximum priority
(Thread.MAX_PRIORITY) is 10.The normal priority of
Thread(Thread.NORM_PRIORITY) is 5. When a Thread is created by default its
priority will be 5.
Example:
class myc extends Thread
{
int c=0; 134 | P a g
public void run() e
{
for(int i=1;i<=100;i++)
c++;
System.out.println("completed Thread="+Thread.current Thread().getName());
System.out.println("its priority Thread=”+Thread.current Thread().getpriority());
}
}
class it11
{
public static void main(String args[])
{
myc obj=new myc();
Thread t1=new Thread(obj,"one");
Thread t2=new Thread(obj,"two");
t1.setpriority(1);
t2.setpriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
}
}

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.

Properties of Daemon threads:

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)

Daemon thread examples

Example 1: DaemonThreadExample1.java
This example is to demonstrate the usage of setDaemon() and isDaemon()
method.
public class DaemonThreadExample1 extends Thread{

public void run(){

// Checking whether the thread is Daemon or not


if(Thread.currentThread().isDaemon()){
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread executing");
}
}
public static void main(String[] args){
/* Creating two threads: by default they are
* user threads (non-daemon threads)
*/
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();

//Making user thread t1 to Daemon


t1.setDaemon(true);

//starting both the threads


t1.start(); 137 | P a g
t2.start(); e
}
}

Output:
Daemon thread executing
user(normal) thread executing
q) Dead lock of thread?

Deadlock in Java is a part of multithreading. Deadlock can occur in a situation


when a thread is waiting for an object lock, that is acquired by another thread
and second thread is waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock, the condition
is called deadlock.
Q)What are the applications of thread?
A multi-threaded application is an application whose architecture takes
advantage of the multi-threading provided by the operating system. Usually,
these applications assign specific jobs to individual threads within the
process and the threads communicate, through various means, to
synchronize their actions.

q) Expain Thread group?

There are only two constructors of ThreadGroup class.


No. Constructor Description

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


name.

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


String name) parent group and name

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

Input and Output Streams


Stream Classes: -
The java.io.*; package contains a large number of stream classes that
provide capabilities for processing all types of data. It is mainly categorized into
two types. They are
 Byte Stream classes that provide support for handling I/O operations on
bytes.
 Character Stream classes that provide support for managing I/O
operations on Characters.
These two groups may further be classified based on their purpose.

Java Stream
Classes

Byte Stream Character


Classes Stream Classes

Input Stream Output Stream Reader Writer


Classes Classes Classes Classes
141 | P a g
e

Memory File Pipe Memory File Pipe


These stream classes contain specialized classes to deal with input and output
operations independently on various types of devices.
Byte Stream Classes: -
It have been designed to provide functional features for crating and
manipulating streams and files for reading and writing bytes of data to the files
and from the files. So, streams are Unidirectional (One Direction Only) i.e.,
they can transmit bytes of data in only one direction. So, we have two kinds of
stream classes for reading and writing the data to the files. They are: Input
Streams and Output Streams.
Input Stream Classes: -
Input Stream Classes are used to read 8 bit bytes include a super class
known as InputStream and a number of subclasses for supporting various
input related functions. The super class InputStream is an abstract class and
therefore, we cannot create instances of this class. We must use the subclasses
that inherits or derived from this class. The InputStream class defines
methods for performing input functions such as:
 Reading Bytes
 Closing Streams
 Marking Positions in Streams
 Skipping ahead in a Stream
 Finding the no. of bytes in a Stream.

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

The DataInputStream extends FilterInputStream and implements the


interface DataInput and it has some methods described in addition to suing the
methods of InputStream. They are:
 readShort( )
 readInt( )
 readLong( ) 143 | P a g
e
 readFloat( )
 readUTF( )
 readDouble( )
 readLine( )
 readChar( )
 readBoolean( )
Output Stream Classes: -
Output Stream classes are derived from the base class OutputStream.
Like InputStream, OutputStream is an abstract class and therefore we cannot
instantiate it. The several sub classes of the OutputStream can be used for
performing the Output Operations. It includes the following methods.
 Writing Bytes
 Closing Streams
 Flushing Streams
Method Description
Write( ) Writes a byte to the output stream
Writes all bytes in the array b to the
Write(byte b[])
Output Stream
Write(byte b[], int n, Writes m bytes from array b starting from
int m) nth byte.
Flush( ) Flushes the Output 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

BufferedReader StringReader 145 | P a g


e

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.

The RandomAccessFile supports a pointer known as File Pointer that


can be moved to arbitrary positions in the file prior to reading or writing. The
file pointer is moved using the method “seek( )” in the RandomAccessFile
class.

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.

 Creating a File  Opening a File


 Closing a File  Deleting a File
 Getting the Name of a File  Getting the size of a File
 Checking the Existence of a File  Renaming a File
 Checking whether the File is Writable  Checking whether the File is
Readable
Creation of Files: -
If we want to create and use a disk File, we need to follow these steps to
intended the File and its purpose.
 Suitable Name for the File (Ex: abc, xyz etc)
 Data type to be stored (Ex: .txt, .dat, .data, .doc etc)
 Purpose of a File (Reading, Writing or Updating)
 Method of creating a File

A file name is a unique string of characters that helps to identify a file on


the disk. The length of a Filename and the characters allowed are dependent on
the System (OS) on which the Java Program is executed. A filename may
contain two parts. A Primary name and an Optional period with extension.
Ex: - input.data, salary, test.doc, student.txt, inventory.dat etc.,
Data type is important to decide the type of file Stream classes to be used
for handling the data. We should decide whether the data to be handled is in
the form of characters, bytes or primitive type. The purpose of using a file must
149 | P a g
also be decided before using it. There are two ways of initializing the File eStream
Objects. All of the constructors require that we provide name of the File either
directly or indirectly by giving a file object that has been already assigned to a
filename.

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)
{ ………………….
……………………
}

The above code includes the 4 steps. 1. Selecting a File Name. 2.


Declaring a File Object. 3. Give the selected name to the file object declared. 4.
Connect the file to the File Stream Object.
150 | P a g
Handling Primitive Data Types: - e
The basic Input and Output Streams provide read and write methods that
can only be used for reading / writing bytes or characters. If we want to
read/write the Primitive data types such as integers and doubles, we can use
Filter Classes as Wrappers on existing Input and Output Stream to Filter the
original stream. The two Filter classes are used for creating Data Stream for
handling Primitive types are DataInputStream and DataOutputStream. These
classes are use the concept of multiple inheritance.
These streams first create a input file stream and then create the input
data stream. Note that the file object must be initialized with appropriate file
name before they are used.
Concatenating and Buffering Files: -
It is possible to combine two or more input streams (files) into a single
input stream file. This process is known as Concatenation of files and is
achieved by using the SequenceInputStream class. One of the Constructors of
this class takes two InputStream objects as arguments and combines them to
construct a single input stream. Java also supports creation of Buffers to store
temporarily data that is read from or written to a stream. This process is known
as buffered File operation. A buffer sits between the program and the source
and function as a Filter. Buffers can be created using the
BufferedInputStream and BufferedOutputStream classes.
Other Stream Classes: -
Java supports many other I/O streams that we might find useful in some
situations.
Object Streams: -
We can read and write characters, bytes and primitive data types to
perform input and output operations on objects using the object streams. The
object streams are created by using the ObjectInputStream and
ObjectOutputStream classes. In this case, we may declare records as objects
and use the object classes to write and read these objects from files. It is also
known as Object Serialization.
Piped Streams: -
It provides functionality for two or more threads to communicate and
151 | P a g
exchange data between them. The write thread sends data to the read ethread
through a pipeline that connects an object of PipedInputStream to an object of
PipedOutputStream. The Objects InputPipe and OutputPipe are connected
through using Connect( ) method.

InputPipe OutputPipe

Write Thread Read Thread

Push Back Stream: - This is created by the classes PushbackInputStream


and PushbackReader can be used to push a single byte or character back into
the input stream so that it can be re-read. This is commonly used with parsers.
When a character indicating a new Input token is read, it is pushed back into
the input stream until the current input token is processed. It is then re-read
when processing of the next input token is initiated.

Filtered Streams: - The two abstract classes FilterInputStream and


FilterOutputStream provides the capability to create input and output streams
for filtering the I/O in a no. of ways. These streams are known as Filters sit
between an input stream and an output stream and to perform the some
operational processing on the data they transfer. We can combine these filters
to perform a series of filtering operations.

Q) Explain about Zipping a file?


DeflaterOutputStream and InflaterInputStream classes are provided in Java to
compress and decompress the file contents. These classes provide useful
methods that can be used for compressing the file content.
Compressing a File using DeflaterOutputStream
This class implements an output stream filter for compressing data in the
“deflate” compression format. It is also used as the basis for other types of
compression filters, such as GZIPOutputStream.
Important Methods:
void close() : Writes remaining compressed data to the output stream and
closes the underlying stream.
protected void deflate() : Writes next block of compressed data to the
output stream.
void finish() : Finishes writing compressed data to the output stream
without closing the underlying stream.
void flush() : Flushes the compressed output stream. 152 | P a g
e
void write(byte[] b, int off, int len) : Writes an array of bytes to the
compressed output stream where off is the start offset of data and len is
total number of bytes.
void write(int b) : Writes a byte to the compressed output stream.
Steps to compress a file(file 1)
Take an input file ‘file 1’ to FileInputStream for reading data.
Take the output file ‘file 2’ and assign it to FileOutputStream . This will help
to write data into ‘file2’.
Assign FileOutputStream to DeflaterOutputStream for Compressing the
data.
Now, read data from FileInputStream and write it into
DeflaterOutputStream. It will compress the data and send it to
FileOutputStream which stores the compressed data into the output file.

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");

//Assign compressed file:file2 to FileOutputStream


FileOutputStream fos=new FileOutputStream("file2");

//Assign FileOutputStream to DeflaterOutputStream


DeflaterOutputStream dos=new DeflaterOutputStream(fos);

//read data from FileInputStream and write it into


DeflaterOutputStream
int data;
while ((data=fis.read())!=-1)
{
dos.write(data);
}

//close the file


fis.close();
dos.close();
}
}
Q) Expalin about unzipping a file? 153 | P a g
e
Decompressing a File using InflaterInputStream
This class implements a stream filter for uncompressing data in the “deflate”
compression format. It is also used as the basis for other decompression
filters, such as GZIPInputStream.
Important methods:
 int available() : Returns 0 after EOF has been reached, otherwise always
return 1.
 void close() : Closes the input stream and releases any system resources
associated with the stream.
 protected void fill() : Fills input buffer with more data to decompress.
 void mark(int readlimit) : Marks the current position in the input stream.
 boolean markSupported() : Tests if the input stream supports the mark
and reset methods.
 int read() : Reads a byte of uncompressed data.
 int read(byte[] b, int off, int len) : Reads decompressed data into an array
of bytes to the compressed output stream where off is the start offset of data
and len is total number of bytes.
 void reset() : Re-positions this stream to the position at the time the mark
method was last called on this input stream.
Steps to decompress a file
 File with the name ‘file2’ now contains compressed data and we need to
obtain original decompressed data from this file.
 Assign the compressed file ‘file2’ to FileInputStream. This helps to read data
from ‘file2’.
 Assign the output file ‘file3’ to FileOutputStream. This will help to write
uncompressed data into ‘file3’.
 Now, read uncompressed data from InflaterInputStream and write it into
FileOutputStream. This will write the uncompressed data to ‘file3’.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.InflaterInputStream;

//Uncompressing a file using an InflaterInputStream


class unzip
{
public static void main(String[] args) throws IOException {
//assign Input File : file2 to FileInputStream for reading data
FileInputStream fis=new FileInputStream("file2");

//assign output file: file3 to FileOutputStream for reading the


data
154 | P a g
FileOutputStream fos=new FileOutputStream("file3"); e
//assign inflaterInputStream to FileInputStream for
uncompressing the data
InflaterInputStream iis=new InflaterInputStream(fis);

//read data from inflaterInputStream and write it into


FileOutputStream
int data;
while((data=iis.read())!=-1)
{
fos.write(data);
}

//close the files


fos.close();
iis.close();

}
}

Q) Explain about serialization deserialization of Objects?

Java provides a mechanism, called object serialization where an object can be


represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file
and deserialized that is, the type information and bytes that represent the object
and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an
object can be serialized on one platform and deserialized on an entirely different
platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams
that contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various
data types, but one method in particular stands out −
public final void writeObject(Object x) throws IOException 155 | P a g
e
The above method serializes an Object and sends it to the output stream.
Similarly, the ObjectInputStream class contains the following method for
deserializing an object −
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The
return value is Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee
class that we discussed early on in the book. Suppose that we have the
following Employee class, which implements the Serializable interface −
Example
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;

public void mailCheck() {


System.out.println("Mailing a check to " + name + " " + address);
}
}
Notice that for a class to be serialized successfully, two conditions must be met

 The class must implement the java.io.Serializable interface.
 All of the fields in the class must be serializable. If a field is not serializable,
it must be marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check
the documentation for the class. The test is simple: If the class implements
java.io.Serializable, then it is serializable; otherwise, it's not.

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 {

public static void main(String [] args) {


Employee e = new Employee();
e.name = "Reyan Ali"; 156 | P a g
e
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;

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 {

public static void main(String [] args) {


Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}

System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("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;

public class WordCountInFile


{
public static void main(String[] args)
{
BufferedReader reader = null;

//Initializing charCount, wordCount and lineCount to 0

int charCount = 0;

int wordCount = 0;

int lineCount = 0;

try
{
//Creating BufferedReader object

reader = new BufferedReader(new FileReader("C:\\sample.txt"));

//Reading the first line into currentLine

String currentLine = reader.readLine();

while (currentLine != null)


{
//Updating the lineCount

lineCount++;
158 | P a g
//Getting number of words in currentLine e
String[] words = currentLine.split(" ");

//Updating the wordCount

wordCount = wordCount + words.length;

//Iterating each word

for (String word : words)


{
//Updating the charCount

charCount = charCount + word.length();


}

//Reading next line into currentLine

currentLine = reader.readLine();
}

//Printing charCount, wordCount and lineCount

System.out.println("Number Of Chars In A File : "+charCount);

System.out.println("Number Of Words In A File : "+wordCount);

System.out.println("Number Of Lines In A File : "+lineCount);


}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close(); //Closing the reader
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Output :
Number Of Chars In A File : 20
Number Of Words In A File : 4 159 | P a g
Number Of Lines In A File : 2 e
Q) Explain file copy one file in to another file?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyExample {


public static void main(String[] args) {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile = new File("C:\\kumar\\abc.txt");
File outfile = new File("C:\\kumar\\bbc.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;

while ((length = ins.read(buffer)) > 0) {


outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File copied successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
The above code sample will produce the following result.
File copied successfully!!
Q) Explain about File class and Methods with example?

The File class is an abstract representation of file and directory pathname. A


pathname can be either absolute or relative.

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.

File obj=new File(filename);

File obj=new File(directoryname);

File obj=new File(“path”,filename);

File obj=new File(“path”,directoryname); 160 | P a g


e

File Class Methods


File class has many useful methods for creating and getting information about
files. For example:

Method Type Description

canRead() Boolean Tests whether the file is readable


or not

canWrite() Boolean Tests whether the file is writable


or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname


of the file

length() Long Returns the size of the file in


bytes

list() String[] Returns an array of the files in


the directory

mkdir() Boolean Creates a directory

161 | P a g
e
import java.io.*;
class FileProperty

public static void main(String args[])

String fname=args[0];

File f=new File(fname);

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());

System.out.println(“file size in bytes”+f.length());

}}

Output

C:\>javac FileProperty.java

C:\>java FileProperty Myfile.txt

File name myfile.txt


path myfile.txt

absolute path c:\kumar\myfile.txt

exists true

is writable true

isreadable true

is a directory false
162 | P a g
file size in bytes 61 e

Q)Explain database servers?


A database server runs a database management system and provides database
services to clients. The server manages data access and retrieval and completes
clients’ requests.

A database server consists of hardware and software that run a database.

The software side of a database server, or the database instance, is the back-
end database application.

The application represents a set of memory structures and background


processes accessing a set of database files.

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.

How Does a Database Server Work?

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.

Clients access a database server through a front-end application that displays


the requested data on the client machine, or through a back-end
application that runs on the server and manages the database.

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.

Q) What is the difference between statement and prepared statement?

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.

Q) what are stored procedures?

A store procedure represents a set of statements that is stored and executed at


database server sending the results to the client.

Q) what is the use of CallableStatements?

Callable statements is useful to call stored procedure and functions which run
at a database server and get the results into the client.

Q) Explain jdbc and Its Components

JDBC
Introduction:

Java DataBase Connectivity, commonly known as JDBC, is an API for Java


programming language that defines how a client may access a database.
JDBC API uses JDBC driver written in Java. JDBC is platform independent.

What is API (Application Programming Interface)?


API is a document that contains description of all features of a product or
software. It represents classes and interfaces that software programs can
follow to communicate with each other.
JDBC Components
JDBC includes four components
1. The JDBC API
The JDBC API provides programmatic access to relational data from 164the
|P ag
Java programming language. Using the JDBC API, applications can execute
e
SQL statements, retrieve results, and propagate changes back to an
underlying data source. The JDBC API can also interact with multiple data
sources in a distributed, heterogeneous environment.

2. JDBC Driver Manager


The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager has traditionally been the
backbone of the JDBC architecture. It is quite small and simple.
3. JDBC Test Suite
The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests
are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC
API.

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.

 Two tier architecture


In the two-tier model, a Java applet or application talks directly to the data
source. This requires a JDBC driver that can communicate with the
particular data source being accessed. A user's commands are delivered to
the database or other data source, and the results of those statements are
sent back to the user. The data source may be located on another machine
to which the user is connected via a network. This is referred to as a
client/server configuration, with the user's machine as the client, and the
machine housing the data source as the server. The network can be
anintranet, which, for example, connects employees within a corporation, or
it can be the Internet.

 Three tier architecture

In the three-tier model, commands are sent to a "middle tier" of services,


which then sends the commands to the data source. The data source
processes the commands and sends the results back to the middle tier, which
then sends them to the user. MIS directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over
access and the kinds of updates that can be made to corporate data. Another
advantage is that it simplifies the deployment of applications. Finally, in
many cases, the three- tier architecture can provide performance
advantages. With enterprises increasingly using the Java programming
language for writing server code, the JDBC API is being used more and more
in the middle tier of a three-tier architecture. Some of the features that make
166 | P a g
e
JDBC a server technology are its support for connection pooling, distributed
transactions, and disconnected

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)

1. JDBC-ODBC Bridge Driver (Type 1)


Uses ODBC bridge driver to connect to database.
Converts JDBC methods call into function call.
ODBC drivers need to be installed on client machine. This
driver is platform dependent

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.

3. Network Protocol Driver (Type 3/Fully Java Driver)


Uses middleware that convert JDBC call directly or indirectly into
vendorspecific database protocol.
Fully written in Java.
Database specific coding to be done in middle tier.

Advantage
No client side library is required.

Disadvantage
Network support is required on client machine.
Database specific coding is done in middleware.

4. Thin Driver (Type 4/Fully Java Driver)


Converts JDBC calls directly into vendor specific database protocol.
Fully written in Java.
User needs different drivers for each database.
Performance is good.

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

Write a JDBC Program to retrieve Employee number,name,job form Emp Table of


Oracle Database
import java.sql.*;
class OracleCon

public static void main(String args[])

try

//step1 load the driver class


Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

Sql important
//step5 Queries
close the connection object
con.close();

} create table employee (empno number(4) primary key,ename


varchar2(10));
catch(Exception e)
173 | P a g
{ e

System.out.println(e);
1. Select ---- To display required columns from

table Syntax:
SELECT COLUMN1,COLUMN2,... FROM TABLENAME;

Ex :

SELECT EMPNO,ENAME,JOB FROM EMP;

Note : Need all columns of table then use '*' for all columns

Ex : SELECT * FROM EMP;

2. insert ----> To add new row to

table Syntax :
insert into tablename values(value1,value2,value2,. );

Ex :
insert into emp values(1342,'GOWTHAM','MANAGER',. );

3. delete ----> To remove row from

table Syntax :

delete from table where condition

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");

//step2 create the connection object Connection


con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object Statement


stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));

emp table and display (ResultSet example)


//step5 close the connection objectcon.close(); 176 | P a g
e

}
catch(Exception e)
{
System.out.println(e);
}
}
}

Write a JDBC program to Update Salary of an employee

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");

// Connect to the database


// You can put a database name after the @ sign in the connectionURL.
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

// Prepare a statement to cleanup the emp tableStatement


stmt = conn.createStatement ();
stmt.execute ("update emp set sal=sal+(sal*10/100),deptno=10 where
ename='SCOTT'");

// Close the statement


stmt.close();
// Close the connecion
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

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");

// Connect to the database


// You can put a database name after the @ sign in the connectionURL.
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

// Prepare a statement to cleanup the emp tableStatement


stmt = conn.createStatement ();
stmt.execute ("delete from employee where empno=9832");stmt.execute

("delete from employee where empno=4282");

// Close the statement


stmt.close();
// Close the connecion
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}}
179 | P a g
e
Write a JDBC program to demonstrate PreparedStatement exampleimport java.sql.*;

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

{
try
{
// Load the Oracle JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");

// Connect to the database


// You can put a database name after the @ sign in the connectionURL.
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

// Prepare a statement to cleanup the emp tablePreparedStatement pstmt =


conn.prepareStatement ("insert into EMPLOYEE (EMPNO, ENAME)values (?, ?)");

// Add LESLIE as employee number 1500


pstmt.setInt (1, 1500); // The first ? is for EMPNO
pstmt.setString (2, "LESLIE"); // The second ? is for ENAME
// Do the insertion
pstmt.execute ();
// Add MARSHA as employee number 507
pstmt.setInt (1, 507); // The first ? is for EMPNO
pstmt.setString (2, "MARSHA"); // The second ? is for ENAME
// Do the insertion
pstmt.execute ();

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
}

import java.awt.*; import


java.sql.*; import
javax.swing.*; import
java.awt.event.*;

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();
}
}

Q) How to use Jdbc-odbc Bridge driver to connect oracle database?

To connect a JAVA application with Oracle database using


JDBC-ODBC Bridge(type-1) Driver. You need to follow the
following steps.

Create DSN Name

Step 1: Go to control panel > Administrative Tools and select


ODBC Data Source.

Step 2: To Add new DSN, Click on Add


P.Y.Kumar M.C.A,M.Tech,M.Phil..,

Step 3: Select Oracle in XE driver from the list, Click on


Finish

Step 4: Give a DSN Name

 Data Source Name: CollegeekDSN ; Give any name to


Data Source that you want to give.
 Description: Write description or leave blank.
 TNS Service Name: XE ; for Oracle is XE, you can
check it in tnsnames.ora file.
 User ID: SYSTEM ; we will give it later.

Than click on Test Connection

184
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

tnsnames.ora file.

Step 5: Oracle Driver Connection

 Service Name: XE ; from previous step it will appear.


 User Name: SYSTEM ;
 Password: Enter Password that you have given at
Oracle Database installation time. In my case it is
admin.
185
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

Than click on OK

Step 6: Click Ok , you can see that new DSN name in


list. Click OK

Setting Up JDBC-ODBC bridge

Method 1: Enable JDBC-ODBC bridge for JDK

Method 2: We will download JDK 7 and set Temporary Java


Path (This will not affect your current Java environment
because we are not installing it).

 Step 1: Download JDK 7 and extract it anywhere.


 Step 2: Copy the path of jdk/bin directory
 Step 3: Open command prompt and write:SET
PATH=copied_path
 Step 4: Compile JAVA program and Run

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);

// Establish the connection to the database


server
// urlstring,enter workspace username or
SYSTEM,password
Connection cn =
DriverManager.getConnection("jdbc:odbc:CollegeekDSN","admin","admin")
;

// Create a statement
Statement st = cn.createStatement();

// Execute the statement


ResultSet rs = st.executeQuery("select * from
emp1000");
// Retrieve the results
while(rs.next())
System.out.println(rs.getString(1)+"
"+rs.getString(2));

187
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

// Close the statement and connection


st.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}

}
}

q) Explain about retrieving data from MySql Database?


Let us open MySql database and see which database are there, by typing show
database command as
Mysql>show database;
Database
Mysql
Test
The above output means that there are 2 databases currently available in mySql.let
us first move into test database as
Mysql>use test;
Database changed
Create a table emp now using create stement in the database “test” as
Mysql> create table emp(eno int,ename char(30),sal float);
Then enter some rows into the emp using insert statement as
Mysql>insert into emp values(100.”kumar”,6000);
Mysql>commit;
Now, let us write a java program to see how to retrieve all the rows from the emp of
test database that is available in MySql database. Mysql.com company provides a
driver mysql.jar along with a user manual where they provide help regarding how to
register their driver. Register the mysql driver in the following manner
driverManager.registerDriver(new com.mysql.jdbc.Driver());
to connect to the database, we should use:
connection
con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?user=root&pa
ssword=student”);
here , user name is root and password is student.

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..,

Q) How to retrieving and connecting data from Ms-


Acess database?
Java application with the MS Access database using the Eclipse and NetBeans IDE and
still after numerous attempts you are failing to connect, then you have come to the right
place. In this tutorial, we are going to learn about How to Connect MS Access Database
in Java or Java 8

How to Connect MS Access Database in Java


Creating an MS Access Database

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.

 Open Microsoft office Access (I am using Microsoft office access 2007).


 Create a New Blank Database as shown in the figure below.
 Give it a name (For example StudentDatabase.accdb) and specify a location where
you want to save it.
 Now click on Create button to create the database.
 As soon as you click Create button, Microsoft Access creates a default table
named “Table1” with its default field “ID“.
 Right-click on the Table and select Design View.
 A Save As dialog box will appear, and it will ask you for to give it a name.
 Provide a suitable name for your table and click OK button.
 Now you can create fields for your table with their associated data types.(I am
going to create two fields Username and City with their data types as Text).
Downloading UCanAccess JAR file

To connect our Java application with Microsoft Access Database, we need to add some
JAR files to our program,

Connecting MS Access Database in Java Using Eclipse


Step #1 -> Creating a Java Project in Eclipse

 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 {

//Creating main method

190
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

public static void main(String[] args) {

}
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.

 Load the UCanAccess Driver using forname method of class Class.


 Now we have to establish a connection using DriverManager.getConnection(String
URL) and it returns a Connection reference.
 In String URL parameter you have to write like this “jdbc:ucanaccess://”+”Full path
of the database”;
 SQL Exception might occur while connecting to the database, So you need to surround
it with the try-catch block.

import java.sql.Connection;
import java.sql.DriverManager;

public class AccessConnectivity {


public static void main(String[] args){
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");//Loading Driver
Connection connection=
DriverManager.getConnection("jdbc:ucanaccess://E:\\StudentDatabase.accdb");//Est
ablishing Connection

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");
}
}
}

Q) Explain about different typs of Result sets in java?


The SQL statements that read data from a database query, return the
data in a result set. The SELECT statement is the standard way to
select rows from a database and view them in a result set.
The java.sql.ResultSet interface represents the result set of a database
query.
A ResultSet object maintains a cursor that points to the current row in
the result set. The term "result set" refers to the row and column data
contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three
categories −
 Navigational methods − Used to move the cursor around.
 Get methods − Used to view the data in the columns of the
current row being pointed by the cursor.
 Update methods − Used to update the data in the columns of the
current row. The updates can then be updated in the underlying
database as well.
The cursor is movable based on the properties of the ResultSet. These
properties are designated when the corresponding Statement that
generates the ResultSet is created.
JDBC provides the following connection methods to create statements
with desired ResultSet −
 createStatement(int RSType, int RSConcurrency);
 prepareStatement(String SQL, int RSType, int
RSConcurrency);
 prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the
second argument is one of two ResultSet constants for specifying
whether a result set is read-only or updatable.

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

ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the


default

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

All our examples written so far can be written as follows, which


initializes a Statement object to create a forward-only, read only
ResultSet object −
try {
Statement stmt =
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}

Navigating a Result Set


There are several methods in the ResultSet interface that involve
moving the cursor, including −

193
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

S.N. Methods & Description

1 public void beforeFirst() throws SQLException

Moves the cursor just before the first row.

2 public void afterLast() throws SQLException

Moves the cursor just after the last row.

3 public boolean first() throws SQLException

Moves the cursor to the first row.

4 public void last() throws SQLException

Moves the cursor to the last row.

5 public boolean absolute(int row) throws SQLException

Moves the cursor to the specified row.

6 public boolean relative(int row) throws SQLException

Moves the cursor the given number of rows forward or backward, from
where it is currently pointing.

7 public boolean previous() throws SQLException

Moves the cursor to the previous row. This method returns false if the
previous row is off the result set.

8 public boolean next() throws SQLException

Moves the cursor to the next row. This method returns false if there are
no more rows in the result set.

9 public int getRow() throws SQLException

Returns the row number that the cursor is pointing to.

10 public void moveToInsertRow() throws SQLException

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..,

11 public void moveToCurrentRow() throws SQLException

Moves the cursor back to the current row if the cursor is currently at the
insert row; otherwise, this method does nothing

For a better understanding, let us study Navigate - Example Code.

Viewing a Result Set


The ResultSet interface contains dozens of methods for getting the
data of the current row.
There is a get method for each of the possible data types, and each get
method has two versions −
 One that takes in a column name.
 One that takes in a column index.
For example, if the column you are interested in viewing contains an
int, you need to use one of the getInt() methods of ResultSet −

S.N. Methods & Description

1 public int getInt(String columnName) throws SQLException

Returns the int in the current row in the column named columnName.

2 public int getInt(int columnIndex) throws SQLException

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.

Updating a Result Set


The ResultSet interface contains a collection of update methods for
updating the data of a result set.
As with the get methods, there are two update methods for each data
type −

195
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

 One that takes in a column name.


 One that takes in a column index.
For example, to update a String column of the current row of a result
set, you would use one of the following updateString() methods −

S.N. Methods & Description

1 public void updateString(int columnIndex, String s) throws


SQLException

Changes the String in the specified column to the value of s.

2 public void updateString(String columnName, String s) throws


SQLException

Similar to the previous method, except that the column is specified by


its name instead of its index.

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.

S.N. Methods & Description

1 public void updateRow()

Updates the current row by updating the corresponding row in the


database.

2 public void deleteRow()

Deletes the current row from the database

3 public void refreshRow()

Refreshes the data in the result set to reflect any recent changes in the
database.

4 public void cancelRowUpdates()

Cancels any updates made on the current row.

196
P.Y.Kumar M.C.A,M.Tech,M.Phil..,

5 public void insertRow()

Inserts a row into the database. This method can only be invoked when
the cursor is pointing to the insert row.

197

You might also like