Java
Java
UNIT : 1
Java Evolution: Java Features - How Java differs from C and C++ Java and Internet - Java and
World Wide Web - Web Browsers - Hardware and Software Requirements - Java Environment.
Overview of Java Language: Simple Java Program - Java Program Structure - Java Tokens -
Java Statements - Implementing a Java Program - Java Virtual Machine - Command Line
Arguments. Constant, Variables, and Data types : Constants – Variables – Data types –
Declaration of Variables – Giving Values to variables – Scope of Variables – Symbolic
Constants – Type Casting. Operators and Expressions: Arithmetic Operators – Relational
Operators – Logical Operators – Assignment Operators – Increment and Decrement Operators –
Conditional Operators – Bitwise Operators – Special Operators – Arithmetic Expressions –
Evaluation of Expression – Precedence of Arithmetic Operators – Operator Precedence and
Associativity - Mathematical Functions. Decision Making and Branching: Decision Making
with IF statement – Simple IF statement – IF Else statement – Nesting If Else Statement – the
EIself Ladder – The Switch Statement- The do statement – The for statement – Jumps in Loops.
UNIT – 2
Class, Objects and Methods: Defining a Class – Fields Declaration – Methods Declaration –
Creating Objects – Accessing Class members – Constructors – Methods Overloading – Static
Members – Nesting of Methods – Inheritance – Overriding Methods – Final Variables and
Methods – Final Classes – Finalizer Methods – Abstract Methods and Classes – Visibility
Control. Arrays, Strings and Vectors: One – Dimensional Arrays – Creating an Array – Two
dimensional Array – Strings – Vectors – Wrapper Classes – Enumerated Types. Interfaces:
Multiple Inheritance: Defining Interfaces – Extending Interfaces – Implementing Interfaces –
Accessing Interface Variables.
UNIT – 3
Packages: : Java API Packages – Using system packages – Naming Conventions – Creating
Packages – Accessing a Package – Using a Package – Adding a Class to a package – Hiding
Classes – Static Import. Multithreaded Programming: Creating Threads – Extending the
Thread Class – Stopping and Blocking a Thread – Life Cycle of a Thread – Using Thread
Methods – Thread Exceptions – Thread Priority – Synchronization – Implementing the Runnable
Interface.
UNIT 4
Managing Errors and Exceptions: Types of Errors – Exceptions – Syntax of Exceptions
Handling Code – Multiple Catch Statements – Using Finally Statement – Throwing our own
Exceptions – Using Exceptions for debugging. Applet Programming: How Applets differ from
Applications – Preparing to write Applets – Building Applet Code – Applet Life Cycle –
Creating an executable Applet – Designing a Web Page – Applet Tag – Adding Applet to HTML
file – Running the Applet.
UNIT : 5
Graphics Programming: The Graphics Class – Lines and Rectangles – Circles and Ellipses,
Drawing Arcs – Drawing Polygons – Line Graphs – Using Control Loops in Applets – Drawing
Bar Charts. Managing Input/Output Files in Java: Concept of Streams – Stream Classes –
Byte Stream Classes – Character Stream Classes – Using Streams – Other Useful I/o Classes –
Using the file Class – I/O Exceptions – Creation of Files- Reading / Writing Characters –
Reading/Writing Bytes- Handling Primitive Data Types – Concatenating and Buffering files-
Random Access Files- Interactive Input and Output.
UNIT : 1
What is programming?
The term programming means to create (or develop) software, which is also called a
program. Computer programs, known as software, are instructions that tell a computer what to
do.
What is Java?
Java is an object oriented, simple, distributed, interpreted, robust, architecture neutral,
portable, high performance, multithreaded, dynamic, powerful and versatile programming
language originally developed by Sun Microsystems and released in 1995 for developing
software running on the mobile device, desktop computer, and server.
JAVA EVOLUTION
Java History
1. Java was designed by Sun Microsystems in the early 1990s.Sun Microsystems was
purchased by Oracle in the 2010s.
2. Java was started as a project called "Oak" by a team led by James Gosling in June
1991.Gosling's goals were to implement a virtual machine and a language that had a
familiar C like notation but with greater uniformity and simplicity than C/C++.
3. The basic aim of java was to solve the problem of connecting many household machines
together.
4. The project was unsuccessful because no one wanted to use it.
5. Earlier Name of Java: OAK
6. Creator of Java: James Gosling (the father of Java)
7. As there was another language called Oak, they decided to rename OAK. The new name
was given to OAK, OAK was renamed Java in 1994s.
8. The First publication of Java 1.0 was released by Sun Microsystems in 1995 May 27. It
made the promise of "Write Once, Run Anywhere", with free run-times on popular
platforms.
9. In 2006-2007 Sun released Java as open source and platform independent software.
10. Java was targeted at Internet development (for developing Web applications.)
11. Applets Had early support from companies: Netscape Communications
Computer language innovation and development occurs for two fundamental reasons:
To adapt to changing environments and uses.
To implement refinements and improvements in the art of programming.
JAVA FEATURES
1. Compiled and Interpreted
2. Platform Independent and Portable
3. Object-Oriented
4. Robust
5. Secure
6. portable
7. Distributed
8. Architecture-Neutral
9. Familiar, Simple and Small
10. Multithreaded and Interactive
11. High Performance
12. Dynamic and Extensible
Compiled and Interpreted
Computer language is either compiled(c programming) or interpreted. Java combines
both these approaches thus making Java a two-stage system.Java compiler (javac) translates
source code into bytecode instructions. When a program is compiled to an intermediate form
(bytecode) and then interpreted by a virtual machine(JVM). Thus we can say Java is both
compiled and Interpreted.
Platform Independent and Portable
Java is platform independent (that is, architecture-neutral), meaning that you can write a
program once and run it on any computer. Platform-independent language that is used to produce
code that runs on a variety of CPUs under differing environments.
Object-Oriented
It is a true object oriented language. Almost everything in java is an object. All program
code and data reside within object and classes.
Robust
Java is a robust language. It provides many safe grounds to ensure reliable code. The
program must execute reliably in a variety of systems. Thus, the ability to create robust programs
was given a high priority in the design of Java. It has strict compile time and runtime checking
for the data type. It has better memory management system. Java also interprets the concept of
exception handling.
Secure
Security is the most important part of every language which is used as programming on
internet. Java has better security for every purpose. Java system not only verifies all memory
access but also ensure that no viruses are communicated with an applet.In java memory locations
cannot be accessed without proper authorization.
Portable
Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable.We may carry the java bytecode to any platform.
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols.This is mainly designed for network application. It has the ability to share both data
and programs.Java enables multiple programmers at multiple remote locations to collaborate and
work together in a single program.
Architecture-Neutral
Java compiler(javac) generates an architecture-neutral object file format(byte code), which
makes the compiled code(byte code) executable on many processors, with the presence of Java
Runtime Environment(JRE).The bytecode is similar to machine instructions but is architecture
neutral and can run on any platform that has a Java Virtual Machine (JVM). The goal of Java
is: "write once; run anywhere, anytime, forever."
Familiar, Simple and Small
Familiarity is another striking feature of java. Because Java inherits the C/C++ syntax and many
of the object-oriented features of C++, most programmers have little trouble learning Java.Java
was designed to be easy for the professional programmer to learn and use effectively.It is also a
small and simple language for that Java eliminates pointers, preprocessor header files
etc.learning Java will be even easier and it requires very little effort.
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.
C, C++, and Java are the most popular programming languages used today at a broad level. They
have a pretty similar syntax for basic concepts. Most of the basic constructs like if statements,
loops, function syntax, switch case statements and concepts like recursion are still valid. Many
other concepts like the syntax for comments, and the idea of static class variables, also held in
both Java and C++.
Java uses the syntax of C and structure of C++ language.
Aspects C C++ Java
The developed year 1972 1979 1991
Developed By Dennis Ritchie Bjarne Stroustrup James Gosling
C(Syntax) & C++
Successor of BCPL C
(Structure)
Paradigms Procedural Object Oriented Object Oriented
Platform Dependency Dependent Dependent Independent
50 defined (goto, const
Keywords 32 63
unusable)
Datatypes: union,
Supported Supported Not Supported
structure
Pre-processor Supported (#include, Supported (#include,
Not Supported
directives #define) #define)
Header files Supported Supported Use Packages (import)
Multiple Inheritance not
Inheritance No Inheritance Supported
Supported
Operator Overloading not
Overloading No Overloading Supported
Supported
Pointers Supported Supported No Pointers
Code Translation Compiled Compiled Interpreted
Storage Allocation Uses malloc, calloc Uses new, delete uses garbage collector
Multithreading and
Not Supported Not Supported Supported
Interfaces
Exception Handling No Exception Supported Supported
handling
Templates Not Supported Supported Not Supported
Storage class: auto,
Supported Supported Not Supported
extern
No Constructor or
Destructors Supported Not Supported
Destructor
Database Connectivity Not Supported Not Supported Supported
The web-browser is a program that accepts a request, processes the request and sends the
required documents.
The HTML document is returned to that user browser.
The document contains the applet tag which identifies the applet. The corresponding
applet is transferred to the user computer.
The Java enabled browser on the user's computer interprets the byte code and provide
output.
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.
An example of Web Browsers:
Hot Java
Netscape Navigator
Internet Explorer
Google Chrome
JAVA ENVIRONMENT
Compilation and Execution process. For most computer languages, the name of the file
that holds the source code to a program is immaterial. However, this is not the case with Java.
The first thing that you must learn about Java is that the name you give to a source file is very
important. For this example, the name of the source file should be Simple.java.
If your program has compile errors, you have to modify the program to fix them, then
recompile it. If your program has runtime errors or does not produce the correct result, you have
to modify the program, recompile it, and execute it again.
The Java language is a high-level language, but Java bytecode is a low-level language.
The bytecode is similar to machine instructions but is architecture neutral and can run on any
platform that has a Java Virtual Machine (JVM).Rather than a physical machine, the virtual
machine is a program that interprets Java bytecode. This is one of Java’s primary advantages:
Java bytecode can run on a variety of hardware platforms and operating systems. Java source
code is compiled into Java bytecode and Java bytecode is interpreted by the JVM. Your Java
code may use the code in the Java library. The JVM exe- cutes your code along with the code in
the library.
To execute a Java program is to run the program’s bytecode. You can execute the
bytecode on any platform with a JVM, which is an interpreter. It translates the individual
instructions in the bytecode into the target machine language code one at a time rather than the
whole pro- gram as a single unit. Each step is executed immediately after it is translated.
Applet Programs
Applets are small Java programs developed for Internet applications. An applet located in
distant computer can be downloaded via Internet and executed on a local computer using
Java capable browser.
How Will Java Technology Change Your Life?
Get started quickly: Although the Java programming language is a powerful object-
oriented language, it's easy to learn, especially for programmers already familiar with C
or C++.
Write less code: Comparisons of program metrics (class counts, method counts, and so
on) suggest that a program written in the Java programming language can be four times
smaller than the same program written in C++.
Write better code: The Java programming language encourages good coding practices,
and automatic garbage collection helps you avoid memory leaks. Its object orientation, its
JavaBeans™ component architecture, and its wide-ranging, easily extendible API let you
reuse existing, tested code and introduce fewer bugs.
Develop programs more quickly: The Java programming language is simpler than C++,
and as such, your development time could be up to twice as fast when writing in it. Your
programs will also require fewer lines of code.
Avoid platform dependencies: You can keep your program portable by avoiding the use
of libraries written in other languages.
Write once, run anywhere: Because applications written in the Java programming
language are compiled into machine-independent bytecodes, they run consistently on any
Java platform.
Distribute software more easily: With Java Web Start software, users will be able to
launch your applications with a single click of the mouse. An automatic version check at
startup ensures that users are always up to date with the latest version of your software. If
an update is available, the Java Web Start software will automatically update their
installation.
Java Install
Setup for Windows-
To install Java on Windows:
1. Go to "System Properties" (Can be found on Control Panel > System and Security >
System > Advanced System Settings)
2. Click on the "Environment variables" button under the "Advanced" tab
3. Then, select the "Path" variable in System variables and click on the "Edit" button
4. Click on the "New" button and add the path where Java is installed, followed by \bin. By
default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was
specified when you installed it). In that case, You will have to add a new path
with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
5. At last, open Command Prompt (cmd.exe) and type java -version to see if Java is
running on your machine
JAVA PROGRAM STRUCTURE
A Java program involves the following sections:
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
SIMPLE JAVA PROGRAM
public class FirstJavaProgram {
public static void main(String[] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class
JAVA TOKENS
Java program is basically a collection of classes. But it have a basic bulding blocks, these
basic buildings blocks in Java language which are constructed together to write a java program.
This basic bulding blocks are called Token.
Each and every smallest individual units in a Java program are known as C tokens.
Simply we can say that java program is also collection of tokens, comments and whitespaces.
In Java Programming tokens are of six types. They are,
3 Identifier -443 43
5 Special Symbol * @
6 Operators * ++
Keyword
Keywords are an special part of a language definition. Keywords are predefined, reserved words
used in programming that have special meanings to the compiler.
These meaning of the keywords has already been described to the java compiler.
These meaning cannot be changed.
Thus, the keywords cannot be used as variable names because that would try to change
the existing meaning of the keyword, which is not allowed.
Keywords are part of the syntax and they cannot be used as an identifier.
But one can change these words as identifiers by changing one or more letters to upper
case, However this will be a bad practice so we should avoid that.
Java language has reserved 50 words as keywords
Identifiers
Identifiers are the names of variables, methods, classes, packages and interfaces.Identifier must
follow some rules. Here are the rules:
All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or
an underscore.
They must not begin with a digit
After the first character, an identifier can have any combination of characters.
A Java keywords cannot be used as an identifier.
Identifiers in Java are case sensitive, foo and Foo are two different identifiers.
They can be any length
The following are legal variable names:
MyVariable
myvariable
MYVARIABLE
The following are not legal variable names:
My Variable // Contains a space
9pins // Begins with a digit
a+c // The plus sign is not an alphanumeric character
testing1-2-3 // The hyphen is not an alphanumeric character
O'Reilly // Apostrophe is not an alphanumeric character
classes and interfaces start with a leading uppercase, the second and subsequent words
are marked with a leading uppercase letters.
Examples: Employee,Area,Animal
public methods and instance variables starts with a leading lowercase letters.
Examples: area, addition
When more than one words are in a name, the scond and subsequent words are mark ed
with a leading uppercase letters.
Examples: areaCircle,businessName
Private and local variables use only lowercase combined with underscore.
Examples: volume,area_circle
Variables that represents constant values use all uppercase letters and underscore between
words
Examples: TOTAL_MARKS, GROSS_VALUE
Constants Or Literals
Literals in java are sequence of characters (digits, letters and other characters) that
represent constant values to be stored in variables. Java language specifies five major type of
literals.
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a
result. Operators are of many types and are considered in operator chapter
There are many types of operators in java which are given below:
Unary Operator,
Arithmetic Operator,
shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
JAVA STATEMENTS
Java methods are blocks of code that perform a task, and can be used by other parts of a
computer program, such as a declaration statement.
Statements in Java can be broadly classified into three categories:
Declaration statement
Expression statement
Control flow statement
CONSTANT
There are several values in the real world which will never change. A square will always have
four sides, PI to three decimal places will always be 3.142.
1. Integer Constants
2. Real Constants
3. Single Character Constants
4. String Constants
5. Backslash Character Constants
VARIABLES
Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. Variables are used to store information to be referenced and manipulated in a
computer program.
DATA TYPES
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java.
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
SCOPE OF VARIABLES
The Java programming language defines the following kinds of variables:
1. Instance Variables
2. Static Variables
3. Local Variables
SYMBOLIC CONSTANTS
Symbolic constants one declared for types there are not done in c & c++ where
symbolic constants one defined using the define statement.
Syntax : final type symbolicname= value;
Eg final float PI =3.14159;
final int STRENGTH =100;
For eg:- STRENTH = 200 is illegal
TYPE CASTING
When you assign value of one data type to another, the two types might not be
compatible with each other. If the data types are compatible, then Java will perform the
conversion automatically known as Automatic Type Conversion and if not then they need to be
casted or converted explicitly. For example, assigning an int value to a long variable.
Type casting is when you assign a value of one primitive data type to another type.In
Java, there are two types of casting:
ARITHMETIC EXPRESSIONS
An arithmetic expression evaluates to a single arithmetic value. A
character expression evaluates to a single value of type character. A logical or
relational expression evaluates to a single logical value.
EVALUATION OF EXPRESSION
Evaluate an expression represented by a String. Expression can contain parentheses, you
can assume parentheses are well-matched. For simplicity, you can assume only binary operations
allowed are +, -, *, and /. Arithmetic Expressions can be written in one of three forms:
Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4 .
Variable = expressions
Variable is any valid java variable name.
Ex:
x=a*b-c ;
y=b/a=h ;
MATHEMATICAL FUNCTIONS
Method Description
if-else
nested-if
if-else-if
switch-case
SIMPLE IF STATEMENT
if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
IF ELSE STATEMENT
The if statement alone tells us that if a condition is true it will execute a block of statements and
if the condition is false it won’t. But what if we want to do something else if the condition is
false. Here comes the else statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
NESTING IF ELSE STATEMENT
A nested if is an if statement that is the target of another if or else. Nested if statements means an
if statement inside an if statement. Yes, java allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.
THE EISELF LADDER
a user can decide among multiple options.The if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed.
THE SWITCH STATEMENT
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
THE DO STATEMENT
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
Following is the syntax of a do...while loop −
do {
// Statements
}while(Boolean_expression);
JUMPS IN LOOPS
jump: Java supports three jump statement: break, continue and return. These three statements
transfer control to other part of the program.
1. Break: In Java, break is majorly used for:
Terminate a sequence in a switch statement (discussed above).
To exit a loop.
Used as a “civilized” form of goto.
2. Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want
to continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The
continue statement performs such an action.
UNIT – 2
CLASS, OBJECTS AND METHODS
DEFINING A CLASS
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
FIELDS DECLARATION
A Java field is a variable inside a class. For instance, in a class representing an employee,
the Employee class might contain the following fields:
name
position
salary
hiredDate
METHODS DECLARATION
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
The return type : The data type of the value returned by the method or void if does not
return a value.
Method Name : the rules for field names apply to method names as well, but the convention
is a little different.
Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body : it is enclosed between braces. The code you need to be executed to perform
your intended operations.
CREATING OBJECTS
A class provides the blueprints for objects. So basically, an object is created from a class. In
Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
CONSTRUCTORS
A constructor initializes an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit return type.
Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Java allows two types of constructors namely −
No argument Constructors
Parameterized Constructors
METHODS OVERLOADING
Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters or both.
Overloading is related to compile-time (or static) polymorphism.
However, Overloading methods on return type are possible in cases where the data type of the
function being called is explicitly specified.
STATIC MEMBERS
We create a static method by using the keyword static. Static methods can access only static
fields, methods. To access static methods there is no need to instantiate the class, you can do it
just using the class name
NESTING OF METHODS
When a method in java calls another method in the same class, it is called Nesting of methods.
INHERITANCE
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Types of inheritance in java
There can be three types of inheritance in java: single, multilevel and hierarchical.
OVERRIDING METHODS
Overriding is a feature that allows a subclass or child class to provide a specific implementation
of a method that is already provided by one of its super-classes or parent classes. When a method
in a subclass has the same name, same parameters or signature and same return type(or sub-type)
as a method in its super-class, then the method in the subclass is said to override the method in
the super-class.
FINAL CLASSES
If you make any class as final, you cannot extend it.
FINALIZER METHODS
Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up activities
and minimize memory leaks.
Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up activities
and minimize memory leaks.
Syntax
protected void finalize() throws Throwable
Throw
Throwable - the Exception is raised by this method
Example 1
public class JavafinalizeExample1 {
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");
}
protected void finalize()
{
System.out.println("finalize method called");
} }
Output:
2018699554
end of garbage collection
finalize method called
VISIBILITY CONTROL
Java provides a number of access modifiers to set access levels for classes, variables, methods,
and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
ARRAYS
Java array is an object which contains elements of a similar data type. The elements of
an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Ex: student[5]
Creating an Arrays
You can create an array by using the new operator with the following syntax and it involves 3
steps.
1. Declaring the array
2. Creating memory locations
3. Putting values into the memory locations
Declaration of Variables
To use an array in a program,
1. must declare a variable
2. must specify the type of array the variable.
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Ex: int number[]; Float avg[];
a[1]=20;
a[2]=30;
//printing array
System.out.println("One dimensional array elements are");
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
}
}
Array Length
To find out how many elements an array has, use the length property:
Example
public class MyClass {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}
TWO DIMENSIONAL ARRAY
In Java, you can declare an array of arrays known as multidimensional array.
INT[][] a = new int[3][4];
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type int.
To initialize a 2d array:
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
class MultidimensionalArray {
public static void main(String[] args) {
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}
When you run the program, the output will be:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
STRINGS
String is a sequence of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’.
for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which
means it is constant and can cannot be changed once it has been created.
Creating a String
There are two ways to create a String in Java
1. String literal
2. Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
String str1 = "Welcome";
String str2 = "Welcome";
String Methods
Sr.No. Method & Description
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
STRINGBUFFER CLASS
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are
the important points about StringBuffer −
A string buffer is like a String, but can be modified.
It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
They are safe for use by multiple threads.
Every string buffer has a capacity.
Class Declaration
Following is the declaration for java.lang.StringBuffer class −
public final class StringBuffer extends Object implements Serializable, CharSequence
Class constructors
StringBuffer(): This constructs a string buffer with no characters in it and an
initial capacity of 16 characters.
StringBuffer(CharSequence seq):This constructs a string buffer that contains the
same characters as the specified CharSequence.
StringBuffer(int capacity): This constructs a string buffer with no characters in it
and the specified initial capacity.
Class methods
1. StringBuffer append(boolean b)
This method appends the string representation of the boolean argument to the sequence
2. setCharAt(n,x) – Modifies nth character to x.
3. insert(n,s2) – insert the string.
VECTORS
Java.util.Vector Class in Java
The Vector class implements a growable array of objects. Vectors basically falls in
legacy classes but now it is fully compatible with collections.
Vector implements a dynamic array that means it can grow or shrink as required. Like an
array, it contains components that can be accessed using an integer index
They are very similar to ArrayList but Vector is synchronised and have some legacy
method which collection framework does not contain.
It extends AbstractList and implements List interfaces.
Three ways to create vector class object:
Method 1:
Vector vec = new Vector();
Method2:
Syntax: Vector object= new Vector(int initialCapacity)
Method 3:
Syntax: Vector object= new vector(int initialcapacity, capacityIncrement)
Commonly used methods of Vector Class:
1. void addElement(Object element): It inserts the element at the end of the Vector.
2. int capacity(): This method returns the current capacity of the vector.
3. int size(): It returns the current size of the vector.
4. void setSize(int size): It changes the existing size with the specified size.
5. boolean contains(Object element): This method checks whether the specified element is
present in the Vector. If the element is been found it returns true else false.
6. boolean containsAll(Collection c): It returns true if all the elements of collection c are
present in the Vector.
7. Object elementAt(int index): It returns the element present at the specified location in
Vector.
8. Object firstElement(): It is used for getting the first element of the vector.
9. Object lastElement(): Returns the last element of the array.
10. Object get(int index): Returns the element at the specified index.
11. boolean isEmpty(): This method returns true if Vector doesn’t have any element.
12. boolean removeElement(Object element): Removes the specifed element from vector.
13. boolean removeAll(Collection c): It Removes all those elements from vector which are
present in the Collection c.
14. void setElementAt(Object element, int index): It updates the element of specifed index
with the given element.
Ex: Vector
import java.util.Iterator;
import java.util.Vector;
public class SimpleVectorExample {
public static void main(String[] args) {
//create a Vector object
Vector v = new Vector();
v.add("1");
v.add("2");
v.add("3");
System.out.println("Getting elements of Vector");
System.out.println(v.get(0));
System.out.println(v.get(1));
System.out.println(v.get(2));
}
}
Output would be
Getting elements of Vector
1
2
3
WRAPPER CLASSES
A Wrapper class is a class whose object wraps or contains a primitive data types. When
we create an object to a wrapper class, it contains a field and in this field, we can store a
primitive data types. In other words, we can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this
case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.
short short
Int Integer
long Long
float Float
More about string conversions will be covered in the Strings chapter of this tutorial.
String s = (String) 15; // compilation error
int i = (int) "25"; // compilation error
It is not possible to cast between numbers and strings. Instead, we have various methods for
doing conversion between numbers and strings.
short age = Short.parseShort("35");
int salary = Integer.parseInt("2400");
float height = Float.parseFloat("172.34");
double weight = Double.parseDouble("55.6");
The parse methods of the wrapper classes convert strings to primitive types.
Short age = Short.valueOf("35");
Integer salary = Integer.valueOf("2400");
Float height = Float.valueOf("172.34");
Double weight = Double.valueOf("55.6");
The valueOf() method returns the wrapper classes from primitive types.
int age = 17;
double weight = 55.3;
String v1 = String.valueOf(age);
String v2 = String.valueOf(weight);
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long,
float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known
as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
ENUMERATED TYPES
Enumerated means that something has a defined set of values it can hold. the values
are static and final, which really means they can't be changed. Java enums are type-safe. There is
no way to assign a value to the enum that doesn't fit with the defined values. For example, the
DayOfWeek enum cannot accept anything other than the days of the week that were defined. If
you try to assign a 1 to it, the code will not compile.
public enum DayOfWeek {
SUNDAY(0), MONDAY(1), TUESDAY(2),
WEDNESDAY(3), THURSDAY(4),
FRIDAY(5),
SATURDAY(6);
private int value;
private DayOfWeek(int value) {
this.value = value;
}
}
INTERFACES
Multiple Inheritance
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Defining interface
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the fields are
public, static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Extending Interface
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
Syntax:
Interface name2 extends name1
{
Body of the name
}
For example, if the Hockey interface extended both Sports and Event, it would be declared as −
Example
Interface ItemConstants
{
int code = 1001;
String name=”Fan”;
}
Interface ItemMethods
{
void display();
}
interface Item extends ItemConstants, ItemMethods
{
___
}
IMPLEMENTING INTERFACES
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
int pink=6;
public void choose(int color);
}
class selectimp implements selectcolor
{
public void choose(int color)
{
switch(color)
{
case blue:
System.out.println("The color selected is blue");
break;
case yellow:
System.out.println("The color selected is yellow");
break;
case pink:
System.out.println("The color selected is pink");
break;
}
}
public static void main(String aa[])
{
int a1,b1,c1;
a1=Integer.parseInt(aa[0]);
b1=Integer.parseInt(aa[1]);
c1=Integer.parseInt(aa[2]);
selectimp st=new selectimp();
st.choose(a1);
st.choose(b1);
st.choose(c1);
}}
UNIT – 3
PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here,
we will have the detailed learning of creating and using user-defined packages.
PACKAGE
NAME EXAMPLE CLASSES FUNCTIONALITY (PURPOSE)
FileInputStream,
FileOutputStream, FileReader,
FileWriter, RandomAccessFile, These classes are used in all I/O
BufferedReader, BufferedWriter operations including keyboard
java.io etc. input.
NAMING CONVENTIONS
Java Naming Conventions
Below are some naming conventions of java programming language. They must be
followed while developing software in java for good maintenance and readability of code. Java
uses CamelCase as a practice for writing names of methods, variables, classes, packages and
constants.
Camel case in Java Programming : It consists of compound words or phrases such that each
word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all with
capital.
Classes and Interfaces :
Class names should be nouns, in mixed case with the first letter of each internal word
capitalised. Interfaces name should also be capitalised just like class names.
Use whole words and must avoid acronyms and abbreviations.
interface Bicycle
class MountainBike implements Bicyle
interface Sport
class Football implements Sport
1. Methods :
o Methods should be verbs, in mixed case with the first letter lowercase and with
the first letter of each internal word capitalised.
Examples:
Examples:
com.sun.eng
com.apple.quicktime.v2
CREATING PACKAGES
While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Subpackages: Packages that are inside another package are the subpackages. These are
not imported by default, they have to imported explicitly. Also, members of a subpackage have
no access privileges, i.e., they are considered as different package for protected and default
access specifiers.
Example :
import java.util.*;
util is a subpackage created inside java package.
HIDING CLASSES
When we import a package within a program, only the classes declared as public in that package
will be made accessible within this program. In other words, the classes not declared as public in
that package will not be accessible within this program.
STATIC IMPORT
We can access the static members of a class directly without class name or any object.
For Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(),
but by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance
coding. But according to the programming experts, it will lead to confusion and not good for
programming.If there is no specific requirement then we should not go for static import.
class Geeks {
public static void main(String[] args)
{
System.out.println(Math.sqrt(4));
System.out.println(Math.pow(2, 2));
System.out.println(Math.abs(6.3));
}
}
Output:
2.0 4.0
6.3
MULTITHREADED PROGRAMMING
Java is a multithreaded programming language which means we can develop multi
threaded program using Java. A multi threaded program contains two or more parts that can run
concurrently and each part can handle different task at the same time making optimal use of the
available resources especially when your computer has multiple CPUs.
CREATING THREADS
There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.
Before we begin with the programs (code) of creating threads, let’s have a look at these methods
of Thread class. We have used few of these methods in the example below.
getName(): It is used for Obtaining a thread’s name
getPriority(): Obtain a thread’s priority
isAlive(): Determine if a thread is still running
join(): Wait for a thread to terminate
run(): Entry point for the thread
sleep(): suspend a thread for a period of time
start(): start a thread by calling its run() method
Output:
My thread is in running state.
Runnable
When we call start() function on Thread object, it’s state is changed to Runnable. The
control is given to Thread scheduler to finish it’s execution. Whether to run this thread instantly
or keep it in runnable thread pool before running, depends on the OS implementation of thread
scheduler.
Running
When thread is executing, it’s state is changed to Running. Thread scheduler picks one of
the thread from the runnable thread pool and change it’s state to Running. Then CPU starts
executing this thread. A thread can change state to Runnable, Dead or Blocked from running
state depends on time slicing, thread completion of run() method or waiting for some resources.
Blocked/Waiting
A thread can be waiting for other thread to finish using thread join or it can be waiting for
some resources to available. For example producer consumer problem or waiter notifier
implementation or IO resources, then it’s state is changed to Waiting. Once the thread wait state
is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool.
Dead
Once the thread finished executing, it’s state is changed to Dead and it’s considered to be
not alive. Above are the different states of thread. It’s good to know them and how thread
changes it’s state. That’s all for thread life cycle in java.
THREAD EXCEPTIONS
Exception handling provides a powerful mechanism for controlling complex programs
thathave many dynamic run-time characteristics. It is important to think oftry,throw, andcatchas
clean ways to handle errors and unusual boundary conditions in your program’s logic.Unlike
some other languages in which error return codes are used to indicate failure, Javauses
exceptions. Thus, when a method can fail, have it throw an exception. This is a cleanerway to
handle failure modes.
THREAD PRIORITY
All the thread instances the developer created have the same priority, which the process
will schedule fairly without worrying about the order. It is important for different threads to have
different priorities. Important threads should always have higher priority than less important
ones, while threads that need to run quietly as a Daemon may only need the lowest priority.
For example, the garbage collector thread just needs the lowest priority to execute, which
means it will not be executed before all other threads are scheduled to run. It is possible to
control the priority of the threads by using the Java APIs. The Thread.setPriority(...) method
serves this purpose.
The Thread class provides 3 constants value for the priority: MIN_PRIORITY = 1,
NORM_PRIORITY = 5, MAX_PRIORITY = 10The priority range of the thread should be
between the minimum and the maximum number. The following example shows how to alter the
order of the thread by changing its priority.
SYNCHRONIZATION
Multithreading introduces an asynchronous behavior to your programs, there must be a
way for you to enforce synchronicity when you need it. For example, if you want two threads to
communicate and share a complicated data structure, such as a linked list, you need some way to
ensure that they don’t conflict with each other. That is, you must prevent one thread from writing
data while another thread is in the middle of reading it. For this purpose, Java implements an
elegant twist on an age-old model of inter process synchronization: the monitor.
The monitor is a control mechanism first defined by C.A.R. Hoare. You can think of a
monitor as a very small box that can hold only one thread. Once a thread enters a monitor, all
other threads must wait until that thread exits the monitor. In this way, a monitor can be used to
protect a shared asset from being manipulated by more than one thread at a time. Most
multithreaded systems expose monitors as objects that your program must explicitly acquire and
manipulate. Java provides a cleaner solution.
There is no class “Monitor”; instead, each object has its own implicit monitor that is
automatically entered when one of the object’s synchronized methods is called. Once a thread is
inside a synchronized method, no other thread can call any other synchronized method on the
same object. This enables you to write very clear and concise multithreaded code, because
synchronization support is built into the language.
UNIT 4
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no commandline
arguments, since a will equal zero. It will survive the division if you provide a command-line
argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
before returning. The finally clause is optional. However, each try statement requires at least
one catch or a finally clause.
APPLET PROGRAMMING
Applets are small applications that are accessed on an Internet server, transported over
the Internet, automatically installed, and run as part of a web document. After an applet arrives
on the client, it has limited access to resources so that it can produce a graphical user interface
and run complex computations without introducing the risk of viruses or breaching data integrity.
Most real applications of Java are not text-based, console programs. Rather, they are
graphically oriented programs that rely upon Java’s Abstract Window Toolkit (AWT) or Swing
for interaction with the user. The Applet class, which provides the foundation for applets.The
Applet class is contained in the java.applet package.
*/
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}
/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}}
APPLET TAG
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
UNIT : 5
GRAPHICS PROGRAMMING
The AWT supports a rich assortment of graphics methods. All graphics are drawn
relative to a window. This can be the main window of an applet, a child window of an applet, or
a stand-alone application window. The origin of each window is at the top-left corner and is 0,0.
Coordinates are specified in pixels. All output to a window takes place through a graphics
context. Agraphics context is encapsulated by the Graphics class and is obtained in two ways:
• It is passed to an applet when one of its various methods, such as paint( ) or update( ),
is called.
• It is returned by the getGraphics( ) method of Component.
LINE GRAPHS
A line chart or line graph displays information as a series of data points (markers)
connected by straight line segments. Line Chart shows how data changes at equal time
frequency.Line Chart from a given set of business data.
Business Data
The following example draws a line chart to show a trend of number of schools opened in
different years starting from 1970.
Given data is as follows −
Year Number OF Schools
1970 15
1980 30
1990 60
2000 120
2013 240
2014 300
Like a while statement, except that it tests the condition at the end of the loop body.
USING STREAMS
The following three standard streams,
Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented as System.in.
Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
System.out.
Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented as
System.err.
FileInputStream
public void close() throws IOException{}
protected void finalize()throws IOException {}
public int read(int r)throws IOException{}
public int read(byte[] r) throws IOException{}
public int available() throws IOException{}
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a
file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
public void close() throws IOException{}
protected void finalize()throws IOException {}
public void write(int w)throws IOException{}
public void write(byte[] w)
I/O EXCEPTIONS
The java.io.Exceptions provides for system input and output through data streams, serialization
and the file system.
CharConversionException
1
This is a base class for character conversion exceptions.
EOFException
2 These are signals that an end of file or end of stream has been reached unexpectedly
during input.
FileNotFoundException
3 These are the signals that an attempt to open the file denoted by a specified pathname
has failed.
InterruptedIOException
4
This is signals that an I/O operation has been interrupted.
InvalidClassException
5 This is thrown when the Serialization runtime detects one of the following problems
with a Class.
InvalidObjectException
6
This indicates that one or more deserialized objects failed validation tests.
IOException
7
These are the signals that an I/O exception of some sort has occurred.
NotActiveException
8
This is thrown when serialization or deserialization is not active.
CREATION OF FILES
The java.io.File class can be used to create a new File in Java. When we initialize File
object, we provide the file name and then we can call createNewFile() method to create new file
in Java.
File createNewFile() method returns true if new file is created and false if file already
exists. This method also throws java.io.IOException when it’s not able to create the file. The
files created is empty and of zero bytes.
When we create the File object by passing the file name, it can be with absolute path, or
we can only provide the file name or we can provide the relative path.
This example demonstrates the way of creating a new file by using File() constructor and
file.createNewFile() method of File class.
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("C:/myfile.txt");
if(file.createNewFile())System.out.println("Success!");
READING/WRITING BYTES
Byte Streams are used to read or write byte data with files. This is different from before in the
way they treat the data. Here you work with raw bytes, which could be characters, image data,
unicode data (which takes 2 bytes to represent a character), etc.
In this section we'll take a look at the most commonly used classes. All of these classes are
defined under java.io package.
moving the cursor we do the read write operations. If end-of-file is reached before the desired
number of byte has been read than EOFException is thrown. It is a type of IOException.
Constructor Description
Creates a random access file stream to read from, and
RandomAccessFile(File file, String
optionally to write to, the file specified by the File
mode)
argument.
RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.
Modifier
Method Method
and Type
It closes this random access file stream and releases any system
void close()
resources associated with the stream.
FileChannel getChannel() It returns the unique FileChannel object associated with this file.
//Writing to Console
System.out.println(\"\\nCode Number : \" + codeNumber);
System.out.println(\"Item cost : \" + itemCost);
System.out.println(\"Total Items : \" + totalItems);
System.out.println(\"Total Cost : \" + totalCost);
}
}