Javamaterial
Javamaterial
Javamaterial
SEMESTER III
Data structures are designed such that they characterize the objects.
OBJECTS
ENCAPSULATION
POLYMORPHISM
INHERITANCE
ABSTRACTION
Class
A class is a data-type that has its own members i.e. data members and member
functions. It is the blueprint for an object in object oriented programming language.
It is the basic building block of object oriented programming in c++. The members of a
class are accessed in programming language by creating an instance of the class.
Object
Encapsulation
In our colleges, we have departments for each course like computer science,
information technology, Computer Application, etc. each of these departments have
their own students and subjects that are kept track of and being taught.
let's think of each department as a class that encapsulates the data about students of
that department and the subjects that are to be taught.
Also a department has some fixed rules and guidelines that are to be followed by the
students that course like timings, methods used while learning, etc. this is
encapsulation in real life, there are data and there are ways to manipulate data.
Polymorphism
The name defines polymorphism is multiple forms. which means polymorphism is the
ability of object oriented programming to do some work using multiple forms. The
behaviour of the method is dependent on the type or the situation in which the method
is called.
Let‟s take a real life example, A person can have more than one behaviour depending
upon the situation. like a woman a mother, manager and a daughter And this define
her behaviour. This is from where the concept of polymorphism came from.
In C++ programming language, polymorphism is achieved using two ways. They are
operator overloading and function overloading.
Operator overloading
Function overloading
Functions with the same name that can do multiple types based on some condition.
Inheritance
single inheritance
multiple inheritance
Hierarchical inheritance
hybrid inheritance
Abstraction
Data abstraction or Data Hiding is the concept of hiding data and showing only
relevant data to the final user. It is also an important part object oriented programing.
let's take real life example to understand concept better, when we ride a bike we only
know that pressing the brake will stop the bike and rotating the throttle will accelerate
but you don't know how it works and it is also not think we should know that's why this
is done from the same as a concept data abstraction.
In C++ programming language write two ways using which we can accomplish data
abstraction −
using class
There are several benefits of OOP to both program designer and the user. Object orientation
solves many problems which are associated with the development and quality of software
products. New technology gives greater programmer productivity, good quality of software
and low maintanance cost. The main advantages are:
We can eliminate redundant code and extend the use of existing classes.
The data hiding rules helps the programmer to make secure programs that
cannot be invaded by code in other parts of the program.
It has map objects in the problem domain to those objects in the program.
1. Image Processing
2. Pattern Recognition
3. Computer Assisted Concurrent Engineering
4. Computer Aided Design and Manufacturing
5. Computer Aided Teaching
6. Intelligent Systems
7. Database Management Systems
8. Web based Applications
9. Distributed Computing and Applications
10. Component based Applications
11. Business Process Reengineering
12. Enterprise resource planning
13. Data security and management
14. Mobile Computing
15. Data Warehouse and Data Mining
16. Parallel Computing
Java History:
Java is as of 2012 one of the most popular programming languages in use, particularly
for client-server web applications, with a reported 10 million users.
The original and reference implementation Java compilers, virtual machines, and class
libraries were developed by Sun from 1991 and first released in 1995.
As of May 2007, in compliance with the specifications of the Java Community
Process, Sun relicensed most of its Java technologies under the GNU General Public
License.
Milestones of Java
1.5 Java features:
The inventors of java wanted to design a language which could offer solutions to some
of the problems encountered in modern programming they wanted the language to be not
only reliable, portable and distributed but also simple, compact and interactive
Sun micro System officially describes java with the following attributes:
Compiled and interpreted
Platform _independent and portable
Object-oriented
Robust and secure
Distributed
Familiar, simple and interactive
High performance
Dynamic and Extensible
Ease of development
Scalability of performance
Monitoring and manageability
desktop client
Core XML support
Supplementary character support
JDBC Rowset
These features have made java the first application language of the World Wide Web java
will also become the premier language for general purpose standalone application
Simple and powerful
Object oriented to java
You can learn to program in java quickly once the basic concepts of object-oriented
programming are understood.
You once need to understand a few concepts in order to write productive and
satisfying program.
This style of simplicity has often produced inefficient and non-expressive “scripting
language”.
Java is not scripting language.
Safe
Java is protocol, it provide security and safe.
Even your word processor documents can carry viruses.
One of the key design principles of java is safety and security.
Object-oriented
Class and object are used in java.
Most other object-oriented systems have chosen to have rigid, hard-to –manage
object hierarchies.
It is not a direct derivative of any other programming language, nor is‟t in any way
upward compatible with one.
Robust
It is very strong it is a case sensitive language.
You might think that robustness is a luxury in these times of adventure on the internet.
Java is a very strict language when it comes to type and declarations, most common
errors can be caught time.
Interactive
Requirements real word event It is very interactive to use.
Java was designed to meet the real-word requirement of creating interactive network
program.
Most systems have a hard time dealing with either
One, let alone interactivity and networking at once.
Architecture neutral
Portable language.
Run anywhere at any time.
It‟s work on “macintosh, pc, unix” and whatever the platforms can offer.
Interpreted and high performance
Java is the byte code format it‟s carefully design.
All platforms are independent.
It‟s easy to translate directly into native machine code for very high performance.
Easy to learn
The language features feel like the natural way to do things and encourage good
programming style.
Java is more complicated then a scripting language.
It‟s an object-oriented program.
Java is Compiled and Interpreted
Java compiler
Java is not lot like C but the major difference between Java and C is that Java is an object-
oriented language and has a mechanism to define classes and objects. In an effort to build a
simple and safe language, the Java team did not include some of the C features in Java.
1. Java does not include the C unique statement keywords size of and typedef.
2. Java does not contain the data type struct and union.
3. Java does not define the type modifiers keywords auto, extern, register, signed, and
unsigned.
4. Java does not support an explicit pointer type.
5. Java does not have a preprocessor and therefore we cannot use # define, # include,
and # ifdef statements.
6. Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
7. Java adds new operators such as instanceof and >>>.
8. Java adds labelled break and continue statements.
9. Java adds many features required for object-oriented programming.
It does include the unique statement It does not include the C unique statement
keywords sizeof, and typedef. keywords sizeof, and typedef.
It contain the data type struct and union. It does not contain the data type struct and union.
C Programming Java Programming
It define the type modifiers keywords It does not define the type modifiers keywords
auto, extern, register, signed, and auto, extern, register, signed, and unsigned.
unsigned.
It supports an explicit pointer type. It does not support an explicit pointer type.
It has a preprocessor and therefore we It does not have a preprocessor and therefore we
can use # define, # include, and # ifdef cannot use # define, # include, and # ifdef
statements. statements.
It requires that the functions with no It requires that the functions with no arguments
arguments, with the void keyword must be declared with empty parenthesis, not
with the void keyword
C has no operators such as instanceof Java adds new operators such as instanceof and
and >>>. >>>.
C adds have a break and continue Java adds labeled break and continue statements.
statements.
C has no object-oriented programming Java adds many features required for object-
features. oriented programming.
Listed below are some major C++ features that were intentionally omitted from Java or
significantly modified.
It support has template classes. It does not have template classes as in C++.
It supports global variables. It does not support global variables. Every variable and
method is declared within classes and forms part of that
class.
It does not support destructor It has replaced the destructor function with a finalize()
function with a finalize() function. function.
There are header files in Java. There are no header files in Java.
Web Browsers
The internet is a vast sea of information represented in many formats and stored on many
computers. a browser is a software application used to locate, retrieve and display
content on the World Wide Web, including Web pages, images, video and other files.
As a client/server model, the browser is the client run on a computer that contacts the
Web server and requests information. The Web server sends the information back to the
Web browser which displays the results.
The browser application retrieves or fetches code, usually written in HTML (Hypertext
Markup Language) and/or another language, from a web server, interprets this code, and
renders (displays) it as a Web page for you to view. on the computer or another Internet-
enabled device that supports a browser.
Hot Java
Netscape Navigator
Internet Explorer
Google Chrome
Web Browser
local computer should be connected to the internet
Web Server
A program that accepts a request from a user and gives output as per the requirement.
Apache TomCat server is one of the major web servers.
Web Browser
The web browser is a software that will allow you to view web pages on the internet. it is a
program that you use to access the Internet. It reads and knows how to display and
download files that are put on servers for people to read. A program that provides the access
of WWW and runs java applets. Chrome and Firefox are two major web browsers.
HTML
HTML is short for Hypertext Markup Language. HTML is used to create electronic documents
(called pages) that are displayed on the World Wide Web. Each page contains a series of
connections to other pages called hyperlinks. Every web page you see on the Internet is
written using one version of HTML code or another.
Execution of Applets
Interactive WWW
Flashy animation instead of static web pages
Applets react to users input and dynamically change
Display of dynamic data
WWW with Java - more than a document publishing medium
http://www.javasoft.com/applets/alpha/applets/StockDemo/standalone.html
Power of Java and the Web
Deliver applications, not just information
Eliminate porting
Eliminate end-user installation
Slash software distribution costs
Reach millions of customers - instantly
Java Development Kit
javac - The Java Compiler
java - The Java Interpreter
jdb- The Java Debugger
appletviewer -Tool to run the applets
javap - to print the Java bytecodes
javaprof - Java profiler
javadoc - documentation generator
javah - creates C header files
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various types
of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
You can use any editor like notepad or any Java IDE for writing java programs.
/*
*/
class Welcome
After we have written our program we need to compile and run the program. For that we
need to use the compiler called javac which is provided by java.
Go to the command prompt and type the file name as shown here.
c;\>javac Welcome.java
The javac compiler will create a class file called Welcome.class that contains only bytecodes.
These bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the
bytecodes into machine codes. Once we successfully compiled the program, we need to run
the program in order to get the output. So this can be done by the java interpreter called java.
In the command line type as shown here.
c:\>java Welcome
Welcome to Java-Sample!!!
Java Tokens
Token: A unit of user input. Tokens are separated by whitespace (spaces, tabs, new
lines).
Example: If an input file contains the following:
23 3.14
"John Smith"
The tokens in the input are the following, and can be interpreted as the given
types:
Token Type(s)
3. "John String
4. Smith" String
JVM
JVMs are available for many hardware and software platforms. The use of the same
bytecode for all JVMs on all platforms allows Java to be described as a "compile once, run
anywhere" programming language, as opposed to "write once, compile anywhere", which
describes cross-platform compiled languages. Thus, the JVM is a crucial component of the
Java platform.
Java bytecode is an intermediate language which is typically compiled from Java, but it can
also be compiled from other programming languages. For example, Ada source code can be
compiled to Java bytecode and executed on a JVM.
Important University Question Bank
Section - B
Section-C (8 MARK)
1. Discuss basic concept of oops.(2017,2010)
2. Describe the structure of java program with an example(2012)
3. Discuss basic concept of oops.(2019)
4. Describe the structure of java program with an example.(2013)
5. Briefly describe about any four OOP concepts.( 20072014,2019)
6. Explain the basic concept of oops.(2015)
7. How java differs from c and c++.(2017,2019)
8. Describe the various feature of java.(2013,2019)
9. Discuss the application and benefit of OOP. (2013,2015,2019)
10. Explain the following concept with an example(2016,2018)
i. Web browser ii. Java tokens
11. Explain the basic concept of object oriented programming.(2011,2019)
12.Write a note on java tokens. (2011,2014)
Expected Questions
Semester: III
Unit – II
2.1. Constants 2
2.2. Variables 4
2.3. Data Types 7
2.4. Operators and Expressions 11
1
2.1. Constants
• A constant value is the one which does not change during the execution of a program.
• Constants can be of any of the basic data types.
2
• Examples of real constants are: 0.0026, -0.97, 435.29, +487.0, 3.4E-2, 4.5E5
• A floating-point constant consists of a sequence of decimal digits, a decimal point, and
another sequence of decimal digits. A minus sign can precede the value to denote a
negative value. Either the sequence of digits before the decimal point or after the decimal
point can be omitted, but not both.
• Single Character constants are enclosed between single quotes('). For example, 'a' and
'%' are both character constants. So these are also called single quote character
constant.
• For example: 'a', 'M', '5', '+', '1' etc. are some valid single character constant.
• A string is a set of characters enclosed in double quotes ("). For example: "Punar
Deep" is a string.
• You must not confuse strings with characters. A single character constant is enclosed
in single quotes, as in 'a'. However, "a" is a string containing only one letter.
• For example: "Dinesh", "Hello", "2013", "2013-2020", "5+3", "?+!" etc. are some valid
string character constant. These are used for printing purpose or display purpose in the
java program's output statements. These can also be used for assigning the string data
to the character (string) type variables.
• Java Also Supports Backslash Constants those are used in output methods For Example
\n is used for new line Character These are also Called as escape Sequence or backslash
character Constants For Ex: \t For Tab ( Five Spaces in one Time ) \b Back Space etc.
3
2.2. Variables
• Variable is an identifier which holds data or another one variable is an identifier whose
value can be changed at the execution time of program. Variable is an identifier which
can be used to identify input data in a program.
• Every variable name should start with either alphabets or underscore (_) or dollar ($)
symbol. Note: Actually a variable also can start with ¥,¢, or any other currency sign.(in
advance version of java)
• Variables are case sensitive eg. int var must be used ‘var’ not ‘Var’
• They can be constructed with digits, letters. Eg. var12 or var2 must not be 12var
4
• No space is allowed in the variable declarations.
• Except underscore ( _ ) no special symbol are allowed in the middle of variable
declaration
• Variable name always should exist in the left hand side of assignment operators.
• int Sum, float height, double a_value are some examples for variable name
• White space is not allowed. Eg. int var1 is valid int va r1 is not valid
• Upper case lower cases are significant.
• Maximum length of variable is 64 characters
• No keywords should access variable name.
• Variable initialization means assigning a value to the variable. int a=10;
Variable declarations
Variable initialization
• It is the process of storing user defined values at the time of allocation of memory
space.
5
Variable assignment
Types of variable
6
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
• 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.
• Data type is a special keyword used to allocate sufficient memory space for the data, in
other words Data type is used for representing the data in main memory (RAM) of the
computer.
7
Three categories of data types
• Primitive data types are those whose variables allows us to store only one value but
they never allows us to store multiple values of same type.
• This is a data type whose variable can hold maximum one value at a time.
8
• Here "a" store only one value at a time because it is primitive type variable.
• Derived data types are those whose variables allow us to store multiple values of same
type. But they never allow to store multiple values of different types.
• These are the data type whose variable can hold more than one value of similar type.
In general derived data type can be achieve using array.
• Here derived data type store only same type of data at a time not store integer, character
and string at same time.
• User defined data types are those which are developed by programmers by making use
of appropriate features of the language.
• User defined data types related variables allows us to store multiple values either of same
type or different type or both. This is a data type whose variable can hold more than one
value of dissimilar type, in java it is achieved using class concept.
• Note: In java both derived and user defined data type combined name as reference
data type.
• In C language, user defined data types can be developed by using struct, union, enum
etc. In java programming user defined datatype can be developed by using the features
of classes and interfaces.
9
Integer category data types
• These category data types are used for storing integer data in the main memory of
computer by allocating sufficient amount of memory space.
• Integer category data types are divided into four types which are given in following table
• Float category data type are used for representing float values. This category contains
two data types, they are in the given table
• Boolean category data type is used for representing or storing logical values is true or
false. In java programming to represent Boolean values or logical values, we use a data
type called Boolean.
10
2.4. Operators and Expressions
11
Arithmetic Operators
• Java Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus.
• Given table shows the entire Arithmetic operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.
12
Relational Operators
• Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a java program
• Given table shows the entire relatinal operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.
13
Logical Operators
• These operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in java language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
• Which can be used to combine more than one Condition?. Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B)
&& (B>C). Here && is Logical Operator.
Assignment Operators
• In java programs, values for the variables are assigned using assignment operators.
• Let’s suppose variable A hold 8 and B hold 3.
14
Increment/Decrement Operators
• Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
• Increment / Decrement operator are two types as follows:
o Post increment / decrement
o Pre increment / decrement
• Syntax:
o Increment operator: ++var_name; (or) var_name++;
o Decrement operator: – -var_name; (or) var_name – -;
• Example:
o Increment operator : ++ i ; i ++ ;
o Decrement operator : – – i ; i – – ;
15
Conditional Operators (Ternary Operators)
• Conditional operators return one value if condition is true and returns another value is
condition is false.
• This operator is also called as ternary operator.
• Syntax : (Condition? true_value: false_value);
• Example : (A > 100 ? 0 : 1);
16
Bit Wise Operators
• These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
• Bit wise operators in java language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR),
^ (XOR), << (left shift) and >> (right shift).
17
18
2.5. Decision Making Statements
• Decision making structures require that the programmer specifies one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed.
• if the condition is determined to be true, and optionally, other statements to be executed
if the condition is determined to be false.
o Simple if statement
o If else statement
o Nested If-else statement
o Switch statement
o Conditional or Ternary operator statement
Simple If Statement
• The if statement is powerful decision making statement and is used to control the flow
of execution of statements.
• It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression is ‘true’ or ‘false’, it transfer the control to a particular
statement.
• An if statement consists of a Boolean expression followed by one or more statements
• If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-
inside' is skipped and only 'statement-outside' is executed.
19
If else statement
20
21
Nested if...else statement
• The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
• The nested if...else statement allows you to check for multiple test expressions and
execute different codes for more than two conditions.
22
• if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to
perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is
executed otherwise 'statement-block2' is executed.
Switch Statement
• Switch statement is used to solve multiple option type problems for menu like program,
where one value is associated with each option.
• The expression in switch case evaluates to return an integral value, which is then
compared to the values in different cases, where it matches that block of code is
executed, if there is no match, then default block is executed.
• The general form of switch statement is,
23
• The expression is an integer expression or character value1, value-2 ----- are constants
or constant expressions
24
• You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
• Conditional operators return one value if condition is true and returns another value is
condition is false.
• The conditional operator (? :) is a ternary operator (it takes three operands). The
conditional operator works as follows:
• Where
o expression1 is Condition
o expression2 is Statement Followed if Condition is True
o expression2 is Statement Followed if Condition is False
25
2.6. Loop Statements
• Entry controlled loop, the condition is tested before the execution of the loop. If the test
condition is true, then the loop gets the execution, otherwise not.
• The types of loop where the test condition is stated at the end of the body of the loop,
are know as the exit controlled loops.
• In the case of the exit controlled loops, the body of the loop gets execution without
testing the given condition for the first time.
26
• Then the condition is tested. If it comes true, then the loop gets another execution and
continues till the result of the test condition is not false.
For Loop
• for loop is used to execute a set of statements repeatedly until a particular condition is
satisfied. we can say it an open ended loop.
27
• Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any loop control
variables.
• Condition: This is next step after initialization step, if it is true, the body of the loop is
executed, if it is false then the body of the loop does not execute and flow of control goes
outside of the for loop.
• Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This
statement allows to update any loop control variables.
28
29
While Loop
• In while loop first check the condition if condition is true then control goes inside theloop
body otherwise goes outside of the body. while loop will be repeats in clock wise direction.
• While loop can be addressed as an entry control loop. It is completed in 3 steps
o Variable initialization.( e.g int x=0; )
o condition( e.g while( x<=10) )
o Variable increment or decrement ( x++ or x-- or x=x+2 )
30
31
Do..While Loop
• In some situations it is necessary to execute body of the loop before testing the condition
• Such situations can be handled with the help of do-while loop.
• do statement evaluates the body of the loop first and at the end, the condition is checked
using while statement (or) The do..while loop is similar to the while loop with one
important difference is the body of do...while loop is executed once, before checking the
test expression. Hence, the do...while loop is executed at least once.
32
• The code block (loop body) inside the braces is executed once
• Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0 (false).
• When the test expression is false (nonzero), the do...while loop is terminated.
Jump in Loops
• Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or
to leave the loop as soon as certain condition becomes true, that is called jumping out
of loop.
• The types of jump in loops are
o Continue
o Break
Continue
33
• Syntax Continue;
34
APT
Break
• When break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop
• When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement Syntax break;
36
APT
2.7. Class
• The classes are the most important feature of java that leads to Object Oriented
programming.
• Class is a user defined data type, which holds its own data members and member
functions, which can be accessed and used by creating object of that class.
• The variables inside class definition are called as data members and the functions are
called member functions
• A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces.
• A class definition must be followed either by a semicolon or a list of declarations.
• For example, we defined the Box data type using the keyword class as follows:
• A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Objects
• Once a class is defined, you can declare objects of that type. The syntax for declaring a
object is the same as that for declaring any other variable.
• Objects are instances of class, which holds the data variables declared in class and the
member functions work on these class objects.
• To use the data and access functions defined in the class, you need to create objects.
37
APT
• The new keyword is used to allocate memory at run time. All objects get memory in
Heap memory area.
• Creating multiple objects by one type only
Method in Java
38
APT
39
APT
2.8. Creating Method
Method Calling
40
APT
o The return statement is executed.
o It reaches the method ending closing brace
41
Course Material
Semester: III
Unit – III
1
2
3.1. Java Array
• Array is a collection of similar type of data. It is fixed in size means that you can't
increase the size of array at run time
• An array is a collection of similar types of data. It is a container that holds data (values)
of one single type. For example, you can create an array that can hold 100 values of int
type.
• Good question! We have to allocate memory for the array. The memory will define the
number of elements that the array can hold.
o data = new Double[10];
• Here, the size of the array is 10. This means it can hold 10 elements (10 double types
values). The size of an array is also known as the length of an array.
• In Java, each element in an array is associated with a number. The number is known
as an array index. We can access elements of an array by using those indices. For
example,
• int[ ] age = new int[5];
3
How to initialize arrays in Java?
• In Java, we can initialize arrays during declaration or you can initialize later in the
program as per your requirement.
• Initialize an Array During Declaration
• we can easily access and alter elements of an array by using its numeric index
• Here's how you can initialize an array during declaration.
o int[] age = {12, 4, 5, 2, 5};
Advantage of Array
• One variable can store multiple value: The main advantage of the array is we can
represent multiple value under the same name.
• Code Optimization: No, need to declare a lot of variable of same type data, We can
retrieve and sort data easily.
4
• Random access: We can retrieve any data from array with the help of the index value.
Disadvantage of Array
• The main limitation of the array is Size Limit when once we declare array there is no
chance to increase and decrease the size of an array according to our requirement,
Hence memory point of view array concept is not recommended to use.
Array creation
• Every array in a Java is an object, Hence we can create array by using new keyword.
• Note: At the time of array creation we must be specify the size of array otherwise get
an compile time error.
o For Example
o int[] a=new int[]; Invalid (some times).
o int[] a=new int[5]; Valid
• If we specify the array size as negative int value, then we will get run-time error,
• The maximum allowed size of array in Java is 2147483647 (It is the maximum value of
int data type)
5
Difference Between Length and Length() in Java
• length: It is a final variable and only applicable for array. It represent size of array.
• length(): It is the final method applicable only for String objects. It represents the
number of characters present in the String.
Types of Array
• Multidimensional Array
6
3.2. Java String
• Strings represents sequence of char values. An array of characters works same as java
string.
String literal
7
• Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:
New keyword
• In such case, JVM will create a new string object in normal(non pool) heap memory and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in heap(non pool).
8
3.3. Vector in Java
• Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit.
Creating a Vector
9
Methods of Vector
• The Vector class also provides the resizable-array implementations of the List interface
(similar to the ArrayList class). Some of the Vector methods are:
10
• Vector implements a dynamic array. It is similar to ArrayList
• Vector class object organizes the data in the form of cells
• Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program
•
• The default capacity of the Vector v=10 cells
• Vector are Synchronized
• Vector uses Enumeration interface to traverse the elements
• Vector class object organizes the data in the form of cells
11
• The default size of the Vector=0 (size is nothing but number of values available in the
cells)
• In Vector cell values are storing in Heap Memory and cell address
12
• All the methods of an interface are by default public. So, it is not required to use the
keyword public when declaring a method in an interface.
• As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Creating interface:
13
• In the above syntax Interface is a keyword interface name can be user defined name
the default signature of variable is public static final and for method is public abstract.
Extending interface
• An interface can extend another interface in the same way that a class can extend
another class.
• The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface, this means an interface can be sub-interface from
other interfaces, the new sub-interface will inherit all the members of the super-
interface in the manner similar to subclass
Implementing Interface:
14
Rules for implementation interface
15
16
3.5. Java Packages
• Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
• Application development time is less, because reuse the code
• Package in java can be Categorized in two form
o Built-in package
o User-defined package
Built-in package
17
• java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
• java.io: Contains classed for supporting input / output operations.
• java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
• java.applet: Contains classes for creating Applets.
• java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
• java.net: Contain classes for supporting networking operations.
User-defined packages
18
• Import above class in below program using import packageName.className
• Explanations: In above syntax "-d" is a specific tool which is tell to java compiler
create a separate folder for the given package in given path. When we give specific
path then it create a new folder at that location and when we use . (dot) then it crate a
folder at current working directory.
• Explanations: In the above program first we create Package program which is save
with A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello
using "import mypack.A;" statement.
• Package keyword is always used for creating the undefined package and placing
common classes and interfaces.
• Import Is A Keyword which is used for referring or using the classes and interfaces of
a specific package.
Access Package
• There are Three ways to access the package from outside the package.
o import package.*;
o import package.classname;
o fully qualified name
Using Packagename.*
19
• If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages (Package inside the package is called the
subpackage).
• The import keyword is used to make the classes and interface of another package
accessible to the current package.
Using packagename.classname
• If you import package.classname then only declared class of this package will be
accessible.
20
Using fully qualified name
• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
21
Subpackage in java
• A program can be divided into a number of small processes. Each small process can
be addressed as a single thread.
• Multithreaded programs contain two or more threads that can run concurrently and
each thread defines a separate path of execution. This means that a single program
22
can perform two or more tasks simultaneously. For example, one thread is writing
content on a file at the same time another thread is performing spelling check.
• In computer, multitasking is when multiple processes share common processing
resources such as a CPU, hard disk etc... Multi-threading extends the idea of
multitasking into applications where you can subdivide specific operations within a
single application into individual threads.
• Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
• A Thread is similar to a program that has a single flow of control, It has a beginning, a
body, and an end, and executes commands sequentially.
• Thread is a lightweight components and it is a flow of control. In other words a flow of
control is known as thread, Threads share the same address space.
• Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
• It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
• You can perform many operations together so it saves time.
• Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
23
• New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.
24
3.8. Creating Threads
• Create any user defined class and make that one as a derived class of thread class.
25
• Override run() method of Thread class (It contains the logic of perform any operation)
• Create an object for user-defined thread class and attached that object to predefined
thread class object.
• Object Creation for Thread Class_Name obj=new Class_Name Thread t=new
Thread(obj);
• Call start() method of thread class to execute run() method.
• Save the program with filename.java
26
• The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement the
run() method,
• Create any user defined class and implements runnable interface within that
• Override run() method within the user defined class.
• all start() method to execute run() method of thread class
Stopping thread
• When ever we want to stop a thread from running further, we may do so by calling its
stop() method, ex. aThread.stop();
• This statement causes the thread to move to the dead state.
• A thread will also move to the dead state automatically when it reaches the end of its
method.
Blocking thread
• A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either following thread methods.
• sleep() - block for a specified time
• suspend() - blocked until further order
• wait() - blocked until certain condition occurs
27
What is the difference between sleep() and suspend()
• Sleep() can be used to convert running state to waiting state and automatically thread
convert from waiting state to running state once the given time period is completed.
• Whereas suspend() can be used to convert running state thread to waiting state but it
will never return back to running state automatically.
• Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).
28
• sleep() - Used to change running state thread to ready state based on time period it is
a static method should be called with class reference.
• suspend() - used to convert running state thread to waiting state, which will never
come back to running state automatically.
• resume() - Used to change the suspended thread state(waiting state) to ready state.
• stop() - This method is used to convert running state thread to dead state.
• getState() - This method is used to get the current state of thread.
29
Course Material
Semester: III
Unit – IV
1
4.1. Errors
• Syntax errors will be detected and displayed by the java compiler and therefore these
errors are known as compile time error.
• Whenever compiler displays an error, it will not create the .class file.
• It is necessary that we fix all the errors before we can successfully compile and run the
program.
• Mission semicolons
• Missing brackets in classes and methods
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables
• Incompatible types in assignment/initialization
• Bad reference to objects
• Use of = in place of == operator
2
• In the above program semicolon is missing in the first statement
Runtime error
• Sometimes a program may compile successfully creating .class file but may not run
properly, such program may produce wrong results due to wrong logic.
• infinite loop
• divide by zero
• Array Index Out of Bounds
• Finding remainder and storing answer in a float or double.
• Dividing float/float and storing answer in integer
• Negative size of array
• Converting invalid string to a number
3
4.2. Exceptions
• The process of converting system error messages into user friendly error message is
known as Exception handling.
• The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
• An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and
the program/Application terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.
Type of Exception
o Checked Exception
o Un-Checked Exception
Checked Exception
• Checked Exception are the exception which checked at compile-time. These exception
are directly sub-class of java.lang.Exception class.
• Only for remember: Checked means checked by compiler so checked exception are
checked at compile-time.
o FileNotFoundException
o ClassNotFoundException
o IOException
o InterruptedException
4
Un-Checked Exception
• They are the exception both identifies or raised at run time. These exception are
directly sub-class of java.lang.RuntimeException class.
• Note: In real time application mostly we can handle un-checked exception.
• Only for remember: Un-checked means not checked by compiler so un-checked
exception are checked at run-time not compile time.
o ArithmeticException
o ArrayIndexOutOfBoundsException
o StringIndexOutOfBoundsException
o NumberFormateException
o NullPointerException
o NoSuchMethodException
o NoSuchFieldException
5
Difference between checked Exception and un-checked Exception
• Handling the exception is nothing but converting system error generated message into
user friendly error message in others word whenever an exception occurs in the java
application, JVM will create an object of appropriate exception of sub class and
generates system error message, these system generated messages are not
understandable by user so need to convert it into user-friendly error message.
6
• You can convert system error message into user-friendly error message by using
exception handling feature of java.
o try
o catch
o finally
o throw
Try block
• Inside try block we write the block of statements which causes executions at run time in
other words try block always contains problematic statements.
• If any exception occurs in try block then CPU controls comes out to the try block and
executes appropriate catch block.
• After executing appropriate catch block, even through we use run time statement, CPU
control never goes to try block to execute the rest of the statements.
7
• Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
• Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly error
messages.
• One try block can contains another try block that is nested or inner try block can be
possible.
Catch block
• Inside catch block we write the block of statements which will generates user friendly
error messages.
8
• You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.
• At a time only one catch block will execute out of multiple catch blocks.
• in catch block you declare an object of sub class and it will be internally referenced by
JVM.
• Abnormally terminate program and give a message like below, this error message is
not understandable by user so we convert this error message into user friendly error
message, like "denominator not be zero".
9
Example of Exception Handling using try and catch block
• You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.
10
Finally Block
• Inside finally block we write the block of statements which can handle an exception that
is not caught by any of the previous catch statements.
11
Finally block important points
Throw block
• Throw is a keyword in java language which is used to throw any user defined exception
to the same signature of method in which the exception is raised.
• Note: throw keyword always should exist within method body.
12
Throws
which is raised in the called method to it's calling method throws keyword
• Applets are small java programs that are primarily used in internet computing.
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
• An applet, like any application program, can do many things for us, it can perform
arithmetic operations, display graphics, play sounds, accept user input, create
animation and play interactive games.
• An applet developed locally and stored in a local system is known as local applet,
When a web page is trying to find a local applet, it does not need to use interne facility.
• A remote applet is that which is developed by someone else and stored on a remote
computer connected to the internet.
Advantage of Applet
13
o Initialization - init()
o start()
o paint()
o stop()
o destroy()
• init(): Which will be executed whenever an applet program start loading, it contains the
logic to initiate the applet properties.
• paint(): It displays the result of the applet code on the screen. The output may be text,
graphics, or sound.
• start(): It will be executed whenever the applet program starts running.
• stop(): Which will be executed whenever the applet window or browser is minimized.
• destroy(): It will be executed whenever the applet window or browser is going to be
closed (at the time of destroying the applet program permanently).
• Without these import statements, the Java compiler would not recognize the classes
Applet and Graphics, which the applet class refers to.
• import java.applet.*; Applet class which is contained this package provides lifecycle and
behavior to the applet through its methods init(), start() and point()
• import java.awt.*; contains graphics class, all output operations of an applet are
performed using the methods defined in the graphics class, The output may be text,
graphics, or sound.
14
4.5. Running of Applet Programs
• In general no Java program can directly execute on the web browser except markup
language like html.
• Html support a predefined tag called <applet> to load the applet program on the
browser window.
15
Running of applet using appletviewer
• Some browser does not support <applet> tag so that Sun MicroSystem was introduced
a special tool called appletviewer to run the applet program.
• Applet tag is /*<Applet code=filename.class height=200 width=200></Applet>*/
• In this Scenario Java program should contain <applet> tag in the commented lines so
that appletviewer tools can run the current applet program.
The following are the commandds used to compile & run applet program
16
4.6. AWT (Abstract Window Toolkit)
• AWT stand for abstract window toolkits. Any user interact with java program in two
different way;
o CUI (Command user Interface)
o GUI (Graphical user Interface)
17
• If any user interact with java program by passing same commands through command
prompt is known as CUI, if any user interact with java program through a graphical
window known as GUI.
• Container classes - These are the predefined classes in java.awt package which can
be used to display all non-container classes to the end user in the frame of window.
container classes are; frame, panel.
• Non-container classes - These are the predefined classes used to design the input
field so that end user can provide input value to communicate with java program, these
are also treated as GUI component. non-container classes are;
• Label - It can be any user defined name used to identify input field like textbox,
textarea etc.
18
• TextField - This class can be used to design textbox.
• TextArea - This class can be used to design a textarea, which will accept number of
characters in rows and columns format.
• CheckboxGroup - This class can be used to design radio button. Radio button is used
for single selection.
19
• Choice - This class can be used to design a drop down box with more options and
supports single selection.
• List - This class can be used to design a list box with multiple options and support multi
selection.
20
Display numeric value in applet
• In applets, we can display numerical values by first converting them into strings and
then using the drawstring() method of Graphics class we can do this easily by calling
the valueOf() Method of String class. Let us consider an example:
• Applets work in graphical environment, therefore applets treat input as text strings.
• We can do this by using the TextField class of the applet package.
• For any kinds of computation on the input field, we must convert it to the right form and
the results again converted back to strings for display.
21
AWT Frame
• Frame - It is a predefined class used to create a container with the title bar and body
part.
22
• setTitle() - It is used to display user defined message on title bar.
23
• add() - It is used to add non-container components (Button, List) to the frame.
• Explanation: In above code we add button on frame using f.add(b), here b is the object
of Button class.
• Java graphics class includes methods for drawing many different types of shapes
• To draw a shape on the screen, we may call one of the methods available in the
graphics class
• clearRect(int x, int y, int width, int height) - Clears the specified rectangle by filling it
with the background color of the current drawing surface.
• copyArea(int x, int y, int width, int height, int dx, int dy) - Copies an area of the
component by a distance specified by dx and dy.
24
• drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) - Draws the
outline of a circular or elliptical arc covering the specified rectangle
• drawLine(int x1, int y1, int x2, int y2) - Draws a line, using the current color, between
the points (x1, y1) and (x2, y2) in this graphics context's coordinate system
• drawOval(int x, int y, int width, int height) - Draws the outline of an oval
• drawPolygon(int[] xPoints, int[] yPoints, int nPoints) - Draws a closed polygon
defined by arrays of x and y coordinates.
• drawRect(int x, int y, int width, int height) - Draws the outline of the specified
rectangle
• drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) -
Draws an outlined round-cornered rectangle using this graphics context's current color
• drawString(String str, int x, int y) - Draws the text given by the specified string, using
this graphics context's current font and color
• fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) - Fills a circular
or elliptical arc covering the specified rectangle
• fillOval(int x, int y, int width, int height) - Fills an oval bounded by the specified
rectangle with the current color
• fillPolygon(int[] xPoints, int[] yPoints, int nPoints) - Fills a closed polygon defined
by arrays of x and y coordinates.
25
26
1
Unit V
Course Material
Semester: III
Syllabus
. Unit V: Managing Input / Output Files in Java : Concepts of Streams- Stream Classes –
Byte Stream classes – Character stream classes – Using streams – I/O Classes – File
Class – I/O exceptions – Creation of files – Reading / Writing characters, Byte-Handling
Primitive data Types – Random Access Files.
The concept of sending data from one stream to another (like one pipe feeding into
another pipe) has made streams in Java a powerful tool for file processing.
2
Program Destination
Writes
Output streams
Java streams are classified into two basic types, namely, input stream and output
stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the
program. Similarly, an output stream takes data from the program and sends (i.c. writes) it
to the destination (file).
STREAM CLASSES
The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into two
groups based on the data type on which they operate.
a) Byte stream classes that provide support for handling I/O operations on bytes.
b) Character stream classes that provide support for managing I/O operations on
characters.
Write
Output Reader
Input Classes
Stream Classes
Stream
Method Description
1. read() reads a byte from the input stream
2. read (byte b[]) reads an array of bytes into b
3. read(byte b[],int n,int m) reads m bytes into b starting from nth byte
4. available() gives number of bytes available in the input
5. skip(n) skips over n bytes from the input stream
6. reset() goes back to the begining of the stream
7. close() close the input stream
Note that the class DatalnputStream extends FilterInputStream and implements the
interface Data Input. Therefore, the DatalnputStream class implements the methods
described in DataInput in addition to using the methods of InputStream class. The Datalnput
interface contains the following methods:
a) readShort() f) readDouble()
b) readLine() g) readUTF()
c) readChar() h) readLong()
d) readBoolean() i) readInt()
e) readFloat()
4
Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream
USING STREAMS
There are various types of input and output stream classes used for handling both the
16-bit characters and 8-bit bytes. Although all the classes are known as I/O classes, not all
of them are used for reading writing operations only. Some perform operations such as
buffering, filtering, data conversion, counting and concatenation while carrying out I/O tasks.
DataInput DataOutput
RandomAccessFile
INPUT/OUTPUT EXCEPTIONS
When creating files and performing I/O operations on them, the system may generate
i/o related exceptions. The basic i/o related exception classes and their functions are given
below.
Each I/O statement must have an exception handler around it as shown below:
try
{
.....................
. ........................ //I/O statements
.....................
}
catch (IOException e)
{
.................... // Message output statement
}
CREATION OF FILES
If we want to create and use a disk file, we need to decide the following about the file
and its intended purpose:
• Suitable name for the file
• Data type to be stored
• Purpose (reading, writing or updating)
• Method of creating the file
(i) A filename is a unique string of characters that helps identify a file on the disk. The length
of a filename and the characters allowed are dependent on the OS on which the java
program is executed. A file may consist of two parts, a primary name and an optional
period with extension.
9
Example:
Input.data Salary test.doc
student.txt
inventory rand.dat
(i) Data type is important to decide the type of file stream classes to be used for handling
the data. User should decide whether the data to be handled is in form of characters,
bytes or primitive type.
(i) The purpose of using a file must also be decided before using it. For example, user
should know whether the file is created for reading only, or writing only, or both the
operations.
The constructor, of stream classes may be used to assign the desired filenames to the file
stream objects.
There are two ways of initializing the file stream objects. All of the constructors
require that we provide the name of the file either directly, (as a literal string or variable), or
indirectly by giving a file object that has already been assigned a filename. The following
code segment illustrates the use of direct approach.
Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.
{
public static void main (String args[])
{
file inFile=new file ("input.dat");
file outFile=new file ("output.dat");
FileReader ins=null;
FileWriter outs=null;
try
{
ins=new FileReader (inFile); //Opens inFile
outs=new FileWriter (outFile); //Opens outFile
//Read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try
{
ins.close();
outs.close ();
}
catch (IOException e)
{}
}
}
}
12
READING/WRITING CHARACTERS
The subclasses of Reader and Writer implement streams that can handle characters.
The two subclasses used for handling characters in files are FileReader and FileWriter.
The general form is
FileReader fileobject=new FileReader(filename);
FileWriter fileobject= new FileWriter(filename);
Method Description
read() reads a byte from the input stream
read (byte b[]) reads an array of bytes into b
read(byte b[],int n,int m) reads m bytes into b starting from nth byte
available() gives number of bytes available in the input
skip(n) skips over n bytes from the input stream
reset() goes back to the beginning of the stream
close() close the input stream
Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream
Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.
{
ins=new FileReader (inFile); //Opens inFile
outs=new FileWriter (outFile); //Opens outFile
//Read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try
{
ins.close();
outs.close ();
}
catch (IOException e)
{}
} } }
The character -1 indicates the end of the file and therefore the code
while ( (ch-ins.read( ) ) != -1)
causes the termination of the while loop when the end of the file is reached. The statements
ins.close();
outs.close ( );
enclosed in the finally clause close the files created for reading and writing. When the
program catches an I/0 exception, it prints a message and then exits from execution.
14
READING/WRITING BYTES
The FileReader and FileWriter classes is used to read and write 16-bits characters.
Two commonly used classes for handling bytes are FileInputStream and FileOutputStream
classes. This is used in place of FileReader and FileWriter.
The general form is
FileInputStream fileobject=new FileInputStream(filename);
FileOutputStream fileobject=new FileOutputStream(filename);
Method Description
read() reads a byte from the input stream
read (byte b[]) reads an array of bytes into b
read(byte b[],int n,int m) reads m bytes into b starting from nth byte
available() gives number of bytes available in the input
skip(n) skips over n bytes from the input stream
reset() goes back to the beginning of the stream
close() close the input stream
Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream
The program demonstrates how FileOutputStream class is used for writing bytes to a
file. The writes to the names of some cities stored in a byte array to a new file named
"city.txt". User can verify the contents of the file by using the command
type city.txt
Explanation :
type city.txt
DELHI
MADRAS
LONDON
Program shows how FilelnputStream class is used for reading bytes from a file. The
program reads an existing file and displays its bytes on the screen. Remember, before we
run this program, we must first create a file for it to read. We may use this program to read
the file "city.txt" created in Program 1.
import java.io.*;
class ReadBytes
{
public static void main (string args[])
{
//Create an input file stream
FileInputStream infile=null;
int b;
try
{
//Connect infile stream to the required file
infile=new FileInputStream(args[0]);
16
The basic input and output streams provide read/write methods that can be used for
reading/writing bytes or characters. If we want to read/write the primitive data types such
as integers and doubles.
The two filter classes used for creating "data streams" for handling primitive types
are DataInputStream and DataOutputStream.
A data stream for input can be created as follows:
FileInputStream fis=new FileInputStream (infile);
DataInputStream dis=new DataInputStream (fis);
These statements first create the input file stream fis and then create the input data
stream dis. These statements basically wrap dis on fis and use it as a "filter". Similarly, the
following statements create the output data stream dos and wrap it over the output file
stream fos.
FileOutputStream fos=new FileOutputStream (outfile);
DataOutputStream dos=new DataOutputStream (fos);
The file objects infile and outfile must be initialized with appropriate file names before
they are used.
17
Note that the file objects infile and outfile must be initialized with appropriate file names
before they are used. User may also use file names directly in place of files objects.
Output:
18
1999
375.85
false
X
Example:
import java.io.*;
class randomIO
{
public static void main (string args[])
{
RandomAccessFile file=null;
try
{
file=new RandomAccessFile ("rand.dat",”rw”);
file.WriteChar(„X‟);
file.WriteInt(555);
file.Writedouble(3.1412);
file.seek(0);
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2);
19
System.out.println(file.readInt());
file.seek(file.length());
file.WriteBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOExceptiom e)
{
System.out.println(e);
}
}
}
The program opens a random access file and then performs the following operations.
1. Writes three items of data
X
555
3.1412
2. Brings the file pointer to the beginning.
3. Reads and displays all three items.
X
555
3.1412
4. Takes the pointer to the second item and then reads and displays the second item in the
file.
555
5. Places the pointer at the using the method length() and then add a Boolean item to the
file.
6. Finally, takes the pointer to the fourth item and displays it.
7. At the end, closes the file.
X
555
3.1412
555
false