16CS3123-Java Programming Course File-Autonomous
16CS3123-Java Programming Course File-Autonomous
DEPARTMENT OF
ELECTRONICS COMMUNICATION & ENGINEERING
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
Prepared by :
1) Name : G.Swapna
2) Sign :
3) Design : ASSISTANT PROFESSOR
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
8 Brief notes on the importance of the course and how it fits into the curriculum 13
9 Prerequisites if any 13
14 Lesson Schedule 18
15 Detailed notes 21
16 Additional topics 83
18 Question Bank 90
19 Assignment Questions 96
22 Known gaps ,if any and inclusion of the same in lecture schedule 118
3
B Teaching Evaluation 122
2. Syllabus
16CS3123 – JAVA PROGRAMMING
(Open Elective – I)
4
L T P/D C
Prerequisite(s): C Programming (or) C++ Programming 3 - -/- 3
Course Objectives:
Develop ability to
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.
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
Inner classes – Uses of inner classes, local inner classes, anonymous inner classes, static inner
classes, examples.
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.
TEXT BOOK(S)
6
1. Java fundamentals – A comprehensive Introduction, Herbert Schidlt and Dale Skrien, TMH,
REFERENCE BOOK(S):
2. Java for programmers, PJ. Dietel and H.M Dietel person education
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.
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.
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.
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.
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.
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.
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.
11
Course POS
Code and Title
Java Programming 1 2 3 4 5 6 7 8 9 10 11 12 13 14
8. Brief notes on the importance of the course and how it fits into the curriculum
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
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
14
12. Individual Time Table:
15
passing
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
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
19
15. Detailed notes
Unit-I
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.
Object=data+ methods
The data of an object can be accessed only by methods associated with that object.
5. Code reusability
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.
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.
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.
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
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.
Example:
Syntax:
1. /*
2. This
3. is
25
4. multi line
5. comment
6. */
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
byte 0 1 byte
short 0 2 byte
26
int 0 4 byte
long 0L 8 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.
Types of Variable
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.
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.
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.
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.
The logical expression defer a value of true or false. Following table shows the truth table of
Logical – OR and Logical – AND.
32
T F T
F T T
F F F
T - True
F - False
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.
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.
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.
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.
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.
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
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:
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:
Enumerated types
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 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.
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;
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.
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.
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.
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
Program:
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
System.out.println(name);
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.
import java.util.Scanner;
class GetInputFromUser
String s = in.nextLine();
int a = in.nextInt();
float b = in.nextFloat();
}}
Advantages:
43
Reading password without echoing the entered characters.
Reading methods are synchronized.
Format string syntax can be used.
Drawback:
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.
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:
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.
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.
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.
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.
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.
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.
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:
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;
}
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
}
}
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;
}
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
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;
}
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.
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
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.
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).
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 changeContrast(int x){ System.out.println(“Constrast Changed by” + x);
}
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.
To stop a class from being extended, the class declaration must explicitly say it cannot be
inherited.
Defining a Package:-
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
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
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
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.
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.
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.
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.
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:
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.
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.
68
read( ) int Reads a single character
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:
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.
Method Description
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.
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.
Let‘s now see some I/O streams that are used to perform reading and writing operation in a file.
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:
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();
}
}
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.
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)
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.
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.
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
78
o Statement
o PreparedStatement
o CallableStatement
The statement interface provides three different methods for executing SQL statements :
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
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();
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.
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();
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());
}
}
}
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.
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.
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
---
2. Write a java program to explain the concept of Classes and Objects. [15]
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?
3. Define Encapsulation?
4. Define Inheritance?
5. Benefits of inheritance.
6. Define Polymorphism?
5. History of java.
6. What are variables? Discuss about the scope and life time of variables in detail.
89
UNIT II
Short Answer Questions
2. Define constructor?
4. Define recursion?
11. Write about the console input and output with an example.
90
Long Answer Questions
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?
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?
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
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.
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
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?
Assignment-4
95
1. Explain creation of thread using runnable interface and extending thread class 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.
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
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
97
15.In java, the equal sign is
a.increment b.decrement c.assignment d.negation
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
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.
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
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
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
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
102
c) Abstract class can be initiated by new operator.
d) Abstract class can be inherited.
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
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
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
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
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.
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
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();
109
23. A thread is a
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
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
114
21.Tutorial problems
Tutorial-1
Tutorial-2
Tutorial-3
Tutorial-4
Tutorial-5
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
Tutorial-8
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:
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.
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.
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.
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.
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.
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
121
122