Sunteți pe pagina 1din 122

Geethanjali College of Engineering and Technology

Cheeryal (V), Keesara (M), Medchal District – 501 301 (T.S)


UGC AUTONOMOUS
JAVA Programming
Course File

DEPARTMENT OF
ELECTRONICS COMMUNICATION & ENGINEERING

Course Coordinator HOD-ECE

1
Geethanjali College of Engineering and Technology
DEPARTMENT OF ELECTRONICS COMMUNICATION & ENGINEERING
(Name of the Subject/Lab Course): JAVA Programming
(Course Code): 16CS3123 Programme: UG

Branch: ECE Version No: 1


Year: III Document Number :GCET/EEE /2019-20
Semester: I No. of Pages: 122

Classification status (Unrestricted/Restricted ) : Unrestricted


Distribution List: Unrestricted

Prepared by :
1) Name : G.Swapna
2) Sign :
3) Design : ASSISTANT PROFESSOR
4) Date :

Verified by : *For Q.C only


1) Name : 1)Name :
2) Sign : 2) Sign :
3) Design : 3) Design :
4) Date : 4) Date :

Approved by (HOD) :
1) Name :
2) Sign :
3) Date :

Contents

2
S.No Topic Page. No.

1 Cover Page 2

2 Syllabus copy 5

3 Vision of the Department 8

4 Mission of the Department 8

5 PEOs and PO’s & PSO’s 9

6 Course objectives and outcomes 11

7 Course mapping with Pos 12

8 Brief notes on the importance of the course and how it fits into the curriculum 13

9 Prerequisites if any 13

10 Instructional Learning Outcomes 14

11 Class Time Table 15

12 Individual Time Table 15

13 Lecture schedule with methodology being used/adopted 15

14 Lesson Schedule 18

15 Detailed notes 21

16 Additional topics 83

17 University Question papers of previous years 84

18 Question Bank 90

19 Assignment Questions 96

20 Unit wise Quiz Questions 98

21 Tutorial problems 116

22 Known gaps ,if any and inclusion of the same in lecture schedule 118

23 Discussion topics , if any 121

24 References, Journals, websites and E-links if any 122

25 Quality Measurement Sheets 122

A Course End Survey 122

3
B Teaching Evaluation 122

25 Student List 122

26 Group-Wise students list for discussion topic 122

Course coordinator Program Coordinator HOD

2. Syllabus
16CS3123 – JAVA PROGRAMMING

(Open Elective – I)

III Year B.Tech I Sem

4
L T P/D C
Prerequisite(s): C Programming (or) C++ Programming 3 - -/- 3

Course Objectives:

Develop ability to

1. Understand basic concepts of object oriented programming.

2. Understand the primitive data types built into the java language and features of strongly typed
language.

3. Understanding scope, lifetime, and the initialization mechanism of variables and parameter
passing mechanisms.

4. Understand file streams and database connectivity using Java language.

Course Outcomes (COs):

After completion of the course, student would be able to

CO1. Apply the concepts of OOPs in problem solving.

CO2. Use data abstraction, inheritance, polymorphism, encapsulation and method overloading
principles in structuring computer applications.

CO3. Identify classes, objects, members of a class and relationships among them needed for a
specific problem.

CO4. Use java standard class library with necessary exception handling mechanisms in
constructing computer applications.

CO5. Develop java programs using multi – threading, files and database concepts and their
connectivity.

UNIT – I

5
Object Oriented Characteristics – Data abstraction, encapsulation, and inheritance, benefits of
inheritance, polymorphism, classes and objects, procedural and object oriented programming
paradigms.

Java Programming – History of Java, comments, data types, variables, constants, scope and
lifetime of variables.

UNIT – II

Operators, operator hierarchy, expressions, type conversion and casting, enumerated types,
control flow block scope, conditional statements, loops, break and continue statements, simple
java program, arrays, console input and output, formatting output, constructors, methods,
parameter passing, static fields and methods, access control, this keyword, overloading methods
and constructors, recursion, garbage collection, building strings, exploring string class.

UNIT – III

Interfaces – Interfaces VS. Abstract classes, defining an interface, implementing interfaces,


accessing implementations through interface references, extending interface.

Inner classes – Uses of inner classes, local inner classes, anonymous inner classes, static inner
classes, examples.

Packages – Definition, creating and accessing a package, understanding CLASSPATH,


importing packages.

UNIT - IV
Exception handling – Dealing with errors, benefits of exception handling, the classification of
exceptions – exception hierarchy, checked exceptions and unchecked exceptions, usage of try,
catch, throw, throws and finally, rethrowing exceptions, exception specification, built in
exceptions, creating own exception sub classes.
Multithreading – Differences between multiple processes and multiple threads, thread states,
creating threads, interrupting threads, thread priorities, synchronizing threads, inter thread
communication, producer consumer problem.

UNIT – V

File: Streams – byte streams, character streams, text input/output, binary input/output, random
access file operations, file management using file class.

Connecting to Database – JDBC type 1 to 4 drivers, connecting to a database, querying a


database and processing the results, updating data with JDBC.

TEXT BOOK(S)

6
1. Java fundamentals – A comprehensive Introduction, Herbert Schidlt and Dale Skrien, TMH,

1st Edition, 2013.

REFERENCE BOOK(S):

1. Core Java2 – volume1, cay S.Horstmann and Gray cornell

2. Java for programmers, PJ. Dietel and H.M Dietel person education

3. Object oriented programming through java. P.Radha Krishna. Universities Press.

4. Thinking in java, Bruce Eckel, Pearson Education.

3. Vision of the Department

7
To impart quality technical education in Electronics and Communication Engineering
emphasizing analysis, design/synthesis and evaluation of hardware/embedded software using
various Electronic Design Automation (EDA) tools with accent on creativity, innovation and
research thereby producing competent engineers who can meet global challenges with societal
commitment.

4. Mission of the Department


i. To impart quality education in fundamentals of basic sciences, mathematics, electronics and
communication engineering through innovative teaching-learning processes.

ii. To facilitate Graduates define, design, and solve engineering problems in the field of
Electronics and Communication Engineering using various Electronic Design Automation
(EDA) tools.

iii. To encourage research culture among faculty and students thereby facilitating them to be
creative and innovative through constant interaction with R & D organizations and Industry.

iv. To inculcate teamwork, imbibe leadership qualities, professional ethics and social
responsibilities in students and faculty.

5. PROGRAM EDUCATIONAL OBJECTIVES (PEOs) OF E.C.E DEPARTMENT


Program Educational Objectives of B. Tech (ECE) Program :

8
I. To prepare students with excellent comprehension of basic sciences, mathematics and
engineering subjects facilitating them to gain employment or pursue postgraduate studies
with an appreciation for lifelong learning.

II. To train students with problem solving capabilities such as analysis and design with
adequate practical skills wherein they demonstrate creativity and innovation that would
enable them to develop state of the art equipment and technologies of multidisciplinary
nature for societal development.

III. To inculcate positive attitude, professional ethics, effective communication and


interpersonal skills which would facilitate them to succeed in the chosen profession
exhibiting creativity and innovation through research and development both as team
member and as well as leader.

Program Outcomes of B.Tech ECE Program:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems:
 The problems that cannot be solved by straightforward application of knowledge, theories
and techniques applicable to the engineering discipline.
 That may not have a unique solution. For example, a design problem can be solved in
many ways and lead to multiple possible solutions.
 That require consideration of appropriate constraints/requirements not explicitly given in
the problem statement. (like: cost, power requirement, durability, product life, etc.).

 Which need to be defined (modeled) within appropriate mathematical framework.

9
 That often require use of modern computational concepts and tools.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs):

1.An ability to design an Electronics and Communication Engineering system, component, or


process and conduct experiments, analyze, interpret data and prepare a report with conclusions

10
to meet desired needs within the realistic constraints such as economic, environmental, social,
political, ethical, health and safety, manufacturability and sustainability.

2. An ability to use modern Electronic Design Automation (EDA) tools, software and electronic
equipment to analyze, synthesize and evaluate Electronics and Communication Engineering
systems for multidisciplinary tasks.

6. Course objectives and outcomes:


Course objectives:
Course Objectives Develop ability to
1. Understand basic concepts of object oriented programming.
2. Understand the primitive data types built into the Java language and features of strongly typed
language.
3. Understanding scope, lifetime, and the initialization mechanism of variables and parameter
passing mechanisms.
4. Understand file streams and database connectivity using java language

Course Outcomes (COs)


After completion of the course, student would be able to
CO1. Apply the concepts of OOPs in problem solving.
CO2. Use data abstraction, inheritance, polymorphism, encapsulation and method overloading
principles in structuring computer applications.
CO3. Identify classes, objects, members of a class and relationships among them needed for a
specific problem.
CO4. Use Java standard class library with necessary exception handling mechanisms in
constructing computer applications.
CO5. Develop java programs using multi-threading, files and database concepts and their
connectivity.

7. Course mapping with Program Outcomes

11
Course POS
Code and Title
Java Programming 1 2 3 4 5 6 7 8 9 10 11 12 13 14

CO1. Apply the concepts of 2 2 2 2 1 1 1 1 2 2


OOPs in problem solving
CO2. Use data abstraction, 2 2 2 2 1 1 1 1 2 2
inheritance, polymorphism,
encapsulation and method
overloading principles in
structuring computer
applications.

CO3. Identify classes, objects, 2 2 2 2 1 1 1 1 2 2


members of a class and
relationships among them
needed for a specific problem.

CO4. Use Java standard class 2 2 2 2 1 1 1 1 2 2


library with necessary exception
handling mechanisms in
constructing computer
applications.

CO5. Develop java programs 2 2 2 2 1 1 1 1 2 2


using multi-threading, files and
database concepts and their
connectivity

8. Brief notes on the importance of the course and how it fits into the curriculum

This course introduces students to object oriented programming and design.


Students will be exposed to the principles of the object oriented programming paradigm

12
specifically including abstraction, encapsulation, inheritance and polymorphism. They are
equipped to use an object oriented programming language Java, and associated class libraries, to
develop object oriented programs with a clear understanding of Java features. The course helps
the students to design, develop, test, and debug programs using object oriented principles, GUI
design with Applets and Swings, JDBC –ODBC connections in conjuncture with an integrated
development environment Eclipse. They will be able to describe and explain the factors that
contribute to a good object oriented solution.

The course enables a student to analyze a problem and identify and define the computing
requirements appropriate for its solution under given constraints, to perform experiments to
analyze and interpret data for different applications, and to design, implement and evaluate
computer-based systems, processes, components or programs to meet desired needs within
realistic constraints of time and space. The student can use current techniques, skills and tools
necessary to practice as a CSE professional and continuing professional development. The
student gains knowledge of subject to apply design and development principles in producing
software systems of varying complexity

9. Prerequisites if any

i) Knowledge in programming i.e., C language

10. Instructional Learning Outcomes

Unit-I:
Students gain ability to

13
1. Explain and apply object oriented concepts
2. Differentiate Procedural and object oriented paradigms
3. Explain features of Java programming language
4. Apply the Concepts of inheritance.

Unit-II
1. Apply the Concepts of inheritance, Polymorphism and Interfaces and Packages
2. Design abstract classes and interfaces and analyze when to use them.
3. Create and access a package.
4.Define Inheritance and Explain types of Inheritance.

Unit-III
1. Handle Exceptions and create own exception sub classes.
2. Multithread programming with an ability to synchronize threads.
3. Exploring Java.Util Package.

Unit- IV
1. Handle Exceptions and create own exception sub classes.
2. Multithread programming with an ability to synchronize threads.
3. Differentiate between checked and unchecked exceptions
4. Write a java program on producer consumer pattern

Unit-V
1. File management with a clear understanding of different kinds of input output streams
2. Connecting and querying a database using JDBC

11. Class Time Table

14
12. Individual Time Table:

13. Lecture schedule with methodology being used/adopted

SNO LECTURE TOPIC NAME Methodology Remarks


NO OHP/Board/LCD
UNIT I
1 1 Introduction to subject: Objectives , Board
Outcomes,Object Oriented
Programming Concepts
2 2 classes and objects, Concepts of Board
classes
3 3,4 Oop’s Principles, Benefits of Board
Inheritance, Polymorphism
4 5 History of JAVA, comments, Data Board
Types
5 6 classes and objects, Concepts of Board
classes
6 7 Variables,Constants,Scope and life Board
time of variables
7 8,9 Procedural and Object Oriented Board
Paradigms
Total classes for unit1 : 09
UNIT-II
8 10 Operators, Expressions, type Board
conversion, Type casting.
9 11 Enums, Conditional Statements. Board
10 12&13 Loops, break and continue stmt Board
,Simple java program.
11 14 Arrays, Console I/O, Formatted I/O. Board
12 15 Constructors, Methods, Parameter Board

15
passing

13 16 Static fields, Access control, This Board


keyword
14 17 overloading methods,Recurssion Board
15 18,19 Garbage collection, Board
Strings(Building/Exploring)
16 20 Interfaces vs. abstract classes Board
Total classes for unit2 : 11
UNIT III
17 21 Abstract classes and methods. Board
18 22,23 Implementing Interfaces, Extending Board
interfaces.
19 24 Inner classes, Anonymous inner Board
classes. Static inner classes.

20 25 Packages: Class path, Import class Board


path
Total classes for unit3 : 10
UNIT IV
21 26 Exceptions,uses,classification of Board
exception, Hierarchy
22 27 Checked& unchecked Exceptions Board
23 28 Exception handlers, Exception Board
specifications.
24 29 Built-in exceptions create own Board
exceptions
25 30 Differences between multithreads and Board
multi process.
26 31,32 Thread life cycle, Thread priorities.
27 33 Creating threads, Synchronizing Board
threads.
28 34 Inter thread communication, Board
Producer-consumer pattern
Total classes for unit4 : 9
UNIT V
29 35,36 Byte streams, character streams Board
30 37 Board
Text I/O, Binary I/O

31 38,39 Random Access File operations. Board

16
32 40 File Management using file classes. Board
33 41 JDBC Type I to IV Drivers Board
34 42 Querying a database and processing Board
the result
35 43 Connecting to Data base. Board

36 44 Updating Data with JDBC Board


Total classes for unit5 : 10

14. Lesson schedule:

Lesson Plan Schedule


SNO LECTURE TOPIC NAME Methodology Remarks
NO OHP/Board/LCD
UNIT I
1 1 Introduction ,Object Oriented Board
Programming Concepts.
2 2 Classes and objects, Concepts of classes Board
3 3,4 Oops Principles, Benefits of Inheritance, Board
Polymorphism
4 5 History of JAVA, comments, Data Types Board
5 6 classes and objects, Concepts of classes Board
6 7 Variables,Constants,Scope and life time Board
of variables
7 8,9 Procedural and Object Oriented Board
Paradigms
Total classes for unit1 : 09
UNIT-II
8 10 Operators, Expressions, type conversion, Board
Type casting.
17
9 11 Enums, Conditional Statements. Board
10 12&13 Loops, break and continue stmt ,Simple Board
java program.
11 14 Arrays, Console I/O, Formatted I/O. Board
12 15 Constructors, Methods, Parameter Board
passing

13 16 Static fields, Access control, This Board


keyword
14 17 overloading methods,Recuession Board
15 18,19 Garbage collection, Board
Strings(Building/Exploring)
16 20 Interfaces vs abstract classes Board
Total classes for unit2 : 11
UNIT III
17 21 Abstract classes and methods. Board
18 22,23 Implementing Interfaces, Extending Board
interfaces.
19 24 Inner classes, Anonymous inner classes. Board
Static inner classes.

20 25 Packages: Class path, Import class path Board


Total classes for unit3 : 10
UNIT IV
21 26 Exceptions,uses,classification of Board
exception, Hierarchy
22 27 Checked& unchecked Exceptions Board
23 28 Exception handlers, Exception Board
specifications.
24 29 Built-in exceptions create own exceptions Board
25 30 Differences between multithreads and Board
multi process.
26 31,32 Thread life cycle, Thread priorities.
27 33 Creating threads, Synchronizing threads. Board
28 34 Inter thread communication, Producer- Board
consumer pattern
Total classes for unit4 : 9
UNIT V
29 35,36 Byte streams, character streams Board
30 37 Text I/O, Binary I/O Board
31 38,39 Random Access File operations. Board
32 40 File Management using file classes. Board

18
33 41 JDBC Type I to IV Drivers Board
34 42 Querying a database and processing the Board
result
35 43 Connecting to Data base. Board

36 44 Updating Data with JDBC Board


Total classes for unit5 : 10

19
15. Detailed notes

Unit-I

Object-oriented programming (OOP):

Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which may contain data, in the form of fields, often known as attributes; and code, in
the form of procedures, often known as methods.

Object:
Any real world entity is called object. Any entity that has state and behavior is known as an
object. For example: chair, pen, table, keyboard, bike, car etc. It can be physical and logical.
Need for OOP paradigm:

The major objective of Object-oriented approach is to eliminate some of the flaws /problems
encountered in the procedural approach or structured programming techniques or Procedural
oriented programming.

With object oriented programming, allows us to decompose a problem into a number of entities
(units) called objects. and then build data and methods around these entities.

The combination of data and methods makeup an object.

Object=data+ methods

The data of an object can be accessed only by methods associated with that object.

Some of the features of Object-oriented paradigm:

1. Give more importance on data rather than procedure.

2. Data is secure i.e. controlled access on data

3. Programs are divided into objects.

4. Objects communicate with each other through methods

5. Code reusability

6. Follows bottom – up approach in program design.

Examples of object oriented languages:

Java, C++, C#, Python, PHP, Ruby, Perl, Common Lisp, and Smalltalk.

The object oriented paradigm is a methodology for producing reusable software components.

20
Disadvantages of Procedural languages:
1. Procedural languages are difficult to relate with the real world objects.
2. Procedural codes are very difficult to maintain, if the code grows larger.
3. Procedural languages does not have automatic memory management as like in Java.
Hence, it makes the programmer to concern more about the memory management of the
program.
4. The data, which is used in procedural languages are exposed to the whole program. So,
there is no security for the data.
 Examples of Procedural languages : BASIC, C, Pascal, FORTRAN

OOPS Concepts:
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Polymorphism
6. Inheritance
1. Object:
Object means a real word entity.
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike, car etc. It can be physical and logical.
2. Class
Collection of objects is called class. It is a logical entity.
Class is a blueprint of object.
A class is the blueprint from which individual objects are created.
Syntax:
Class <class name>
{ attributes/variables;
methods();
}

21
Example:
Class Car
{
int modelnumber;
String color;
String name;
void start()
{
}
void move()
{
}
void stop()
{
}

3. Abstraction

Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.

Hiding un necessary Details or features but exposing only essential details or features.

Real Time Example:

In Real Time if we consider the TV Remote or Computer or laptop Keyboard has Buttons in
Structured format, those are only visible to us. But hardware materials like inner circuit, device
all are invisible in same manner.

In java, we use abstract class and interface to achieve abstraction

4. Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.

That keeps the data in safe manner from outside of the interface and also to avoid misuse.

22
Encapsulation= Abstraction+ data hiding

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.

5. Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

Polymorphism means ability to take more than one form that an operation can exhibit different
behavior at different instance depend upon the data passed in the operation.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

6. Inheritance
When one object acquires all the properties and behaviors of parent object i.e. known as
inheritance. It provides code reusability.
Deriving a new class from the existing class is called inheritance.
It is used to achieve runtime polymorphism.
1. Object - Instance of Class
2. Class - Blue print of Object
3. Encapsulation - Protecting our Data
4. Polymorphism - Different behaviors at different instances
5. Abstraction - Hiding our irrelevant Data
6. Inheritance - One property of object is acquiring to another property of object

Benefits of inheritance
 The most frequent use of inheritance is for deriving classes using existing classes, which
provides reusability. ...
 The derived classes extend the properties of base classes to generate more dominant
objects.
 The same base classes can be used by a number of derived classes in class hierarchy.

23
Procedural and Object oriented programming paradigms

Procedure Oriented Programming Object Oriented Programming


Divided Into In POP, program is divided into small partsIn OOP, program is divided into parts
called functions. called objects.
Importance In POP,Importance is not given to data but In OOP, Importance is given to the data
to functions as well as sequence of actions rather than procedures or functions because
to be done. it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access specifier. OOP has access specifiers named Public,
Specifiers Private, Protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move and communicate
function to function in the system. with each other through member functions.
Expansion To add new data and function in POP is OOP provides an easy way to add new data
not so easy. and function.
Data Access In POP, Most function uses Global data for In OOP, data can not move easily from
sharing that can be accessed freely from function to function,it can be kept public or
function to function in the system. private so we can control the access of data.
Data Hiding POP does not have any proper way for OOP provides Data Hiding so
hiding data so it is less secure. provides more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
Examples Example of POP are : C, VB, FORTRAN, Example of OOP are : C++, JAVA,
Pascal. VB.NET, C#.NET.

History of Java
1. Brief history of Java
2. Java Version History

Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc

24
Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax: //This is single line comment

Example:

1. public class CommentExample1 {


2. public static void main(String[] args) {
3. int i=10;//Here, i is a variable
4. System.out.println(i);
5. }
6. }

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

1. /*
2. This
3. is

25
4. multi line
5. comment
6. */

3)Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API,
you need to use javadoc tool.

Syntax:

1. /**
2. This
3. is
4. documentation
5. comment
6. */
Datatypes

There are 8 types of primitive data types:

o Boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

26
int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8

Variables

A variable is a container which holds the value while the java program is executed. A variable is
assigned with a datatype.

Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

There are two types of data types in java: primitive and non-primitive.

Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.

int data=50;//Here data is variable

Types of Variable

There are three types of variables in java:

Local variable

Instance variable

Static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

27
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among
instances.

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in the memory.

Constants

A constant is a variable whose value cannot change once it has been assigned. Javadoesn't have
built-in support for constants, but the variable modifiers static and final can be used to
effectively create one.

Constants can make your program more easily read and understood by others. In addition, a
constant is cached by the JVM as well as your application, so using a constant can improve
performance.

Scope and life time of variables


Scope of a variable refers to in which areas or sections of a program can the variable be accessed
and lifetime of a variable refers to how long the variable stays alive in memory.

General convention for a variable’s scope is, it is accessible only within the block in which it is
declared. A block begins with a left curly brace { and ends with a right curly brace }.

Scope of a variable refers to in which areas or sections of a program can the variable be
accessed and lifetime of a variable refers to how long the variable stays alive in memory.

General convention for a variable’s scope is, it is accessible only within the block in which it is
declared. A block begins with a left curly brace { and ends with a right curly brace }.

As we know there are three types of variables: 1) instance variables, 2) class variables and 3)
local variables, we will look at the scope and lifetime of each of them now.

Instance Variables

A variable which is declared inside a class and outside all the methods and blocks is an instance
variable.

28
General scope of an instance variable is throughout the class except in static
methods. Lifetime of an instance variable is until the object stays in memory.

Class Variables

A variable which is declared inside a class, outside all the blocks and is marked static is known
as a class variable.

General scope of a class variable is throughout the class and the lifetime of a class variable is
until the end of the program or as long as the class is loaded in memory.

Local Variables

All other variables which are not instance and class variables are treated as local variables
including the parameters in a method.

29
Scope of a local variable is within the block in which it is declared and the lifetime of a local
variable is until the control leaves the block in which it is declared.

Nested Scope

In Java, we can create nested blocks – a block inside another block. In case of nested blocks
what is the scope of local variables?

All the local variables in the outer block are accessible within the inner block but vice versa is
not true i.e., local variables within the inner block are not accessible in the outer block. Consider
the following

1 class Sample
2{
3 public static void main(String[] args)
4 {
5 int x;
6 //Begining of inner block
7 {
8 int y = 100;
9 x = 200;
10 System.out.println("x = "+x);
11 }
12 //End of inner block
13 System.out.println("x = "+x);
14 y = 200; //Error as y is not accessible in the outer block
15 }
16 }

As you can see in the above program, line 14 generates an error as the variable y is not visible in
the outer block and therefore cannot be accessed.

30
The summary of scope and lifetime of variables is as shown below:

UNIT-2

Operators:
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to

31
operate data and variables. They frequently form a part of mathematical or logical expressions.
Categories of operators are as follows:

1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators

Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the working out as same in
algebra. Java provides the fundamental arithmetic operators. These can operate on built in data
type of Java.
Following table shows the details of operators.

Operator Importance/ significance


+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo division or remainder

Logical operators:
When we want to form compound conditions by combining two or more relations, then we can
use logical operators.
Following table shows the details of operators.

Operators Importance/ significance


|| Logical – OR
&& Logical –AND
! Logical –NOT

The logical expression defer a value of true or false. Following table shows the truth table of
Logical – OR and Logical – AND.

Truth table for Logical – OR operator:

Operand1 Operand3 Operand1 || Operand3


T T T

32
T F T
F T T
F F F

T - True
F - False

Truth table for Logical – AND operator:

Operand1 Operand3 Operand1 && Operand3


T T T
T F F
F T F
F F F

T - True
F – False

Relational Operators:

When evaluation of two numbers is performed depending upon their relation, assured decisions
are made. The value of relational expression is either true or false.If A=7 and A < 10 is true while
10 < A is false.
Following table shows the details of operators.

Operator Importance/ significance


> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to

Assignment Operators:
Assignment Operators is used to assign the value of an expression to a variable and is also called
as Shorthand operators.
Variable_name binary_operator = expression
Following table show the use of assignment operators.

Simple Assignment Operator Statement with shorthand Operators


A=A+1 A+=1
A=A-1 A-=1
A=A/(B+1) A/=(B+1)
A=A*(B+1) A*=(B+1)
A=A/C A/=C
A=A%C A%=C

33
These operators avoid repetition, easier to read and write.
Now the following program shows the use of operators.

Conditional Operators:
The character pair ?: is a ternary operator of Java, which is used to construct conditional
expressions of the following form:
Expression1 ? Expression3 : Expression3
The operator ? : works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value of the
conditional expression. If Expression1 is false then Expression3 is evaluated and its value
becomes the conditional expression.

Increment and Decrement Operators:

The increment operator ++ adds 1 to a variable. Usually the variable is an integer type, but it can
be a floating point type. The two plus signs must not be split by any character. Usually they are
written immediately next to the variable.
Following table shows the use of operators.

Expression Process Example end result


A++ Add 1 to a variable int A=10,B; A=11
after use. B=A++; B=10
++A Add 1 to a variable int A=10,B; A=11
before use. B=++A; B=11
A-- Subtract 1 from a int A=10,B; A=9
variable after use. B=A--; B=10
--A Subtract 1 from a int A=10,B; A=9
variable before use. B=--A; B=9

Now the following program shows the use of operators.

Bit Wise Operators:


Bit wise operator execute single bit of their operands. Following table shows bit wise operator:

Operator Importance/ significance


| Bitwise OR
& Bitwise AND
&= Bitwise AND assignment
|= Bitwise OR assignment
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
~ One‘s complement

34
Separators are symbols. It shows the separated code.they describe function of our code.

Name Use
() Parameter in method definition, containing statements for conditions,etc.
{} It is used for define a code for method and classes
[] It is used for declaration of array
; It is used to show the separate statement
, It is used to show the separation in identifier in variable declarartion
. It is used to show the separate package name from sub-packages and classes,
separate variable and method from reference variable.

Operator Precedence in Java:


An arithmetic expression without any parentheses will be calculated from left to right using the
rules of precedence of operators.
There are two priority levels of arithmetic operators are as follows:
(a) High priority (* / %)
(b) Low priority (+ -)

The evaluation process includes two left to right passes through the expression. During the first
pass, the high priority operators are applied as they are encountered.
During the second pass, the low priority operators are applied as they are encountered.

For example:
Z=A-B/3+C*3-1
When A=10, B=13, C=3
First pass:
Z=10-(13/3) + (3*3)-1
Z=10-4+3-1

Second pass:
Z=6+3-1
Z=7
Answer is=7

Type conversions and casting

If the two types are compatible, then Java will perform the conversion automatically. For
example, assign an int value to a long variable. For incompatible types we must use a cast.

An automatic type conversion will be used if the following two conditions are met:

1. The two types are compatible.


2. The destination type is larger than the source type.

35
If we want to convert two types which are incompatible or if the size of destination type is less
than the size of source type, then we must do the conversion explicitly. This process is also called
as “type casting”.
Syntax for type casting is:

(destination type) value;

Java promotes various types in expressions based on the following rules:


1) byte, short and char values are converted into values of type int.
2) If one operand is long, entire expression is promoted to long.
3) If one operand is float, entire expression is promoted to float.
4) If one operand is double, entire expression is promoted to double.

Enumerated types

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc.
The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

1. class EnumExample1{
2. public enum Season { WINTER, SPRING, SUMMER, FALL }
3. public static void main(String[] args) {
4. for (Season s : Season.values())
5. System.out.println(s);
6. }}

Control flow block scope, Conditional statements, Loops break:

Control Structure:
In java program, control structure is can divide in three parts:

36
Selection statement
Iteration statement
Jumps in statement

Selection Statement:

Selection statement is also called as Decision making statements because it provides the decision
making capabilities to the statements.
In selection statement, there are two types:
if statement
switch statement
These two statements are allows you to control the flow of a program with their conditions.

if Statement:

The “if statement” is also called as conditional branch statement. It is used to program execution
through two paths. The syntax of “if statement” is as follows:

Syntax:
if (condition)
{
Statement 1;
Statement 2;
...
}
else
{
Statement 3;
Statement 4;
...
}

The “if statement” is a commanding decision making statement and is used to manage the flow
of execution of statements. The “if statement” is the simplest one in decision statements. Above
syntax is shows two ways decision statement and is used in combination with statements.

Simple if statement:
In statement block, there may be single statement or multiple statements. If the condition is true
then statement block will be executed. If the condition is false then statement block will omit and
statement-a will be executed.
The if…else statement:

Syntax:
If (condition)

37
{
True - Statement block;

}
else
{
False - Statement block;
}
Statement-a;

If the condition is true then True - statement block will be executed. If the condition is false then
False - statement block will be executed. In both cases the statement-a will always executed.

Following program shows the use of if statement.

Nesting of if-else statement:

Syntax:

if (condition1)
{
If(condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
Statement 4;
If the condition1 is true then it will be goes for condition2. If the condition2 is true then
statement block1 will be executed otherwise statement2 will be executed. If the condition1 is
false then statement block3 will be executed. In both cases the statement4 will always executed.

switch statement:

38
In Java, switch statement check the value of given variable or statement against a list of case
values and when the match is found a statement-block of that case is executed. Switch statement
is also called as multiway decision statement.
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;

default:statement block-default;break;
}
statement a;

The condition is byte, short, character or an integer. value-1,value-2,value-3,…are constant and


is called as labels. Each of these values be matchless or unique with the statement. Statement
block1, Statement block2, Statement block3,..are list of statements which contain one statement
or more than one statements. Case label is always end with “:” (colon).

Iteration Statement:
The process of repeatedly executing a statements and is called as looping. The statements may be
executed multiple times (from zero to infinite number). If a loop executing continuous then it is
called as Infinite loop. Looping is also called as iterations.

In Iteration statement, there are three types of operation:


for loop
while loop
do-while loop

for loop:

The for loop is entry controlled loop. It means that it provide a more concious loop control
structure.
Syntax:
for(initialization;condition;iteration)//iteration means increment/decrement
{
Statement block;
}

When the loop is starts, first part(i.e. initialization) is execute. It is just like a counter and
provides the initial value of loop. But the thing is, I nitialization is executed only once. The next
part( i.e. condition) is executed after the initialization. The important thing is, this part provide
the condition for looping. If the condition will satisfying then loop will execute otherwise it will
terminate.
Third part(i.e. iteration) is executed after the condition. The statements that incremented or
decremented the loop control variables.

39
Here we declare i=1 and then it check the condition that if i<10 then only loop will be executed.
After first iteration the value of i will print and it will incremented by 1. Now the value of i=2
and again we have to check the condition and value of i will print and then increment I by 1 and
so on.

while loop:
The while loop is entry controlled loop statement. The condition is evaluated, if the condition is
true then the block of statements or statement block is executed otherwise the block of statement
is not executed.

Syntax:
While(condition)
{
Statement block;
}

do-while loop:
In do-while loop, first attempt of loop should be execute then it check the condition.
The benefit of do-while loop/statement is that we get entry in loop and then condition will check
for very first time. In while loop, condition will check first and if condition will not satisfied then
the loop will not execute.

Syntax:
do
{
Statement block;
}
while(condition);

In program,when we use the do-while loop, then in very first attempt, it allows us to get enter in
loop and execute that loop and then check the condition.

Simple Java Program:


class FirstProgram
{
public static void main(String args[]){
System.out.println(―This is my first program‖);
}}
 The file must be named ―FirstProgram.java‖ to equivalent the class name containing
the main method .Java is case sensitive. This program defines a class called ―First
Program‖.
 A class is an object oriented term. It is designed to perform a specific task. A Java class
is defined by its class name, an open curly brace, a list of methods and fields, and a
close curly brace.

40
 The name of the class is made of alphabetical characters and digits without spaces, the
first character must be alphabetical.The line ―public static void main (String [] args )‖
shows where the program will start running. The word main means that this is the main
method –The JVM starts running any program by executing this method first.
The main method in ―FirstProgram.java‖ consists of a single statement.
System.out.println ("This is my first program");
The statement outputs the character between quotes to the console.
Above explanation is about how to write program and now we have to learn where to write
program and how to compile and run the program.

For this reason, the next explanation is showing the steps.


1. Edit the program by the use of Notepad.
2. Save the program to the hard disk.
3. Compile the program with the javac command.(Java compiler)
4. If there are syntax errors, go back to Notepad and edit the program.
5. Run the program with the java command.(Java Interpreter)
6. If it does not run correctly, go back to Notepad and edit the program.
7. When it shows result then stop.

The Java Buzzwords:-


The key considerations were summed up by the Java team in the following list of buzzwords:
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic
Arrays:-
• An array is a group of liked-typed variables referred to by a common name, with
individual variables accessed by their index. Arrays are:
1) declared 2) created 3) initialized 4) used
Array Creation:-
• In order to create an array, we use the new operator: type array-variable[];
array-variable = new type[size];

Console input and output, formatting output

41
In Java, there are three different ways for reading input from the user in the command line
environment(console).
1.Using Buffered Reader Class

This is the Java classical method to take input, Introduced in JDK1.0. This method is used by
wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the command line.
Advantages

The input is buffered for efficient reading.

Program:
// Java program to demonstrate BufferedReader

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Test

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

//Enter data using BufferReader

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// Reading data using readLine

String name = reader.readLine();

// Printing the read line

System.out.println(name);

2. Using Scanner Class

42
This is probably the most preferred method to take input. The main purpose of the Scanner class
is to parse primitive types and strings using regular expressions, however it is also can be used to
read input from the user in the command line.
Advantages:

 Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized
input.
 Regular expressions can be used to find tokens.

// Java program to demonstrate working of Scanner in Java

import java.util.Scanner;

class GetInputFromUser

public static void main(String args[])

// Using Scanner for Getting Input from User

Scanner in = new Scanner(System.in);

String s = in.nextLine();

System.out.println("You entered string "+s);

int a = in.nextInt();

System.out.println("You entered integer "+a);

float b = in.nextFloat();

System.out.println("You entered float "+b);

}}

3. Using Console Class


It has been becoming a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the characters entered
by the user; the format string syntax can also be used (like System.out.printf()).

Advantages:

43
 Reading password without echoing the entered characters.
 Reading methods are synchronized.
 Format string syntax can be used.

Drawback:

 Does not work in non-interactive environment (such as in an IDE).


// Java program to demonstrate working of System.console()

// Note that this program does not work on IDEs as

// System.console() may require console

public class Sample

public static void main(String[] args)

{ // Using Console to input data from user

String name = System.console().readLine();

System.out.println(name);

}
CONSTRUCTOR:-
• A constructor initializes the instance variables of an object.
• It is called immediately after the object is created but before the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return type of a class
• constructor is the same class.
• When the class has no constructor, the default constructor automatically initializes all its
instance variables with zero.

METHODS:-
• General form of a method definition:
type name(parameter-list) {
… return value;

}
• Components:

44
1) type - type of values returned by the method. If a method does not return
any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method.

METHOD OVERLOADING:-
• It is legal for a class to have two or more methods with the same name.
• However, Java has to be able to uniquely associate the invocation of a method with its
definition relying on the number and types of arguments.
• Therefore the same-named methods must be distinguished:
• 1) by the number of arguments, or
• 2) by the types of arguments
Overloading and inheritance are two ways to implement polymorphism.

Parameter Passing:-
• Two types of variables: 1) Simple types 2) class types
• Two corresponding ways of how the arguments are passed to methods:
1) By value a method receives a cope of the original value; parameters of simple types
2) By reference a method receives the memory address of the original value, not the value
itself; parameters of class types
Data type Size (byte) Range
Fig: byte 1 -128 to 127 Datatypes
with size boolean 1 True or false and range
char 2 A-Z,a-z,0-9,etc.
Static short 2 -32768 to 32767 fields and
methods
Int 4 (about) -2 million to 2 million
long 8 (about) -10E18 to 10E18
Static variable
in Java is float 4 -3.4E38 to 3.4E18 variable
which double 8 -1.7E308 to 1.7E308 belongs to
the class and initialized only once at the start of the execution.

 It is a variable which belongs to the class and not to object(instance)


 Static variables are initialized only once, at the start of the execution. These variables will
be initialized first, before the initialization of any instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn’t need any object

Syntax :

<class-name>.<variable-name>

Static method in Java is a method which belongs to the class and not to the object. A static
method can access only static data.

45
 It is a method which belongs to the class and not to the object(instance)
 A static method can access only static data. It can not access non-static data (instance
variables)
 A static method can call only other static methods and can not call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn’t need any object
 A static method cannot refer to "this" or "super" keywords in anyway

Syntax :

<class-name>.<method-name>

Access control:

Access Modifiers: Public, Private, Protected and default


• Public: keyword applied to a class, makes it available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it behaves like public in its package and
private in other packages.
• Default Public keyword applied to a class, makes it available/visible everywhere. Applied
to a method or variable, completely visible.

There are two types of modifiers in java: access modifiers and non-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.

this keyword

46
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method.

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes.

Overloading methods

47
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Constructors recursion
In a class you can define methods, but there is a special type of methods which are used to solve
a particular problem, to construct objects. Constructor methods are special because of their role
and because they have a lot rules regarding declaration and usage.

Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.
Every time an object is created, a constructor is called. Based on this fact, in Java, every class
has at least one constructor, even if the programmer hasn’t explicitly declared one.
The constructor methods roles are:

main role – to construct objects, meaning to allocate space in Heap

secondary role [optional] – to initialize instance variables with default (remember, that instance
variables get their default value when the object is created) or given values;

Considering the given class and the main method

public class Book {


float price;
String title;
String author;

public static void main(String[] args)


{
48
//create a book
Book b1 = new Book();
}
}
it is obvious that in main() method it is constructed an object of type Book, referenced by
the b1reference. So, where is the constructor ?. One rule regarding constructors states that the
compiler will provide a default constructor (a no-arguments one) if there are no explicitly
declared constructors.The form of the default constructor, generated by the compiler, is :
public Book()
{

}
Rules for declaring and calling constructors in Java
 constructors have the same name (case-sensitive) as the parent class;
 constructors don’t have a return type (it is logic because they always return a reference to
the constructed object); methods with the same name as the class but with a return type are
common methods and NOT constructors:
public class Book {
//NOT a constructor - has a return type
public void Book(){
System.out.println("A simple no-sense method !");
}
public static void main(String[] args)
{
//create a book with the default constructor
Book b1 = new Book();
b1.Book(); //call the method
}
}

 constructors can be declared public or private (for a Singleton) – more on access


modifiers in the next posts;
 constructors can have no-arguments, some arguments and var-args;
//no-arg constructor
public Book(){
price = 100;
title = "Nothing";
}
//3 arguments constructor
public Book(float Price, String Title, String Author){
price = Price;
title = Title;
author= Author;
}
//2 arguments constructor
public Book(String Title, String Author){
49
price = 0; //default value
title = Title;
author= Author;
}
//var-arg constructor
public Book(float Price, String ... someStrings){
//some processing here
}

 the default constructor is a no-arguments one;


 if you don’t write ANY constructor, the compiler will generate the default one;
 if you write at least one constructor (doesn’t matter its arguments) the compiler will NOT
generate the default one;
 if you write at least one constructor and you need the default one, you must write it;
otherwise you get a compiler error when you try to call it:
public class Book {
float price;
String title;
String author;

//2 arguments constructor


public Book(String Title, String Author){
price = 0; //default value
title = Title;
author = Author;
}
public static void main(String[] args){
//create a book
Book b1 = new Book(); //compiler error
//cannot find symbol : constructor Book()
}

 constructors CAN’T be static,final or abstract;


 inside a constructor you can use this reference to refer the constructed object (useful to
avoid shadowing –

public Book(float Price, String title, String Author){


this.price = Price; //this is optional
this.title = title; //must use this
author = Author;
}

 the first statement in a constructor is a call to another constructor using this() or to a


superclass constructor using super() (more on that in the inheritance topic); if you don’t use

50
either this() or super(), the compiler will make the super() call; in order to understand who
is super() you must know something about inheritance (next topics in this tutorial)
//2 arguments constructor
public Book(String Title, String Author){
//super();//compiler generated if you don't write it
//in this case calls the Object class constructor
price = 0; //default value
title = Title;
author = Author;
}

//3 arguments constructor


public Book(float Price, String Title, String Author){
this(Title,Author); //explicit call to the 2 arguments constructor
//MUST be the first statement
//without it, the compiler puts super();
price = Price;
}

 a constructor is called with new operator or using this() from another constructor; it is
not allowed to call constructors as any other method;
Book myBook = new Book(23,"Dune","Frank Herbert"); //ok

Book(23,"Dune","Frank Herbert"); //compiler error


myBook.Book(23,"Dune","Frank Herbert"); //compiler error

 when calling other constructors with this() watch out for cross-calls that can generate
infinite recursion and StackOverflowError runtime exception (some compilers may catch
the problem and may generate a recursive constructor invocation error:
public Book(String Title, String Author){
this(0,Title,Author); //calls the 3 arguments constructor
}
//3 arguments constructor
public Book(float Price, String Title, String Author){
this(Title,Author); //calls the 2 arguments constructor
//MUST be the first statement
price = Price;
}

 constructors have access to static methods or variables;


 abstract classes have constructors;
 when overloading constructors (defining methods with the same name but with different
arguments lists) you must define them with different arguments lists (as number or as type)

Garbage collection:-
51
Garbage collection is a mechanism to remove objects from memory when they are no longer
needed.
Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many references an object has.
2) It removes an object from memory when it has no longer any references.
3) Thereafter, the memory occupied by the object can be allocated again.
4) The garbage collector invokes the finalize method.

Building strings, exploring string class.

A String is a sequence of characters. In many other languages a string is treated as a character


array. But in Java a string is treated as an object. After creating a string object you can not
change it. So that is why it is said that a string is immutable. Java provides three string classes
named String, StringBuffer and StringBuilder. The reason for three class is to reduce the problem
of the mutability of the StringBuffer and StringBuilder classes; both are mutable. But in your
mind you might ask why not remove the String class. The reason is that an immutable
String can be implemented more efficiently. The StringBuffer and StringBuilder classes have the
same methods with one difference and that's synchronization. A StringBuffer is synchronized
(which means it is thread safe and hence you can use it when you implement threads for your
methods) whereas StringBuilder is not synchronized (which implies it isn't thread safe). So, if
you aren't going to use threading then use the StringBuilder class as it wll be
more efficient than StringBuffer due to the absence of synchronization.

The String class has several constructors (near about 13) and several methods (near about more
than 60) so it's not possible to describe all of them but the important constructors and methods
are described in this article.
Constructor

Initializes a newly created String object so that it represents an empty


String()
character sequence.
String(Char Allocates a new String so that it represents the sequence of characters
chars[]) currently contained in the character array argument.
Initializes a newly created String object so that it represents the same
String(String
sequence of characters as the argument; in other words, the newly
strobj)
created string is a copy of the argument string.
String(byte[] Constructs a new String by decoding the specified array of bytes using
bytes) the platform's default charset.

Methods

52
Return
Name Description
Type
Char charAt(int index) Returns the char value at the specified index.
compareTo(String
Int Compares two strings lexicographically.
anotherString)
compareToIgnoreCase( String Compares two strings lexicographically, ignoring case
Int
str) differences.

String concat(String str) Concatenates the specified string to the end of this string.

Returns the index within this string of the first occurrence


Int indexOf(int ch)
of the specified character
replace(char oldchar, char Returns a new string resulting from replacing all
string
newchar) occurrences ofoldChar in this string with newChar.
Int length() Returns the length of this string.
char[] toCharArray() Converts this string to a new character array.
Returns a copy of the string, with leading and trailing
String trim()
whitespace omitted.
Static
valueOf(Object obj) Returns the string representation of the Object argument.
String

UNIT-III

53
Interfaces
Abstract class, which allows you to create methods in a class without writing the code for
execution of the method (implementation of the method).

Inheritance through the keyword ‘extends’ which tells the machine that an (inherited) class
defined is of the type of a base class.

Methods in the inherited class must provide implementation. (except when the inherited class is
an Abstract class as well.

Interface takes the above concepts even further. It provides a mechanism to define a class with
absolutely no implementation (code for execution of a method or logic).

One or more classes can implement a defined interface


When a class implements a defined interface, it has to implement (write the code, execution
logic) for all the methods defined by the

Syntax of Interface
To define an interface, use the interface keyword instead of the class keyword.

package xxx.xxx;
interface MusicPlayer{
// Cannot have method implementations: void on();
void off(); void play(); void stop();
}

Multiple Inheritance
In Java, there is nothing which prevents from inheriting from multiple interfaces. Since there are
no implementations in the methods (code in the methods), there is no danger or overwriting any
implementations between multiple interfaces.
// Multiple interfaces.
interface MusicPlayer { void on();
void off(); void play(); void stop();
}
}
interface VideoPlayer{ void on();void off(); void play(); void stop();
void changeContrast(int x); void changeBrightness(int x);
}
}
class iPod implements MusicPlayer, VideoPlayer{
public void on(){
System.out.println(“the MP3 Player is ON”);
}
public void off(){
System.out.println(“the MP3 Player is OFF”);
}

54
public void play(){
System.out.println(“the MP3 Player is playing”);
}

public void stop(){

System.out.println(“the MP3 Player is off”);

}
public void changeContrast(int x){ System.out.println(“Constrast Changed by” + x);
}

Interfaces Vs Abstract Classes

Interfaces are similar to abstract classes. The differences are as follows:

1. All methods in an interface are abstract. Which means all methods must be empty; no
code implemented.
2. In abstract class, the methods can have code/implementation within it. Atleast one
method must be abstract.
3. All properties (data fields) in an interface are static final. Properties in an abstract class
need not be static final.
4. Interfaces are implemented(implements keyword); Abstract classes are extended(extends
keyword)
5. Class can extend only one abstract class; where as a class can implement multiple
interfaces (multiple inheritance)
6. Contractual obligation: When a class specifies that it implements an interface, it must
define all methods of that interface. A class can implement many different interfaces. If a
class doesn't define all methods of the interfaces it agreed to define (by the implements
clause), the compiler gives an error message, which typically says something like "This
class must be declared abstract". An abstract class is one that doesn't implement all
methods it said it would. The solution to this is almost always to implement the missing
methods of the interface. A misspelled method name or incorrect parameter list is the
usual cause, not that it should have been abstract!

Inner classes
Inner classes are classes that are declared within other classes. They are also knows as nested
classes and provide additional clarity to the program. The scope of the inner class is limited to
the class that encloses it. The object of the inner class can access the members of the outer class.
While the outer class can access the members of the inner class through an object of the inner
class.

Syntax:

55
class
{
class
{

}
//other attributes and methods
}
why prevent inheritance?

The main reason to prevent inheritance is to make sure the way a class behaves is not corrupted
by a subclass.

how to prevent inheritance

To stop a class from being extended, the class declaration must explicitly say it cannot be
inherited.

This is achieved by using the "final" keyword:

Defining a Package:-

A package is both a naming and a visibility control mechanism:


1) divides the name space into disjoint subsets It is possible to define classes within a package
that are not accessible by code outside the package.
2) controls the visibility of classes and their members It is possible to define class members that
are only exposed to other members of the same package.
 Same-package classes may have an intimate knowledge of each other, but not expose that
knowledge to other packages.

Creating a Package:-
 A package statement inserted as the first line of the source file:
package myPackage;
class MyClass1 { … }
class MyClass2 { … }
 means that all classes in this file belong to the myPackage package.
 The package statement creates a name space where such classes are stored.
 When the package statement is omitted, class names are put into the default package
which has no name.

CLASSPATH Variable:-

56
 CLASSPATH - environment variable that points to the root directory of the system’s
package hierarchy.
 Several root directories may be specified in CLASSPATH,
 e.g. the current directory and the C:\raju\myJava directory:
.;C:\raju\myJava
 Java will search for the required packages by looking up subsequent directories described
in the CLASSPATH variable.

Importing of Packages:-
 Since classes within packages must be fully-qualified with their package names, it would
be tedious to always type long dot-separated names.
 The import statement allows to use classes or whole packages directly.

Import Statement:-
 The import statement occurs immediately after the package statement and before the class
statement:
package myPackage;
 import otherPackage1;otherPackage2.otherClass;
class myClass { … }
 The Java system accepts this import statement by default:
import java.lang.*;
 This package includes the basic language functions. Without such functions, Java is of no
much use.
 Provides for system input and output through data streams, serialization and the file
system.

Package java.io
 Provides for system input and output through data streams, serialization and the file
system Interface Summary
 .DataInput The DataInput interface provides for reading bytes from a binary stream and
reconstructing from them data in any of the Java primitive types.
 DataOutputThe DataOutput interface provides for converting data from any of the Java
primitive types to a series of bytes and writing these bytes to a binary stream
 .Externalizable Only the identity of the class of an Externalizable instance is written in
the serialization stream and it is the responsibility of the class to save and restore the
contents of its instances.
 SerializableSerializability of a class is enabled by the class implementing the
java.io.Serializable interface.

UNIT-IV

57
Exception Handling
 An exception is an object that describes an exceptional condition (error) that has occurred
when executing a program.
 Exception handling involves the following:
1) when an error occurs, an object (exception) representing this error is created and thrown in the
method that caused it
2) that method may choose to handle the exception itself or pass it on
3) either way, at some point, the exception is caught and processed.

Exception Constructs
Five constructs are used in exception handling:
1) try – a block surrounding program statements to monitor for exceptions
2) catch – together with try, catches specific kinds of exceptions and handles them in some way
3) finally – specifies any code that absolutely must be executed whether or not an exception
occurs
4) throw – used to throw a specific exception from the program
5) throws – specifies which exceptions a given method can throw.

Exception-Handling Block
General form:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }

finally { … }
where:
1) try { … } is the block of code to monitor for exceptions
2) catch(Exception ex) { … } is exception handler for the
exception Exception
3) finally { … } is the block of code to execute before the try
block ends

Benefits of exception handling


 Separating Error-Handling code from “regular” business logic code
 Propagating errors up the call stack
 Grouping and differentiating error types.
Termination vs. resumption
 There are two basic models in exception-handling theory.
 In termination the error is so critical there’s no way to get back to where the exception
occurred. Whoever threw the exception decided that there was no way to salvage the
situation, and they don’t want to come back.
 The alternative is called resumption. It means that the exception handler is expected to do
something to rectify the situation, and then the faulting method is retried, presuming

58
success the second time. If you want resumption, it means you still hope to continue
execution after the exception is handled.
Exception Hierarchy
 All exceptions are sub-classes of the build-in class Throwable.
 Throwable contains two immediate sub-classes:
1) Exception – exceptional conditions that programs should catch
The class includes:
a) RuntimeException – defined automatically for user
programs to include: division by zero, invalid array indexing, etc.
b) use-defined exception classes
2) Error – exceptions used by Java to indicate errors with the runtime environment; user
programs are not supposed to catch them

Using Java Exception Handling


method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}

59
Termination vs. resumption
 There are two basic models in exception-handling theory.
 In termination the error is so critical there’s no way to get back to where the exception
occurred. Whoever threw the exception decided that there was no way to salvage the
situation, and they don’t want to come back.
 The alternative is called resumption. It means that the exception handler is expected to do
something to rectify the situation, and then the faulting method is retried, presuming
success the second time. If you want resumption, it means you still hope to continue
execution after the exception is handled.
 In resumption a method call that want resumption-like behavior (i.e don’t throw an
exception all a method that fixes the problem.)
 Creating Exceptions
Two ways to obtain a Throwable instance:
1) creating one with the new operator
2) using a parameter of the catch clause
try { … } catch(Throwable e) { … e … }
Java Built-In Exceptions
 The default java.lang package provides several exception classes, all sub-classing the
RuntimeException class.
 Two sets of build-in exception classes:
1) unchecked exceptions – the compiler does not check if a method handles or throws there
exceptions.
2) checked exceptions – must be included in the method’s throws clause if the method generates
but does not handle them.
 Unchecked Built-In Exceptions
 Methods that generate but do not handle those exceptions need not declare them in the
throws clause:
1) ArithmeticException
2) ArrayIndexOutOfBoundsException
3) ArrayStoreException
4) ClassCastException
5) IllegalStateException
6) IllegalMonitorStateException
7) IllegalArgumentException
8. StringIndexOutOfBounds
9. UnsupportedOperationException
10. SecurityException
11. NumberFormatException
12. NullPointerException
13. NegativeArraySizeException
14. IndexOutOfBoundsException
15. IllegalThreadStateException

Checked Built-In Exceptions

60
Methods that generate but do not handle those exceptions must declare them in the throws
clause:
1. NoSuchMethodException NoSuchFieldException
2. InterruptedException
3. InstantiationException
4. IllegalAccessException
5. CloneNotSupportedException
6. ClassNotFoundException

Multi-Tasking
 Two kinds of multi-tasking:
1) process-based multi-tasking
2) thread-based multi-tasking
 Process-based multi-tasking is about allowing several programs to execute concurrently,
e.g. Java compiler and a text editor.
 Processes are heavyweight tasks.

Thread Lifecycle:
 Thread exist in several states:
1) ready to run
2) running
3) a running thread can be suspended
4) a suspended thread can be resumed
5) a thread can be blocked when waiting for a resource
6) a thread can be terminated
 New state – After the creations of Thread instance the thread is in this state but before the
start() method invocation. At this point, the thread is considered not alive.
 Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread
first enters runnable state after the invoking of start() method but a thread can return to
this state after either running, waiting, sleeping or coming back from blocked state also.
On this state a thread is waiting for a turn on the processor.
 Running state – A thread is in running state that means the thread is currently executing.
There are several ways to enter in Runnable state but there is only one way to enter in
Running state: the scheduler select a thread from runnable pool.
 Dead state – A thread can be considered dead when its run() method completes. If any
thread comes on this state that means it cannot ever run again.
 Blocked - A thread can enter in this state because of waiting the resources that are hold
by another thread.
 Creating Threads
 To create a new thread a program will:
1) extend the Thread class, or
2) implement the Runnable interface
 Thread class encapsulates a thread of execution.
 The whole Java multithreading environment is based on the Thread class.
 Thread Methods
 Start: a thread by calling start its run method

61
 Sleep: suspend a thread for a period of time
 Run: entry-point for a thread
 Join: wait for a thread to terminate
 isAlive: determine if a thread is still running
 getPriority: obtain a thread’s priority
 getName: obtain a thread’s name
 New Thread: Runnable

Threads: Synchronization
 Multi-threading introduces asynchronous behavior to a program.
 Java implementation of monitors:
1) classes can define so-called synchronized methods
2) each object has its own implicit monitor that is automatically entered when one of the object’s
synchronized methods is called
3) once a thread is inside a synchronized method, no other thread can call any other synchronized
method on the same object
Daemon Threads
 Any Java thread can be a daemon thread.
 Daemon threads are service providers for other threads running in the same process as the
daemon thread.
 The run() method for a daemon thread is typically an infinite loop that waits for a service
request.
SNo Methods with Description

1 boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and
false when all the elements have been enumerated.

2 Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.

Autoboxing :
Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to an
Integer, a double to a Double, and so on. If the conversion goes the other way, this is called
unboxing.

Annotation:
Annotations, a form of metadata, provide data about a program that is not part of the program
itself. Annotations have no direct effect on the operation of the code they annotate.

Generics:
It would be nice if we could write a single sort method that could sort the elements in an Integer
array, a String array or an array of any type that supports ordering.

62
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods or, with a single class declaration, a set of related types,
respectively.

Generic Methods:
You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods:
 All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next example).
 Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.
 The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
 A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).

Exception Summary
 FileNotFoundException: Signals that an attempt to open the file denoted by a specified
pathname has failed.
 InterruptedIOException: Signals that an I/O operation has been interrupted
 InvalidClassException: Thrown when the Serialization runtime detects one of the
following problems with a Class.
 InvalidObjectException: Indicates that one or more deserialized objects failed
validation tests.
 IOException: Signals that an I/O exception of some sort has occurred.

Interface Summary
 Collection<E>: The root interface in the collection hierarchy.
 Comparator<T>: A comparison function, which imposes a total ordering on some
collection of objects.
 Enumeration<E>: An object that implements the Enumeration interface generates a series
of elements, one at a time.
 EventListener: A tagging interface that all event listener interfaces must extend.
 Iterator<E>: An iterator over a collection
 List<E>An ordered collection (also known as a sequence).
 ListIterator<E>: An iterator for lists that allows the programmer to traverse the list in
either direction, modify the list during iteration, and obtain the iterator's current position
in the list.

Class Summary
 AbstractCollection<E>: This class provides a skeletal implementation of the Collection
interface, to minimize the effort required to implement this interface.

63
 AbstractList<E>: This class provides a skeletal implementation of the List interface to
minimize the effort required to implement this interface backed by a "random access"
data store (such as an array).
 AbstractMap<K,V>: This class provides a skeletal implementation of the Map
interface, to minimize the effort required to implement this interface.
 AbstractQueue<E>: This class provides skeletal implementations of some Queue
operations.
 AbstractSequentialList<E>: This class provides a skeletal implementation of the List
interface to minimize the effort required to implement this interface backed by a
"sequential access" data store (such as a linked list).
AbstractSet<E>: This class provides a skeletal implementation of the Set interface to minimize
the effort required to implement this interface.

Exception Summary
 EmptyStackException: Thrown by methods in the Stack class to indicate that the
stack is empty.
 InputMismatchException: Thrown by a Scanner to indicate that the token retrieved
does not match the pattern for the expected type, or that the token is out of range for the
expected type.
 InvalidPropertiesFormatException: Thrown to indicate that an operation could not
complete because the input did not conform to the appropriate XML document type for a
collection of properties, as per the Properties specification.
 NoSuchElementException: Thrown by the nextElement method of an Enumeration to
indicate that there are no more elements in the enumeration.
 TooManyListenersException: The TooManyListenersException Exception is used as
part of the Java Event model to annotate and implement a unicast special case of a
multicast Event Source.
 UnknownFormatConversionException: Unchecked exception thrown when an
unknown conversion is given.

64
UNIT-V

File streams

o Byte stream

o Character stream

Byte Streams:

It supports 8-bit input and output operations. There are two classes of byte stream

o Input Stream
o Output Stream

InputStream:

The InputStream class is used for reading the data such as a byte and array of bytes from an
input source. An input source can be a file, a string, or memory that may contain the data. It is
an abstract class that defines the programming interface for all input streams that are inherited
from it. An input stream is automatically opened when you create it. You can explicitly close a
stream with the close( ) method, or let it be closed implicitly when the object is found as a
garbage.

The subclasses inherited from the InputStream class


ByteArrayInputStream

FileInputStream

ObjectInputStream

FilterInputStream

PipedInputStream

StringBufferInputStream

FilterInputStream

BufferedInputStream

DataInputStream

LineNumberInputStream

PushbackInputStream

65
OutputStream:

The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when you create it. You can explicitly close an output stream with the
close( ) method, or let it be closed implicitly when the object is garbage collected.

The classes inherited from the OutputStream are


ByteArrayOutputStream
FileOutputStream
ObjectOutputStream
FilterInputStream
PipedOutputStream
StringBufferInputStream
FilterOutputStream
BufferedOutputStream
DataOutputStream
PrintStream

OutputStream is also inherited from the Object class. Each class of the OutputStream provided
by the java.io package is intended for a different purpose.

Character Streams:

It supports 16-bit Unicode character input and output. There are two classes of character stream
as follows:
o Reader
o Writer
These classes allow internationalization of Java I/O and also allow text to be stored using
international character encoding.

Reader:
BufferedReader
LineNumberReader
CharAraayReader
PipedReader
StringReader
FilterReader
PushbackReader
InputStreamReader
FileReader

66
Writer:

BufferedWriter

CharAraayWriter

FileWriter

PipedWriter

PrintWriter

String Writer

OutputStreamWriter

FileWriter

Classes:
The following lists of classes are provided by the java.io package shown in the table:

Standard Streams:

Standard Streams are a feature provided by many operating systems. By default, they read input
from the keyboard and write output to the display. They also support I/O operations on files.

Standard Input: - Accessed through System.in which is used to read input from the
keyboard.

Standard Output: - Accessed through System.out which is used to write output to be
display.

Standard Error: - Accessed through System.err which is used to write error output to
be display.
Java also supports three Standard Streams:

These objects are defined automatically and do not need to be opened explicitly.

Standard Output and Standard Error, both are to write output; having error output separately so
that the user may read error messages efficiently.

System.in is a byte stream that has no character stream features. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an argument.

InputStreamReader inp= new InputStreamReader (System.in);

Working with Reader classes:

67
Java provides the standard I/O facilities for reading text from either the file or the keyboard on
the command line. The Reader class is used for this purpose that is available in the java.io
package. It acts as an abstract class for reading character streams. The only methods that a
subclass must implement are read(char[], int, int) and close(). The Reader class is further
categorized into the subclasses.

The following diagram shows a class-hierarchy of the java.io.Reader class.

However, most subclasses override some of the methods in order to provide higher efficiency,
additional functionality, or both.

InputStreamReader:

An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes and
decodes them into Unicode characters according to a particular platform. Thus, this class reads
characters from a byte input stream. When you create an InputStreamReader, you specify an
InputStream from which, the InputStreamReader reads the bytes.
he syntax of InputStreamReader is written as:

InputStreamReader<variable_name>= new InputStreamReader (System.in)

BufferedReader:

The BufferedReader class is the subclass of the Reader class. It reads character-input stream data
from a memory area known as a buffer maintains state. The buffer size may be specified, or the
default size may be used that is large enough for text reading purposes.

BufferedReader converts an unbuffered stream into a buffered stream using the wrapping
expression, where the unbuffered stream object is passed to the constructor for a buffered stream
class.

For example the constructors of the BufferedReader class shown as:

BufferedReader (Reader in): Creates a buffering character-input stream that uses a default-sized
input buffer.

BufferedReader (Reader in, int sz): Creates a buffering character-input stream that uses an input
buffer of the specified size.

BufferedReader class provides some standard methods to perform specific reading operations
shown in the table. All methods throw an IOException, if an I/O error occurs.

Method Return Type Description

68
read( ) int Reads a single character

read(char[] cbuf, int off,


int Read characters into a portion of an array.
int len)

Read a line of text. A line is considered


readLine( ) String
to be terminated by ('\n').

close( ) void Closes the opened stream.

This program illustrates use of standard input stream to read the user input.

import java.io.*;
public class ReadStandardIO
{
public static void main(String[] args) throws IOException
{
InputStreamReader inp = new InputStreamReader(System.in) BufferedReader br = new
BufferedReader(inp);
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);

}
}
Output of the Program:

C:\>javac ReadStandardIO.java C:\>java ReadStandardIO Enter text:


this is an Input Stream
You entered String: this is an Input Stream
C:\>

Files-streams
The File class deals with the machine dependent files in a machine-independent manner i.e. it is
easier to write platform-independent code that examines and manipulates files using the File
class. This class is available in the java.lang package.

The java.io.File is the central class that works with files and directories. The instance of this class
represents the name of a file or directory on the host file system.

69
When a File object is created, the system doesn't check to the existence of a corresponding
file/directory. If the files exist, a program can examine its attributes and perform various
operations on the file, such as renaming it, deleting it, reading from or writing to it.

Thus the statement can be written as:

File f = new File (“<filename>”);


The methods that are used with the file object to get the attribute of a corresponding file shown
in the table.

Method Description

f.exists() Returns true if file exists.

sFile() Returns true if this is a normal file.

f.isDirectory() true if "f" is a directory.

f.getName() Returns name of the file or directory.

f.isHidden() Returns true if file is hidden.

f.lastModified() Returns time of last modification.

f.length() Returns number of bytes in file.

f.getPath() Path name.

f.delete() Deletes the file.

Renames f to File f2. Returns true if


f.renameTo(f2)
successful.

f.createNewFile() eates a file and may throw IOException.

Whenever the data is needed to be stored, a file is used to store the data. File is a collection of
stored information that is arranged in string, rows, columns and lines etc.

Further, we will see how to create a file. This example takes the file name and text data for
storing to the file.

70
For creating a new file File.createNewFile ( ) method is used. This method returns a boolean
value true if the file is created otherwise return false. If the mentioned file for the specified
directory is already exist then the createNewFile () method returns the false otherwise the
method creates the mentioned file and return true.

Let‘s see an example that checks the existence of a specified file.

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

First, this program checks, the specified file "myfile.txt" is exist or not. If it does not exist then
a new file is created with same name to the current location.
Output of the Program
C:\>java CreateFile1
New file "myfile.txt" has been created to the current directory

In Java, it is possible to set dynamic path, which is helpful for mapping local file name with the
actual path of the file using the constructing filename path technique.

File I/O Streams:

Let‘s now see some I/O streams that are used to perform reading and writing operation in a file.

Java supports the following I/O file streams

Java supports the following I/O file streams.


FileInputstream
FileOutputStream
FileInputstream:

This class is a subclass of Inputstream class that reads bytes from a specified file name. The read
() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-
file has been reached. We typically use this class in conjunction with a BufferedInputStream and
DataInputstream class to read binary data. To read text data, this class is used with an
InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the
specified file is not exist. You can use the constructor of this stream as:
71
FileInputstream (File filename);

FileOutputStream:-

This class is a subclass of OutputStream that writes data to a specified file name. The write ()
method of this class writes a byte or array of bytes to the file. We typically use this class in
conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To
write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter
class. You can use the constructor of this stream as:

FileOutputstream (File filename);

The following program demonstrates how contains are read from a file.

import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws IOException
{
File f;
f=new File("myfile.txt"); if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f); byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1); finp.close();
}
}

Output of the Program:


This program reads the bytes from file and displays it to the user.

Demo of the FileOutputStream class


import java.io.*;
public class WriteFile
{
public static void main(String[] args) throws IOException
{
File f=new File ("textfile1.txt");
FileOutputStream fop=new FileOutputStream (f);

72
if (f.exists ())
{
String str="This data is written through the program"; fop.write (str.getBytes ());
fop.flush (); fop.close ();
System.out.println ("The data has been written");
}
else
System.out.println ("This file is not exist");
}

JDBC ARCHITECTURE

Introduction to JDBC

JDBC stands for Java Database Connectivity. It is set of Java API‘s(application programming
interface) used for executing SQL statements. This API consists of a set of classes and interfaces
to enable programmers to write pure Java Database applications.

JDBC is a software layer that allows developers to write real client –server projects in Java.
JDBC does not concern itself with specific DBMS functions. JDBC API defines how an
application opens a connection, communicates with a database, executes SQL statements, and
retrieves query result. Following fig. will illustrate the role of JDBC. JDBC is based on the
X/OPEN call level interface (CLI) for SQL.

JDBC was designed to be very compact, simple interface focusing on the execution of raw SQL
statements and retrieving the results. The goal of creating JDBC is to create an interface that
keeps simple tasks, while ensuring the more difficult and uncommon tasks are at least made
possible.

It is possible to access various relational databases like Sybase, Oracle, Informix, Ingers, using
JDBC API. Using JDBC, we can write individual programs to connect to individual database or
one program that take care of connecting to the respective database.

Java and JDBC


The combination of java with JDBC is very useful because it lets the programmer run his/her
program on different platforms, Java programs are secure, robust, automatically downloaded
from the network and java is a good language to create database applications. JDBC API enables
Java applications to interact with different types of database. It is possible to publish vital
information from a remote database on a web page using a java applet. With increasing
inclination of programmers towards Java, knowledge about JDBC is essential.

The JDBC API is in the package java.sql .It includes the following interfaces and classes
Interfaces:

73
CallableStatement
Connection
DatabaseMetaData
Driver
PreparedStatement
ResultSet
ResultSetMetaData
Statement
Classes:
Date
DriverManager
DriverPropertyInfo
Time
Timestamp
Types
Exceptions:
DataTruncation
SQLException
SQLWarning

Types of Drivers:
DBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.

74
Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

75
3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.

76
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depends on the Database.

Types of Driver Managers


JDBC contains three components: Application, Driver Manager, Driver. The user application
invokes JDBC methods to send SQL statements to the database and retrieves results. JDBC
driver manager is used to connect Java applications to the correct JDBC driver . JDBC driver test
suite is used to ensure that the installed JDBC driver is JDBC Compliant. There are four different
types of JDBC drivers as follows

1.The JDBC-ODBC Bridge plus ODBC driver :


The JDBC-ODBC Bridge plus ODBC driver is a JavaSoft Bridge protocol that provides JDBC
access via ODBC drivers. But as we have mentioned earlier, combining ODBC brings in a lot of
drawbacks and limitations, since the ODBC driver has to be installed on each client machine, it
is not advisable to choose this type of driver for large networks.

2. Native-API partly-Java driver :

Native-API partly-Java driver converts JDBC calls into calls on the client API for Oracle,
Sybase, Informix or other DBMS. But some binary code has to be loaded on all client like the
bridge driver and hence is not suitable for large networks.

77
3.JDBC-Net pure Java driver:

JDBC-Net pure Java driver translates JDBC calls into DBMS independent net protocol. A server
again translates this protocol to a DBMS protocol. The net server middleware connects its pure
Java clients to many different databases. The type of protocol in this middleware depends on the
vendor.
4.Native-protocol pure Java driver :

Native-protocol pure Java driver convert JDBC calls to network protocols used by the DBMSs
directly. Requests from client machines are made directly to the DBMS server.
Drivers 3 and 4 are the most preferred ways to access databases from JDBC drivers.

A connection can be open with the help of following steps


1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection

Step 1. Importing Packages

The following JDBC packages will be imported for creating connection. java.sql.
java.math.
java.io.
oracle.jdbc.driver.
Step 2. Registering the JDBC Drivers
Following four parameters are required to register JDBC
o JDBC Driver name o User Name o Password

JDBC Drivers can be register using following methods. o Class


drvClass=Class.forName(m_driverName);
DriverManager.registerDriver((Driver)drvClass.newInstance());

Step 3 : Opening a Connection to a Database


Connection to the underlying database can be opened using
Connection m_con=DriverManager.getConnection(m_url,m_userName,m_password);

Step 4 : Creating a Statement Object


SQL Statements
Once a connection is established, It is used to pass SQL statements to its underlying database.
JDBC provides three classes for sending SQL Statements to the database, where
PreparedStatement extends from Statement, and CallableStatement extends
fromPreparedStatement:

78
o Statement
o PreparedStatement
o CallableStatement

The statement interface provides three different methods for executing SQL statements :

o executeQuery : For statements that produce a single result set.


o executeUpdate : For executing INSERT, UPDATE, or DELETE statements and
also SQL DDL (Data Definition Language) statements.
o execute : For executing statements that return more than one result set,
more than one update count, or a combination of the two.

A Statement object is used with following steps:


Statement
Statement stmt=m_con.createStatement();
Statement stmt=m_con.createStatement(int resultSetType, int resultSetConcurrency);
PreparedStatement

PreparedStatement pstmt=m_con.prepareStatement(String sql);


PreparedStatement pstmt=m_con.prepareStatement(String sql, int resultSetType, int
resultSetConcurrency),
Note:

The SQL parameter could contain one or more ‗?‘ in it. Before a PreparedStatement object is
executed, the value of each ‗?‘ parameter must be set by calling a setXXX method, where XXX
stands for appropriate type for the parameter. For ex. If the parameter has a java type of String,
the method to use is setString.

CallableStatement

CallableStatemet csmt=m_con.prepareCall(String sql);


CallableStatemet csmt=m_con.prepareCall(String sql, int resultSetType, int
resultSetConcurrency),);

Step 5: Executing a Query and Returning a Result Set Object


Execute the Statement

Statement :
ResultSet res=stmt.executeQuery(String sql); int rowCount=stmt.executeUpdate(String sql);
boolean result=stmt.execute(String sql);

PrepaedStatement :
ResultSet res=pstmt.executeQuery(); int rowCount=pstmt.executeUpdate(); boolean
result=pstmt.execute();

CallableStatement :

79
ResultSet res=cstmt.executeQuery(); int rowCount=cstmt.executeUpdate();
boolean result=cstmt.execute();

step 6:Processing the Result set


A result set contains all of the rows which satisfied the conditions in an SQL statement and it
provides access to the data in those rows through getXXX mehods that allow access to the
various columns of the current row.

The ResultSet.next() method is used to move to the next row of the ResultSet, making the next
row become the current row. ResultSet.next() returns true if the new current row is valid, false if
there are no more rows. After all the works have been done, the ResultSet should be closed with
ResultSet.close() method.

Because of limitations imposed by some DBMSs, it is recommended that for maximum


portability, all of the results generated by the execution of a CallableStatement object should be
retrieved before OUT parameters are retrieved using CallableStatement.getXXX methods.

Step 7: Closing the Result Set and Statement Objects

Close the statement

After all the works have been done, the result set and statement should be closed with the
following code :
Resultset : rset.close();
Statement : stmt.close();
PrepaedStatement : pstmt.close();
CallableStatement : cstmt.close();

Step 8: Closing the Connection


After all the works have been done, the Connection should be closed with the following code:
(Connection name)m_con.close();

JDBC demo Programs

Example for viewing rows from a table

import java.sql.*;
public class SelectEmp
{
public static void main(String args[])

80
{
String url=”jdbc:odbc:gcet”;
Connection con;
String s= “select ename from emp1”;
Statement stmt;
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(java.lang.ClassNotFoundException e)
{
System.err.println(“ClassNotFoundException”);
System.err.println(e.getMessage());
}
try
{
con=DriverManager.getConnection(url,”Scott”,”Tiger”);
stmt=con.createStatement(); resultSet rs=stmt.executeQuery(s); while(rs.next())
{
String s1=rs.getString(“ename”);
System.out.println(“Employee name:” +s1);
}
stmt.close();
con.close();
}
catch(SQLException ex)
{
System.err.println(―SQLException:‖+ex.getMessage());
}
}
}

16. Additional topics

Java – Regular Expressions

81
Java provides the java.util.regex package for pattern matching with regular expressions.
Java regular expressions are very similar to the Perl programming language and very easy to
learn.

A regular expression is a special sequence of characters that helps you match or find
other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to
search, edit, or manipulate text and data.

The java.util.regex package primarily consists of the following three classes −


 Pattern Class − A Pattern object is a compiled representation of a regular expression.
The Pattern class provides no public constructors. To create a pattern, you must first
invoke one of its public static compile() methods, which will then return a Pattern
object. These methods accept a regular expression as the first argument.

 Matcher Class − A Matcher object is the engine that interprets the pattern and performs
match operations against an input string. Like the Pattern class, Matcher defines no
public constructors. You obtain a Matcher object by invoking the matcher() method on
a Pattern object.

 PatternSyntaxException − A PatternSyntaxException object is an unchecked exception


that indicates a syntax error in a regular expression pattern.

17. University Previous Question papers

82
83
84
85
OBJECT ORIENTED PROGRAMMING
(ELECTRONICS AND COMMUNICATION ENGINEERING)
Time: 3 hours Max. Marks: 75
Answer any five questions
All questions carry equal marks
---

1. With an example explain the concept of agents, responsibilities methods and


Messages. [15]

2. Write a java program to explain the concept of Classes and Objects. [15]

3. Write a java code to explain Polymorphism and Method overriding. [15]

4. a) Discuss about the creation of CLASSPATH.


b) Explain differences between classes and interfaces. [8+7]

5. With a java code to explain the handling of exceptions using throws. [15]

6. Write a java code to explain the concept of thread priority in multithreading. [15]

7. Explain various layouts manager types with the help of an example. [15]

8. With a neat diagram explain the life cycle of an applet program. [15]

86
87
88
18.QUESTION BANK

UNIT I
Short Answer Questions Short Answer Questions

1. Define OOP?

2. Distinguish between procedural language and OOPs?

3. Define Encapsulation?

4. Define Inheritance?

5. Benefits of inheritance.

6. Define Polymorphism?

7. List advantages of OOP?

8. List disadvantages of OOP?

9. Write history of java?

10. Describe a data type?

11. Describe a constant?

12. Describe scope and life time of variables?

Long Answer Questions

1. Describe the characteristics of object oriented programming concepts?

2. Describe the features (buzzwords) of Java Programming language?

3. Write the Differences between Java and C++.

4. Is Java pure object oriented programming language

5. History of java.

6. What are variables? Discuss about the scope and life time of variables in detail.

7. What is object oriented programming? How is it different from procedure-oriented


programming?
8. What are objects? How are they created from a class?

89
UNIT II
Short Answer Questions

1. Define type casting?

2. Define constructor?

3. How do we invoke a constructor?

4. Define recursion?

5. List of Types of Operators?

6. Define Type conversion?

7. Define enumerated types?

8. Define Input and Output functions?

9. Define garbage collection?

10. Write about string class with an example.

11. Write about the console input and output with an example.

12. Write about simple stand alone programs.

13. Write about the method overloading with an example.

14. Write about the constructor overloading with an example.

15. What is a class? How do classes help us to organize our programs?

90
Long Answer Questions

1 Write about string class with an example.

1 Write about the console input and output with an example.

2 Write about simple stand alone programs.

3 Write about conditional statements.

4 Write about loops with an example.

5 Write about the break and continue statements with an example.

6 Write about the operator hierarchy with an example.

7 Write about all the operators in java with an example.

8 Define static field? Write with an example.

9 Define static method? Write with an example.

10 Define type conversion, type casting with an example?

11 What is the difference between a public member and a private member of a class?

12 How the constructor in Java is implemented? What are its special properties? How many
types of constructors are there in Java? Explain.
13 What are constructors and destructor functions? Explain different types of constructors?

14 Write a program to display Fibonacci series.


15 Compare and contrast between concrete class and abstract class.
16 Write a program to check whether given string is palindrome or not.
17 Write a program to find whether the given triangle is right angled or not
18 What is a class? How do classes help us to organize our programs?
19 Differentiate between static and instance methods.
20 Write a program to check the given number is prime or not.

91
UNIT III
Short Answer Questions

1. Define Inheritance?
2. List types of inheritances in java?
3. Write Member access rules
4. Write Uses of ‘Super’ keyword
5. Write using ‘final’ keyword with inheritance
6. Write about Object class
7. Define abstract classes?
8. Define polymorphism?
9. Define a package?
10. Write creating, importing packages?
11. Define abstract methods?
12. Define CLASSPATH?
13. List advantages of inheritance?
14. Write implementing an interface
15. Difference between interfaces vs. Abstract classes
16. Define inner classes?
17. Define static inner classes?

Long Answer Questions

1. Define Inheritance? Discuss its uses and Hierarchical abstractions?


2. List types of inheritances in java? Write each of them in detail.
3. Define package? Discuss its advantages and necessity of packages?
4. Write different Types of Packages?
5. Define Abstract classes? Write with an example?
6. Define interface? Write with an example?
7. Define inner classes? Write with an example?
8. Write in detail about creating , importing packages
9. Write how packages are accessed
10. Write extending interfaces with an example
11. Define interface? Write Differences between classes and interfaces?
12. Write final classes , methods with an example
13. Write inheritance with an example
14. Write working procedure of CLASSPATH
15. Define multiple inheritances. Does Java Support multiple inheritance. Justify your
answer.
16. Write java program to implement the multilevel Inheritance.
17. How do you construct a class from another class? Explain with an example.
18. Can a sub class access all the members of super class? Justify your answer

19. Explain about the abstract class with example program?


20. Define Abstract class? Explain with a suitable example.

92
21. Explain about Object class in detail.
UNIT IV
Short Answer Questions

1. Define Exception?
2. Distinguish between exception and error?
3. Write benefits of exception handling
4. Write the classification of exceptions
5. Define checked exceptions?
6. Define unchecked exceptions?
7. Define built in exceptions?
8. Write the usage of try and catch
9. Write the usage of throw, throws and finally
10. Distinguish between throw and throws?
11. Distinguish between process and thread?
12. Write thread states.
13. Write creation of thread?
14. Define producer consumer problem?
15. Define inter-thread communication?
16. Write how threads are synchronized?
17. Write thread priorities.
18. How many ways can thread be created?
19. Write the alive() and join() method
20. Write thread class implements Runnable interface.
Long Answer Questions

1. Write about exception handling mechanisms


2. Write try, catch , and finally with an example
3. Define throws keyword? Write with an example?
4. Write a program to implement built in exceptions?
5. Write creation of thread
6. Write with an example how java performs thread synchronization?
7. Write producer consumer problem with an example?
8. Write about multithreading?
9. Write the life cycle of a thread?
10. Discuss about multiple catch clauses and nested try statements.
.
11. What is Synchronization? Explain with suitable example.
12. Explain how exception handling mechanism can be used in a program.
13. What is an exception? How can java handle the exceptions? Illustrate with an example.
14. Explain in detail any three checked exceptions.
15. Explain the following exceptions with the help of examples:

93
16. If we try to catch a super class exception type before a sub class type, compiler generates
exception errors. Explain why this error occurs with an example?

17. What is the difference between unchecked and checked exceptions in java?.
18. Explain in detail any two unchecked exceptions.

19. Explain in detail any three checked exceptions.

20. What is meant by multithreaded programming? Discuss about Java thread model, thread
priorities and interthread communication.
21. Discuss about wait (), notify( ) and notifyAll( ) methods in Java.
22. Discuss various methods of object class.
23. Write a program that demonstrates the priority setting in threads.
24. Write an example program for multithreading using thread class.
25. How do we set priorities for threads? Describe the complete life cycle of a thread.

UNIT-V
Short Answer Questions

1. Define Stream?
2. Define byte stream?
3. Define character stream?
4. Define text input/output file?
5. Define JDBC?
6. List types of JDBC drivers.
7. Define random access file?
Long Answer Questions

1. Write text input/output file operations.


2. Write binary input/output file operations.
3. Write random access file operations.
4. Write File management using File class.
5. Write JDBC with an example.
6. Write different types of JDBC drivers with diagrams.
7. Write JDBC example for querying the database and processing the results.
8. Write JDBC example for updating data.

94
19 Assignment Questions

Assignment-1
1. Describe about the Object Oriented Programming concepts.
2. What is the Difference between procedure oriented and object oriented programming
paradigm?
3. Explain briefly about History of JAVA.
4. Explain about different constants available in java.
5. What is variable? Write briefly about different types of variables in Java.
6. What are variables? Discuss about the scope and life time of variables in detail.

Assignment-2
1. Write a Java Program to demonstrate Static keyword.
2. Explain about different parameter passing techniques in java.
3. Explain about type conversion and casting with example programs.
4. What is garbage collection? Explain its usage.
5. Explain about static fields, constructors, methods with example programs.
6. Explain about type conversion and casting with example programs.

Assignment-3
1. Define abstract classes?
2. How to extend one interface by the other interface? Explain with an example.
3. What is the major difference between an interface and class?
4. Explain in detail about accessing a package
5. Define package? Discuss its advantages and necessity of packages?

6. Define inner classes?


7. Define static inner classes?

Assignment-4

95
1. Explain creation of thread using runnable interface and extending thread class with an
example.

2. Explain about thread interrupts with an example.

3. What is an Exception? Explain how an exception can be handled in Java? Also list the benefits
of exception handling.

4. What are Checked and Unchecked Exceptions? And also explain differences.
Develop and explain with an example, how java performs thread synchronization?
5. Difference between multiprocess and multithread?
8.What are the Thread prioritys?
9.Explain life cycle of thread.

Assignment-5
1. Write JDBC with an example.
2. Write different types of JDBC drivers with diagrams.
3. Write JDBC example for querying the database and processing the results.
4. Updating data with JDBC
5. Explain random access file operations
6. Explain file management using file class.

20. Unit wise Quiz Questions

96
UNIT-1

1_____________ is the ability for a message or data to be processed in more than one form.
a. inheritance c. encapsulation
b. abstraction d.polymorphism
2 An________ is a software bundle of variables and related methods

3. Which of the following statement about the java language is true?


a)Both procedural and OOP are supported in java
b)Java supports only procedural approach through programming
c)Java supports only OOP approach d)None of the above

4. Which of the following statements is false about objects?


a)An instance of a class is an object b)Objects can access both static and instance data
c)Object is the superclass of all other classes d)Object do not permit encapsulation
5_______________ is a technical definition of the language that includes the syntax and
semantics.

6________________ can be characterized as data controlling access to code.

7__________________ is a software unit that combines a structured set of data with a set of
operations for inspecting and manipulating that data.
8. is a group of instructions that is given a name and can be called up at any
point in a program simply by quoting that name
a.method b. class c. data d. messages
9. allows to reuse classes by deriving a new class from an existing one

a. inheritance c. encapsulation
b. abstraction d.polymorphism
10. is an object that can be used to call an arbitrary public method, on an instance that is
acquired by evaluatng the leading portion of a method binding expression via a value binding
a.Method binding b. Type binding c. a&b d.none

11._____________ is an interpreter for bytecode.


b.
a. Compiler JVM c. Internet d. ACM
12.The class that inherits is
called ]
a.Superclass b.subclass c.virtual d.instance class
13.The ____________operator is used to create a new object or a new
array.
a.instanceOf b.scope c.(.) d.new

97
15.In java, the equal sign is
a.increment b.decrement c.assignment d.negation

16. To terminate a program java


statement is
a.System.quit(0);
b.System.exit(0);
c.System.end(0);
d.System.abort(0
);

17.Which method can access to private attributes of a class?


a)Only static method of the same class b)Only instances of the same class
c)Only methods those defined in the same class d)Only classes available in the same package

18.Which can be passed as an argument to a


function? [ ]
a)Constant b)Expression c)Other function d)All the above

19.“this” pointer [ ]
a)Implicitly points to an object b)Can be explicitly used in class
c)Can be used to return an object d)All the above

[ ]
20.Static function Should be called when an object is destroyed
a.Is closely connected with individual objects of a class
b.Can be called using the class name and function name
c.Is used when a dummy object must be created
d.none

21. The new operator [ ]


a) Returns a pointer to the variable b) Creates a variable called new
c) Obtains memory for a new variable d) Tells how much memory is available
22.___________ is the region where the code that needs to be executed under circumstances is
written.

23. _______________ is an independent path of execution in a program.

98
24.A program that a java enabled browser can download and run is
a__________ .

Unit-2

1. Which of these is the method which is executed first before execution of any other
thing takes place in a program?
a) main method
b) finalize method
c) static method
d) private method

2. What is the process of defining more than one method in a class differentiated by
parameters?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of these

3. Which of these can be used to diffrentiate two or more methods having same name?
a) Parameters data type
b) Number of parameters
c) Return type of method
d) All of the mentioned

4. Which of these data tupe can be used for a method having a return statement in it?
a) void
b) int
c) float
d) All of the mentioned.

5. Which of these statement is incorrect?


a) Two or more methods with same name can be diffrenciated on the basis of their
parameters data type.
b) Two or more method having same name can be diffrentiated on basis of number of
parameters.
c) Any already defined method in java’s library can be defined again in the program
with diffrent data type of parameters.
d) If a method is returning a value the calling statement must have a varible to store
that value.

99
6. What is the output of this program?
1. class box {
2. int width;
3. int height;
4. int length;
5. int volume;
6. void volume(int height, int length, int width) {
7. volume = width * height * length;
8. }
9. }
10. class Prameterized_method{
11. public static void main(String args[]) {
12. box obj = new box();
13. obj.height = 1;
14. obj.length = 5;
15. obj.width = 5;
16. obj.volume(3, 2, 1);
17. System.out.println(obj.volume);
18. }
19. }
a) 0
b) 1
c) 6
d) 25

7. What is the output of this program?


1. class equality {
2. int x;
3. int y;
4. boolean isequal(){
5. return(x == y);
6. }
7. }
8. class Output {
9. public static void main(String args[]) {
10. equality obj = new equality();
11. obj.x = 5;
12. obj.y = 5;
13. System.out.println(obj.isequal);
14. }
15. }
a) false
b) true
c) 0
d) 1

100
8. What is the output of this program?
1. class box {
2. int width;
3. int height;
4. int length;
5. int volume;
6. void volume() {
7. volume = width * height * length;
8. }
9. void volume(int x) {
10. volume = x;
11. }
12. }
13. class Output {
14. public static void main(String args[]) {
15. box obj = new box();
16. obj.height = 1;
17. obj.length = 5;
18. obj.width = 5;
19. obj.volume(5);
20. System.out.println(obj.volume);
21. }
22. }
a) 0
b) 5
c) 25
d) 26

9. What is the output of this program?


advertisements
1. class Output {
2. static void main(String args[])
3. {
4. int x , y = 1;
5. x = 10;
6. if(x != 10 && x / 0 == 0)
7. System.out.println(y);
8. else
9. System.out.println(++y);
10. }
11. }
a) 1
b) 2
c) Runtime Error
d) Compilation Error

101
10. What is the output of this program?
1. class area {
2. int width;
3. int length;
4. int volume;
5. area() {
6. width = 5;
7. length = 6;
8. }
9. void volume() {
10. volume = width * height * length;
11. }
12. }
13. class cons_method {
14. public static void main(String args[]) {
15. area obj = new area();
16. obj.volume();
17. System.out.println(obj.volume);
18. }
19. }
a) 0
b) 1
c) 25
d) 30

11. Which of these keywords are used to define an abstract class?


a) abst b) abstract
c) Abstract
d) abstract class

12. Which of these is not abstract?


a) Thread
b) AbstractList
c) List
d) None of the Mentioned

13. If a class inheriting an abstract class does not define all of its function then it will
be known as?
a) abstract
b) A simple class
c) Static class
d) None of the mentioned

14. Which of these is not a correct statement?


a) Every class containing abstract method must be declared abstract.
b) Abstract class defines only the structure of the class not its implementation.

102
c) Abstract class can be initiated by new operator.
d) Abstract class can be inherited.

15. Which of these packages contains abstract keyword?


a) java.lang
b) java.util
c) java.io
d) java.system

16. What is the output of this program?


1. class A {
2. public int i;
3. protected int j;
4. }
5. class B extends A {
6. int j;
7. void display() {
8. super.j = 3;
9. System.out.println(i + " " + j);
10. }
11. }
12. class Output {
13. public static void main(String args[])
14. {
15. B obj = new B();
16. obj.i=1;
17. obj.j=2;
18. obj.display();
19. }
20. }
a) 1 2
b) 2 1
c) 1 3
d) 3 1

103
Unit-3

1. Abstract class and abstract method should be declared by using the keyword
. a. abstract b. super 3. Class d. none
2. writing two or more methods in super and sub classes such that the methods have the same
name and same signature is called
a. method overriding. B.operator overloading c. overloading d.none
3. The Polymorphism exhibited at run time is called
a. dynamic Polymorphism b. static polymorphism c. a&b d none
4. The keyword signifies that the properties of the super class name are extended to the sub
class name
a.extends b. super c. subclass d class

5. Super can be used to refer to super class method as


a.super.class() b.super.method() c. a&b d. none

6. Which of these keyword must be used to inherit a class?


a) super b) this c )
extent
d) extends

7. Which of these keywords is used to refer to member of base class from a sub class?
a) upper
b) super
c) this

104
d) None of the mentioned

8. A class member declared protected becomes member of subclass of which type?


a) public member b) private member
c) protected member
d) static member

9. Which of these is correct way of inheriting class A by class B?


a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}

10. Which of the following statements are incorrect?


a) public members of class can be accessed by any code in the program.
b) private members of class can only be accessed by other members of the class.
c) private members of class can be inherited by a sub class, and become protected members in
sub class.
d) protected members of a class can be inherited by a sub class, and become private members of
the sub class.

11. What is the output of this program?


1. class A {
2. int i;
3. void display() {
4. System.out.println(i);
5. }
6. }
7. class B extends A {
8. int j;
9. void display() {

105
10. System.out.println(j);
11. }
12. }
13. class inheritance_demo {
14. public static void main(String args[])
15. {
16. B obj = new B();
17. obj.i=1;
18. obj.j=2;
19. obj.display();
20. }
21. }
a) 0
b) 1
c) 2
d) Compilation Error

12. What is the output of this program?


1. class A {
2. int i;
3. }
4. class B extends A {
5. int j;
6. void display() {
7. super.i = j + 1;
8. System.out.println(j + " " + i);
9. }
10. }
11. class inheritance {
12. public static void main(String args[])
13. {

106
14. B obj = new B();
15. obj.i=1;
16. obj.j=2;
17. obj.display();
18. }
19. }
a) 2 2
b) 3 3
c) 2 3
d) 3 2

13. What is the output of this program?


class A {
public int i;
private int j;
}
class B extends A {
void display() {
super.j = super.i + 1;
System.out.println(super.i + " " + super.j);
}
}
class inheritance {
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}

107
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error

Unit-4

1. You can use the _ _ _ _ _ _ _ _ method to force one thread to wait for another thread to
finish. [ ]
a. sleep(long milliseconds) b. yield() c. stop() d. join()
2. A Java exception is an instance of _ _ _ _ _ _ _ _ _ _ . [ ]
a. Runtime Exception b. Exception c. Error d. Throw able
3. Program statements that are to be monitored for exceptions are contained within _____ block.[
]
a. try b. catch c. throw d. throws
4.___________________modifier can be accessed only to classes in the same package.

5.___________________ modifiers applies to variables only and it is not stored as part of its
objects persistent state.

6._________________ package has the ability to analyze itself at runtime.

7.A ________________ is a collection of classes and interfaces that provides a high-level


layer of access protection and name space management.

8.Interfaces with no methods are called as _____________________

9.An instance of _______________ are unchecked exceptions


10.An application responds to an exception by throwing an another exception is called as
___________.
11. Benifits of exception handling___________

108
a.Separating Error-Handling code from “regular” business logic code
b.Propagating errors up the call stack
c.Grouping and differentiating error types
d.none
12. All exceptions are sub-classes of the build-in class
a. Throwable b.serializable c. exception d.none
13. defined automatically for user programs to include: division by zero, invalid array
indexing, etc.
14. is the most general and represents any type of error that can occur when performing
I/O

15.Which of the following statement is not defined in the Object class?


a) sleep(long milliseconds) b) wait() c) notify() d) notifyAll()

16. The keyword to synchronize methods in Java is ________________ [ ]


a. synchronize b. synchronizing c. synchronized d. Synchronized
17. _____________ condition occurs when two threads have a circular dependency on a pair of
synchronized objects.
18 The wait(), notify(), and notify All() methods are implemented as ____________ methods in
Object class.
19.Sleep(10000) causes the main thread to sleep for seconds _________

20. Which method on a condition should you invoke to wake all waiting thread?
a) condition.wake(); b) condition.signal();
c) condition.wakeAll(); d) condition.signalAll();

21.You can use the method to force


one thread to wait for another thread
a) sleep(long milliseconds) b) yield() c) stop() d) join()

22.Which cannot directly cause a thread to stop executing?


a) Calling a yield method b) Calling the start method on another thread object
c) Calling the notify method on object d) Calling wait method on an object

109
23. A thread is a

A) light B) strong C) small D) large

24.This thread is called the thread because it is the thread that executes when you start the main
program.
A) float B) main C) void D) int

25. When does Exceptions in Java arises in code sequence?


a) Run Time b) Compilation Time c) Can Occur Any Time d) None of the mentioned

110
UNIT-5

1. Which of these is used to perform all input & output operations in Java?
a) streams
b) Variables
c) classes
d) Methods
2. Which of these is a type of stream in Java?
a) Integer stream
b) Short stream
c) Byte stream
d) Long stream
3. Which of these classes are used by Byte streams for input and output operation?
a) InputStream
b) InputOutputStream
c) Reader
d) All of the mentioned
4. Which of these classes are used by character streams for input and output operations?
a) InputStream
b) Writer
c) ReadStream
d) InputOutputStream
5. Which of these class is used to read from byte array?
a) InputStream.
b) BufferedInputStream.

111
c) ArrayInputStream.
d) ByteArrayInputStream.
6. What is the output of this program if input given is “abc’def/’egh”?
class Input_Output {
public static void main(String args[]) throws IOException {
char c;
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
do {
c = (char) obj.read();
System.out.print(c);
} while(c!='\'');
}
}
a) abc’
b) abcdef/’
c) abc’def/’egh
d) abcqfghq
7. What is the output of this program?
class output {
public static void main(String args[])
{
StringBuffer c = new StringBuffer("Hello");
System.out.println(c.length());
}

a) 4
b) 5
c) 6
d) 7
8. What is the output of this program?
class output {

112
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello");
StringBuffer s2 = s1.reverse();
System.out.println(s2);
}
}
a) Hello
b) olleH
c) HelloolleH
d) olleHHello
9. Which exception is thrown by read() method?
a) IOException
b) InterruptedException
c) SystemException
d) SystemInputException
10. Which of these is used to read a string from the input stream?
a) get()
b) getLine()
c) read()
d) readLine()

11. Which of these class is used to read characters and strings in Java from console?
a) BufferedReader
b) StringReader
c) BufferedStreamReader
d) InputStreamReader

12. Which of these classes are used by Byte streams for input and output operation?
a) InputStream
b) InputOutputStream

113
c) Reader
d) All of the mentioned

13. Which of these class is implemented by FilterInputStream class?


a) InputStream
b) InputOutputStream
c) BufferedInputStream
d) SequenceInputStream

14. Which of these class is used to read from a file?


a) InputStream
b) BufferedInputStream
c) FileInputStream
d) BufferedFileInputStream

114
21.Tutorial problems

Tutorial-1

1. Write a Java Program to print prime numbers up to a given number.


2. Write a Java Program To print Fibonacci sequence up to a given number.
3. Write a Java Program to Overload the method deposit ( ) in bank account class containing
Account number account name and balance .

Tutorial-2

1. Write a Java Program to demonstrate Widening conversion.


2.Write a Java Program to demonstrate Method chaining.
3.Write a Java Program to demonstrate String tokenizer class methods.

Tutorial-3

1. Write a Java Program to demonstrate Dynamic method dispatch (class program).


2. Write a Java Program to check whether a String is palindrome or not.
3. Write a Java Program to Count number of words in a given text.
4. Write a Java Program To print Fibonacci sequence up to a given number.
5. Write a Java Program to demonstrate Final keyword.
6. Design and develop how to create a package and how to import the packages in java.

Tutorial-4

1. Write a Java Program to demonstrate Thread priority.


2. Write a Java Program to simulate a simple calculator
3. Write a Java Program to demonstrate Thread priority.

Tutorial-5

1. Design and develop a java program to how to handle ArithmeticException and


ArrayIndexOutOfBoundsException by use try, catch and finally blocks.
2. Design and develop a java program to create three threads the first thread prints ‘good
morning’ for every one second ,the second thread prints ‘hello!’ for every 2 seconds and the third
thread prints ‘welcome’ for every three seconds

115
3. Design and develop a java program to show the use of throw keyword for throwing
NullPointerException.

Tutorial-6

1. Design and develop a java program that reads a filename and displays the file on screen.
2. Design and develop a java program that reads a filename from keyboard and display the
number of characters in the file.
3.Write a java program to illustrate Stack class.

Tutorial-7

1. Write a Java Program to demonstrate List.


2. Write a Java Program to demonstrate Checkbox.
3. Write a java program to demonstrate passing parameters to Applets.
4.Develop an applet that receives an integer in one text field, and computes its factorial Value
and returns it in another text field, when the button named “Compute” is clicked.

Tutorial-8

1. What is a Borderlayout manager? Write a java program to try out border


Layout manager.
2. What is Mouse listener interface? Explain any four Mouse listener interface
methods.
3. What is a JRadiobutton and Write any three constructors.
4. Create a JApplet that displays two JRadiobuttons and a JTextField and whenever a
radiobutton is clicked, its text is displayed in TextField.

Tutorial -9
1. Design and develop a java program to demonstrate the creation of thread groups.
2. Design and develop a java program to create multiple threads and make the threads to act on a
single object using Synchronization block .
3. Design and develop a java program to show how to handle checked exceptions.
4. Design and develop a java program to demonstrate on inter-thread communication for
producer-consumer problem.
5. Write a Java program for handling mouse events.

116
22.Known gaps ,if any and inclusion of the same in lecture schedule

JDBC Drivers:

What is JDBC Driver?


JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact with
it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.

JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBC Bridge Driver


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when no
other alternative is available.

117
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.

If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java


In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.

118
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

119
Which Driver should be Used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.

Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.

The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

23. Discussion topics


 Difference between procedure oriented programming and object oriented
programming
 Operator precedence and Associativity
 Method Overloading versus Method Overriding
 Java Buzzwords
 Nested Classes
 This and super keywords
 Forms of Inheritance
 Inner classes
 Packages
 String Class
 Exception handling
 Multithreading
 Auto boxing, Enumerations
 Event Handling
 Layout Managers
 Swing Components
 Applets
 java.util package, java.io package
 JDBC Drivers

24. References, Journals, websites and E-links if any


http://docs.oracle.com/javase/tutorial/java/
http://www.freejavaguide.com/corejava.htm
http://iiti.ac.in/people/~tanimad/JavaTheCompleteReference.pdf
http://www.oracle.com/technetwork/java/newtojava/java8book-2172125.pdf
http://javabeginnerstutorial.com/core-java/
http://beginnersbook.com/java-tutorial-for-beginners-with-examples/

120
http://interviewquestionsanswerspdf.com/2017/01/java-multiple-choice-questions-answers-mcqs/
https://www.javatpoint.com/package
http://www.studytonight.com/java/object-and-classes
https://www.tutorialspoint.com/java/java_basic_datatypes.htm
https://www.javatpoint.com/multithreading-in-java
http://www.studytonight.com/java/event-handling-in-java

25.Quality Measurement Sheets


1. Course End Survey
2. Teaching Evaluation

26. Student List

ECE – III Year – I sem – C Section - A.Y:2018 - 19

Academic Year: 2018-2019 Class: B.Tech III year


Sem:I Sections:C&EEE
Name of the Elective: (16CS3123) JAVA PROGRAMMING

26. Group-Wise students list for discussion topics:

121
122