0% found this document useful (0 votes)
5 views77 pages

Java

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views77 pages

Java

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

JAVA PROGRAMMING

PARVATHY’S ARTS AND SCIENCE COLLEGE, DINDIGUL.


DEPARTMENT OF COMPUTER SCIENCE
JAVA PROGRAMMING ( SCAJC31 )
II BCA (III SEM) – (2018 -2021)

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.

Prepared by Mrs.R.Padma Page 1


JAVA PROGRAMMING

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.

Prepared by Mrs.R.Padma Page 2


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 3


JAVA PROGRAMMING

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.

Prepared by Mrs.R.Padma Page 4


JAVA PROGRAMMING

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.

Prepared by Mrs.R.Padma Page 5


JAVA PROGRAMMING

Multithreaded and Interactive


Java was designed to meet the real-world requirement of creating interactive, networked
programs.Multithreading means handling multiple tasks simultaneously. It supports
multithreaded programs, which allows you to write programs that do many things
simultaneously. For this feature, we need not wait for the application to finish one task before
beginning another. For example, we can listen to any song while doing any program at the same
time we can download any file from the internet.so this is an example of multi threading and an
interactive performance.
High Performance
Java performance is impressive for an interpreted language. Java allows us for the creation of
cross-platform programs by compiling into an intermediate representation called Java
bytecode.Java is faster than c/c++ because in Java bytecode can be executed on any system that
implements the Java Virtual Machine(JVM). Java architecture is designed to reduce overheads
during runtime.
Dynamic and Extensible
Java is dynamic language because it is capable of linking in new class libraries, methods, and
objects.
it is extensible because it supports native methods(methods which are written in another
language like c/c++).Native methods are linked dynamically at runtime.

HOW JAVA DIFFERS FROM C AND C++


Java and C
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.

Prepared by Mrs.R.Padma Page 6


JAVA PROGRAMMING

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.

Java and C++


Java is a true object-oriented language while C++ is basically C with object-oriented extension.
That is what exactly the increment operator ++ indicates. C++ has maintained backward
compatibility with C. Is is, therefore, possible to write an old style C program and run it
successfully under C++. Java appears to be similar to C++ when we consider only the
“extensions” part of C++. However, some object -oriented features of C++ make the C++ code
extremely difficult to follow and maintain.
Listed below are some major C++ features that were intentionally omitted from Java or
significantly modified.
1. Java does not support operator overloading.
2. Java does not have template classes as in C++.
3. Java does not support multiple inheritances of classes. This is accomplished using a new
feature called “Interface”.
4. Java does not support global variables. Every variable and method is declared within
classes and forms part of that class.
5. Java does not use pointers.
6. Java has replaced the destructor function with a finalize() function.
7. There are no header files in Java.

DIFFERENCES AMONG C, C++ AND JAVA PROGRAMMING LANGUAGES: C VS


C++ VS JAVA
The purpose of learning a programming language is to become a better programmer i.e. to
become more effective at designing and implementing new systems and at maintaining old ones.

Prepared by Mrs.R.Padma Page 7


JAVA 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

Prepared by Mrs.R.Padma Page 8


JAVA PROGRAMMING

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

JAVA AND INTERNET


 Java is strongly associated with the internet because of the first application program is
written in Java was hot Java.
 Web browsers to run applets on the internet.
 Internet users can use Java to create applet programs & run then locally using a Java-
enabled browser such as hot Java.
 Java applets have made the internet a true extension of the storage system of the local
computer.

JAVA AND WORLD WIDE WEB


World wide web is a collection of information stored on internet computers.
1. World wide web is an information retrieval system designed to be used in the
internet’s distributed environment.
2. World wide web contains web pages that provide both information and controls.
3. Web pages contain HTML tags that enable us to find retrieve, manipulate and
display documents world wide.
4. Before Java, the world wide web was limited to the display of still images &
texts.
5. With the help of Java WWW is capable of supporting animation graphics, games
and wide rage special effects.
 Java communicates with a web page through a special tag called .
 Java user sends a request for an HTML document to the remote computers net browser.

Prepared by Mrs.R.Padma Page 9


JAVA PROGRAMMING

 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

HARDWARE AND SOFTWARE REQUIREMENTS


Hardware Requirement for Java
Minimum hardware requirement to download Java on your Windows operating system as
follows:
 Minimum Windows 95 software
 IBM-compatible 486 system

Prepared by Mrs.R.Padma Page 10


JAVA PROGRAMMING

 Hard Drive and Minimum of 8 MB memory


 A CD-ROM drive
 Mouse, keyboard and sound card, if required
Software requirement for Java
Nowadays, Java is supported by almost every operating systems. whether it is a Windows,
Macintosh and Unix all supports the Java application development. So you can download any of
the operating system on your personal computer. Here are the minimum requirement.
 Operating System
 Java SDK or JRE 1.6 or higher
 Java Servlet Container (Free Servlet Container available)
 Supported Database and library that supports the database connection with Java.

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

Prepared by Mrs.R.Padma Page 11


JAVA PROGRAMMING

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.

WHAT IS JVM (JAVA VIRTUAL MACHINE)


The Java language is a high-level language. All language compilers translate source code
into machine code. Java compiler does the same thing.You save a Java program in a .java file
and compile it into a .class file. The .class file (also called bytecode). Output of a Java compiler
is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions
designed to be executed by the Java run-time system, which is called the Java Virtual Machine
(JVM).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 JVM executes our code along with the
code in the library.
To execute a Java program is to run the program’s bytecode or .class file. You can
execute the bytecode on any platform with a JVM, which is an interpreter . the original JVM
was designed as an interpreter for bytecode. It translates the individual instructions in the
bytecode into the target machine language code one at a time rather than the whole program as a
single unit. Each step is executed immediately after it is translated.

OVERVIEW OF JAVA LANGUAGE


Where Java is used?
There are many devices where java is currently used. Some of them are as follows:
 Desktop Applications
 Web Applications
 Mobile
 Embedded System
 Robotics
 Games etc.
Types of Java Applications
 Application programs
Application programs are stand-alone programs that are written to carry out certain tasks
on local computer such as solving equations, reading and writing files etc.

Prepared by Mrs.R.Padma Page 12


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 13


JAVA PROGRAMMING

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

Output: This is my first program in java

Prepared by Mrs.R.Padma Page 14


JAVA PROGRAMMING

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,

No Token Type Example 1 Example 2

1 Keyword int for

2 Constants height sum

3 Identifier -443 43

4 String "Hello" "atnyla"

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

Prepared by Mrs.R.Padma Page 15


JAVA PROGRAMMING

abstract continue for new switch


assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

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

Prepared by Mrs.R.Padma Page 16


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 17


JAVA PROGRAMMING

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

IMPLEMENTING A JAVA PROGRAM


Implementation of a Java application program involves a series of steps. They include,
 Creating the program
 Compiling the program
 Running the program

JAVA VIRTUAL MACHINE


Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM).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 JVM executes our code along with the code in the library.

COMMAND LINE ARGUMENTS


 Command Line Arguments can be used to specify configuration information while
launching your application.
 There is no restriction on the number of java command line arguments.You can specify
any number of arguments
 Information is passed as Strings.
 They are captured into the String args of your main method

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.

Prepared by Mrs.R.Padma Page 18


JAVA PROGRAMMING

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.

DECLARATION OF VARIABLES & GIVING VALUES TO VARIABLES


Variables are used to represent values that may be changed in the program. In Java, all
variables must be declared before they can be used. The basic form of a variable declaration is
shown here:
type identifier [ = value][, identifier [= value] ...] ;
 To compile : javac IntExample1.java
 To Run : java IntExample1
Example :
// A Java program to demonstrate int data type
class IntExample1 {
public static void main(String args[])
{

Prepared by Mrs.R.Padma Page 19


JAVA PROGRAMMING

int age; // Declaration of variable age


age = 20; // initialization of the variable age
System.out.println(age);
}
}
Output :
20
press any key to continue ...

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:

Prepared by Mrs.R.Padma Page 20


JAVA PROGRAMMING

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

OPERATORS AND EXPRESSIONS


1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. conditional operator

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 ;

Prepared by Mrs.R.Padma Page 21


JAVA PROGRAMMING

PRECEDENCE OF ARITHMETIC OPERATORS & OPERATOR PRECEDENCE AND


ASSOCIATIVITY
Category Operator Associativity
Postfix >() [] . (dot operator) Left toright
Unary >++ - - ! ~ Right to left
Multiplicative >* / Left to right
Additive >+ - Left to right
Shift >>> >>> << Left to right
Relational >> >= < <= Left to right
Equality >== != Left to right
Bitwise AND >& Left to right
Bitwise XOR >^ Left to right
Bitwise OR >| Left to right
Logical AND >&& Left to right
Logical OR >|| Left to right
Conditional ?: Right to left
Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left

MATHEMATICAL FUNCTIONS

Method Description

Math.abs() It will return the Absolute value of the given value.

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.

Math.sqrt() It is used to return the square root of a number.

Math.cbrt() It is used to return the cube root of a number.

Prepared by Mrs.R.Padma Page 22


JAVA PROGRAMMING

DECISION MAKING AND BRANCHING


DECISION MAKING WITH IF STATEMENT
Java’s Selection statements:
 if

 if-else

 nested-if

 if-else-if

 switch-case

 jump – break, continue, return

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.

Prepared by Mrs.R.Padma Page 23


JAVA PROGRAMMING

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

THE FOR STATEMENT


A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to be executed a specific number of times. A for loop is useful when you know how many
times a task is to be repeated.
Syntax
The syntax of a for loop is −
for(initialization; Boolean_expression; update) {
// Statements
}

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

Prepared by Mrs.R.Padma Page 24


JAVA PROGRAMMING

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

The corresponding Java class could be defined like this:


public class Employee {
String name ;
String position ;
int salary ;
Date hiredDate;
}

Prepared by Mrs.R.Padma Page 25


JAVA PROGRAMMING

Field Declaration Syntax


[access_modifier] [static] [final] type name [= initial value] ;

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.

Prepared by Mrs.R.Padma Page 26


JAVA PROGRAMMING

ACCESSING CLASS MEMBERS


Instance variables and methods are accessed via created objects. To access an instance variable,
following is the fully qualified path −

/* First create an object */


ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

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

Prepared by Mrs.R.Padma Page 27


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 28


JAVA PROGRAMMING

{
//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 VARIABLES AND METHODS


 When final keyword is used with a variable of primitive data types (int, float, .. etc),
value of the variable cannot be changed.
 final variables are nothing but constants. We cannot change the value of a final variable
once it is initialized.
 For example following program gives error because i is final.
public class Test {
public static void main(String args[]) {
final int i = 10;
i = 30; // Error because i is final.
}
}

Prepared by Mrs.R.Padma Page 29


JAVA PROGRAMMING

Java final method


 If you make any method as final, you cannot override it. A final method cannot be
overridden. Which means even though a sub class can call the final method of parent
class without any issues but it cannot override it.
Example:
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
} Output:Compile Time Error

FINAL CLASSES
If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

Prepared by Mrs.R.Padma Page 30


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 31


JAVA PROGRAMMING

ABSTRACT METHODS AND CLASSES


An abstract class is a class that is declared abstract —it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract
class is subclassed, the subclass usually provides implementations for all of the abstract
methods in its parent class.
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}

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]

ONE - DIMENSIONAL ARRAYS


An array is a collection of elements of one specific type in a horizontal fashion. Anything
having one-dimension means that there is only one parameter to deal with. One dimension means
it has only one value per location or index.

Prepared by Mrs.R.Padma Page 32


JAVA PROGRAMMING

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[];

CREATION OF ARRAYS: CREATING MEMORY LOCATIONS


Syntax : arrayRefVar = new dataType[arraySize];
The above statement does two things −
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the variable arrayRefVar.
Initialization of Arrays
Example,
Here is a complete example showing how to create, initialize, and process arrays.
Example
class OnedimensionalStandard
{
public static void main(String args[])
{
int[] a=new int[3];//declaration
a[0]=10;//initialization

Prepared by Mrs.R.Padma Page 33


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 34


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 35


JAVA PROGRAMMING

Using New Keyword


As we saw above that when we tried to assign the same string object to two different literals,
compiler only created one object and made both of the literals to point the same object. To
overcome that approach we can create strings like this:
String str1 = new String("Welcome");
String str2 = new String("Welcome");
A Simple Java String Example
public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = "Beginnersbook";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);

//creating another java string str3 by using new keyword


String str3 = new String("Java String Example");

//Displaying all the three strings


System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Output:
Beginnersbook
hello
Java String Example

Prepared by Mrs.R.Padma Page 36


JAVA PROGRAMMING

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.

3 int compareTo(String anotherString)


Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)


Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)


Concatenates the specified string to the end of this string.

6 boolean contentEquals(StringBuffer sb)


Returns true if and only if this String represents the same sequence of
characters as the specified StringBuffer.

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.

Prepared by Mrs.R.Padma Page 37


JAVA PROGRAMMING

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)

Prepared by Mrs.R.Padma Page 38


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 39


JAVA PROGRAMMING

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.

Primitive Data types and their Corresponding Wrapper class


Primitive Type Wrapper class
boolean Boolean
Byte Byte

Prepared by Mrs.R.Padma Page 40


JAVA PROGRAMMING

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.

Prepared by Mrs.R.Padma Page 41


JAVA PROGRAMMING

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.

Wrapper class Example: Wrapper to Primitive


public class WrapperExample2{
public static void main(String args[]){
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
Output: 333

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

Prepared by Mrs.R.Padma Page 42


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 43


JAVA PROGRAMMING

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.

Prepared by Mrs.R.Padma Page 44


JAVA PROGRAMMING

A class uses the implements keyword to implement an interface. The implements


keyword appears in the class declaration following the extends portion of the declaration.
Syntax:
class ClassName implements interfacename
{
Body of class
}

class ClassName extends superclass implements interface1, interface2


{
Body of class
}
Example:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
/* File name : MammalInt.java */
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}

Prepared by Mrs.R.Padma Page 45


JAVA PROGRAMMING

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Output
Mammal eats Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed −
 Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
 The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
 An implementation class itself can be abstract and if so, interface methods need not be
implemented.
When implementation interfaces, there are several rules −
 A class can implement more than one interface at a time.
 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another
class.

ACCESSING INTERFACE VARIABLES


The variables of an interface are always declared as "final". Final variables are those
variables, whose values are constants and cannot be changed. The class that implements the
interface can use the variables as declared in the interface and cannot modify or changed the
value of the variable.
interface selectcolor
{
int blue=4;
int yellow=5;

Prepared by Mrs.R.Padma Page 46


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 47


JAVA PROGRAMMING

Output: javac selectimp.java


Java selectimp 4 5 6
The color selected is blue
The color selected is yellow
The color selected is pink

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.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

JAVA API PACKAGES

PACKAGE
NAME EXAMPLE CLASSES FUNCTIONALITY (PURPOSE)

These classes are indispensable for


every Java program. For this
reason, even if this package is not
System, String, Object, Thread, imported, JVM automatically
java.lang Exception etc. imports.

java.util These are called as utility

Prepared by Mrs.R.Padma Page 48


JAVA PROGRAMMING

(service) classes and are used


very frequently in coding.

FileInputStream,
FileOutputStream, FileReader,
FileWriter, RandomAccessFile, These classes are used in all I/O
BufferedReader, BufferedWriter operations including keyboard
java.io etc. input.

URL, ServerSocket, Socket, Useful for writing socket


DatagramPacket, programming (LAN
java.net DatagramSocket etc. communication).

Required for developing applets


AppletContext, Applet, that participate on client-side in
java.applet AudioStub, AudioClip etc Internet (Web) programming.

Button, Choice, TextField, Essential for developing GUI


java.awt Frame, List, Checkbox etc. applications.

MouseListener, ActionListener, Without these classes, it is


ActionEvent, WindowAdapter impossible to handle events
java.awt.event etc. generated by GUI components

DriverManager, Statement, Required for database access in


java.sql Connection, ResultSet etc JDBC applications.

Table: Predefined Packages Java Java API

USING SYSTEM PACKAGES


Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

Prepared by Mrs.R.Padma Page 49


JAVA PROGRAMMING

A Package can be defined as a grouping of related types (classes, interfaces,


enumerations and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −
 java.lang − bundles the fundamental classes
 java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.

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:

Prepared by Mrs.R.Padma Page 50


JAVA PROGRAMMING

void changeGear(int newValue);


void speedUp(int increment);
void applyBrakes(int decrement);
2. Variables : Variable names should be short yet meaningful.
o Should not start with underscore(‘_’) or dollar sign ‘$’ characters.
o Should be mnemonic i.e, designed to indicate to the casual observer the intent of
its use.
o One-character variable names should be avoided except for temporary
variables.
o Common names for temporary variables are i, j, k, m, and n for integers; c, d, and
e for characters.
Examples:
// variables for MountainBike class
int speed = 0;
int gear = 1;
3. Constant variables:
o Should be all uppercase with words separated by underscores (“_”).
o There are various constants used in predefined classes like Float, Long, String etc.
Examples:
static final int MIN_WIDTH = 4;

// Some Constant variables used in predefined Float class


public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
public static final float NaN = 0.0f / 0.0f;
4. Packages:
o The prefix of a unique package name is always written in all-lowercase ASCII
letters and should be one of the top-level domain names, like com, edu, gov, mil,
net, org.
o Subsequent components of the package name vary according to an organisation’s
own internal naming conventions.

Prepared by Mrs.R.Padma Page 51


JAVA PROGRAMMING

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.

ACCESSING A PACKAGE & USING A PACKAGE


There are three ways to access the package from outside the package:
 import package.*;
 import package.classname;
 fully qualified name.
You can use the import statement when there are many references to a particular package. The
same approach can be used to access the user-defined packages as well. The import statement
can be used to search a list of packages for a particular class. The general form of import
statement for searching a class is:
import package1 [.package2] [.package3].classname;
Here, package1 is the name of the top-level package. package2 is the name of the package that is
inside the 1st package i.e. package1 and so on. Programmers can use any number of packages in
the package hierarchy. In the end, the explicitly class name is specified.

ADDING A CLASS TO A PACKAGE


We can add more classes to a created package by using package name at the top of the
program and saving it in the package directory. We need a new java file to define a public class,
otherwise we can add the new class to an existing .java file and recompile it.

Prepared by Mrs.R.Padma Page 52


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 53


JAVA PROGRAMMING

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

EXTENDING THE THREAD CLASS


Example 1:
class MultithreadingDemo extends Thread{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}

Prepared by Mrs.R.Padma Page 54


JAVA PROGRAMMING

Output:
My thread is in running state.

STOPPING AND BLOCKING A THREAD


Use of stop() MethodThe stop() method kills the thread on execution.

LIFE CYCLE OF A THREAD


New
When we create a new Thread object using new operator, thread state is New Thread. At
this point, thread is not alive and it’s a state internal to Java programming.

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.

Prepared by Mrs.R.Padma Page 55


JAVA PROGRAMMING

USING THREAD METHODS


1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.


3) static void sleep() It sleeps a thread for the specified amount of time.
static
4) currentThread() It returns a reference to the currently executing thread object.
Thread
5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.


10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

It causes the currently executing thread object to pause and allow


12) static void yield()
other threads to execute temporarily.
13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.


15) void stop() It is used to stop the thread.

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

Prepared by Mrs.R.Padma Page 56


JAVA PROGRAMMING

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.

Prepared by Mrs.R.Padma Page 57


JAVA PROGRAMMING

IMPLEMENTING THE RUNNABLE INTERFACE


The easiest way to create a thread is to create a class that implements the Runnable
interface.Runnable abstracts a unit of executable code. You can construct a thread on any object
that implements Runnable. To implement Runnable, a class need only implement a single
method called run( ), which is declared like this:
 public void run( )
After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will use
is shown here:
 Thread(Runnable threadOb, String threadName)
 void start( )

UNIT 4

MANAGING ERRORS AND EXCEPTIONS


Exception handling is one of the most important feature of java programming that allows
us to handle the runtime errors caused by exceptions.
TYPES OF ERRORS
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
EXCEPTIONS
An Exception is an unwanted event that interrupts the normal flow of the program. When
an exception occurs program execution gets terminated.

SYNTAX OF EXCEPTIONS HANDLING CODE


Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors

Prepared by Mrs.R.Padma Page 58


JAVA PROGRAMMING

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

MULTIPLE CATCH STATEMENTS


Sometimes, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different type
of exception. When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues
after the try/catch block. The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);

Prepared by Mrs.R.Padma Page 59


JAVA PROGRAMMING

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

USING FINALLY STATEMENT


finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block. The finally block will execute
whether or not an exception is thrown. If an exception is thrown, the finally block will execute
even if no catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just before
the method returns. This can be useful for closing file handles and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing of them

Prepared by Mrs.R.Padma Page 60


JAVA PROGRAMMING

before returning. The finally clause is optional. However, each try statement requires at least
one catch or a finally clause.

THROWING OUR OWN EXCEPTIONS


To create your own exception types to handle situations specific to your applications.
This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of
Throwable). Your subclasses don’t need to actually implement anything—it is their existence in
the type system that allows you to use them as exceptions.
Method & Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed
stack trace. This object can be rethrown. Throwable getCause( ) Returns the exception that
underlies the current exception. If there is no underlying exception, null
is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.

USING EXCEPTIONS FOR DEBUGGING


Exception handling provides a powerful mechanism for controlling complex programs
that have many dynamic run-time characteristics. It is important to think of try, throw, and
catch as 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 cleaner
way to handle failure modes. One last point: Java’s exception-handling statements should not be
considered a general mechanism for nonlocal branching.

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

Prepared by Mrs.R.Padma Page 61


JAVA PROGRAMMING

for interaction with the user. The Applet class, which provides the foundation for applets.The
Applet class is contained in the java.applet package.

HOW APPLETS DIFFER FROM APPLICATIONS


There are two varieties of applets. The first are those based directly on the Applet class
described in this chapter. These applets use the Abstract Window Toolkit (AWT) to provide the
graphic user interface (or use no GUI at all). This style of applet has been available since Java
was first created. The second type of applets are those based on the Swing class JApplet. Swing
applets use the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use
user interface than does the AWT.

PREPARING TO WRITE APPLETS


To use an applet, it is specified in an HTMLfile. One way to do this is by using the
APPLET tag. (The OBJECT tag can also be used, but Sun currently recommends the APPLET
tag).
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/

BUILDING APPLET CODE


Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are
defined by Applet. AWT-based applets (such as those discussed in this chapter) will also
override the paint( ) method, which is defined by the AWT Component class. This method is
called when the applet’s output must be redisplayed.
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>

Prepared by Mrs.R.Padma Page 62


JAVA PROGRAMMING

*/
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 LIFE CYCLE


 Applet is initialized.
 Applet is started.
 Applet is painted.
 Applet is stopped.
 Applet is destroyed

Prepared by Mrs.R.Padma Page 63


JAVA PROGRAMMING

CREATING AN EXECUTABLE APPLET


import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
} }
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

DESIGNING A WEB PAGE


Java applet are programs that reside on web page. A web page is basically made up of
text and HTML tags that can be interpreted by a web browser or an applet viewer. Java source
code, it can be prepared using any ASCII text editor.
A web page is also called HTML page or HTML document. A Web pages are stored
using a file extension .html such as my Applet.html. Such files are referred to as HTML files.
HTML files should be stored in the same directory as the compiled code of the applets.
A web page is marked by an opening HTML tag <HTML> and closing HTML tag </HTML>
and is divided into the following three major parts:
1. Comment Section
2. Head Section
3. Body Section

APPLET TAG
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/

Prepared by Mrs.R.Padma Page 64


JAVA PROGRAMMING

ADDING APPLET TO HTML FILE


The APPLET tag be used to start an applet from both an HTML document and from an
applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate
window, while web browsers will allow many applets on a single page.

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

RUNNING THE APPLET


To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Prepared by Mrs.R.Padma Page 65


JAVA PROGRAMMING

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.

THE GRAPHICS CLASS


The Graphics class defines a number of drawing functions. Each shape can be drawn
edge-only or filled. Objects are drawn and filled in the currently selected graphics color, which
is black by default. When a graphics object is drawn that exceeds the dimensions of the
window, output is automatically clipped.

LINES AND RECTANGLES


Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
 void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX,startY and ends
at endX,endY.
 g.drawLine(40, 25, 250, 180);
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
They are shown here:
 void drawRect(int top, int left, int width, int height)
 void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified
by width and height.

Prepared by Mrs.R.Padma Page 66


JAVA PROGRAMMING

 g.drawRect(10, 10, 60, 50);


 g.fillRect(100, 10, 60, 50);
 g.drawRoundRect(190, 10, 60, 50, 15, 15);
 g.fillRoundRect(70, 90, 140, 100, 30, 40);

CIRCLES AND ELLIPSES, DRAWING ARCS


Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods are
shown here:
 void drawOval(int top, int left, int width, int height)
 void fillOval(int top, int left, int width, int height)
 g.drawOval(10, 10, 50, 50);
 g.fillOval(100, 10, 75, 50);
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
 void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
 void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
 g.drawArc(10, 40, 70, 70, 0, 75);
 g.fillArc(100, 40, 70, 70, 0, 75);
DRAWING POLYGONS
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),
shown here:
 void drawPolygon(int x[ ], int y[ ], int numPoints)
 void fillPolygon(int x[ ], int y[ ], int numPoints)
 int xpoints[] = {30, 200, 30, 200, 30};
 int ypoints[] = {30, 30, 200, 200, 30};

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.

Prepared by Mrs.R.Padma Page 67


JAVA PROGRAMMING

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

USING CONTROL LOOPS IN APPLETS


There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.Programming languages provide various
control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming languages.
Java programming language provides the following types of loop to handle looping
requirements.

Sr.No. Loop & Description


1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 do...while loop

Prepared by Mrs.R.Padma Page 68


JAVA PROGRAMMING

Like a while statement, except that it tests the condition at the end of the loop body.

DRAWING BAR CHARTS


This is a Java program to draw a bar chart for the table given below which shows annual
result analysis of a school from period 2001-2005.these values may be placed in a HTML file as
<param> attributes and then used in Applet for dislaying bar-chart.

Year 2001 2002 2003 2004 2005


Result % 80 90 100 100 98

MANAGING INPUT/OUTPUT FILES IN JAVA


The File class is Java’s representation of a file or directory path name. Because file and
directory names have different formats on different platforms, a simple string is not adequate to
name them.
The File class contains several methods for working with the path name, deleting and
renaming files, creating new directories, listing the contents of a directory, and determining
several common attributes of files and directories.

CONCEPT OF STREAMS & STREAM CLASSES


A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one.

BYTE STREAM CLASSES


Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file.

Prepared by Mrs.R.Padma Page 69


JAVA PROGRAMMING

CHARACTER STREAM CLASSES


In Java, characters are stored using Unicode conventions (Refer this for details). Character
stream automatically allows us to read/write data character by character. For example FileReader
and FileWriter are character streams used to read from source and write to destination.

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.

OTHER USEFUL I/O CLASSES


Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing
java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

USING THE FILE CLASS


The two important streams are FileInputStream and FileOutputStream

Prepared by Mrs.R.Padma Page 70


JAVA PROGRAMMING

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.

Sr.No. Interface & Description

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.

Prepared by Mrs.R.Padma Page 71


JAVA PROGRAMMING

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

Prepared by Mrs.R.Padma Page 72


JAVA PROGRAMMING

else System.out.println ("Error, file already exists.");


}
catch(IOException ioe) {
ioe.printStackTrace();
} }}

READING / WRITING CHARACTERS


Here are some classes you should know that can be used to read character data:
 Reader: An abstract class to read a character stream.
 InputStreamReader: Class used to read the byte stream and converts to character stream.
 FileReader: A class to read the characters from a file.
 BufferedReader: This is a wrapper over the Reader class that supports buffering
capabilities. In many cases this is most preferable class to read data because more data
can been read from the file in one read() call, reducing the number of actual I/O
operations with file system.
And here are some classes you can use to write character data to a file:
 Writer: This is an abstract class to write the character streams.
 OutputStreamWriter: This class is used to write character streams and also convert them
to byte streams.
 FileWriter: A class to actually write characters to the file.
 BufferedWriter: This is a wrapper over the Writer class, which also supports buffering
capabilities. This is most preferable class to write data to a file since more data can be
written to the file in one write() call. And like the BufferedReader, this reduces the
number of total I/O operations with file system.

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.

Prepared by Mrs.R.Padma Page 73


JAVA PROGRAMMING

Here are the classes used to read the byte data:


 InputStream: An abstract class to read the byte streams.
 FileInputStream: A class to simply read bytes from a file.
 BufferedInputStream: This is a wrapper over InputStream that supports buffering
capabilities. As we saw in the character streams, this is a more efficient method than
FileInputStream.
And here are the classes used to write the byte data:
 OutputStream: An abstract class to write byte streams.
 FileOutputStream: A class to write raw bytes to the file.
 ByteOutputStream: This class is a wrapper over OutputStream to support buffering
capabilities. And again, as we saw in the character streams, this is a more efficient
method than FileOutputStream thanks to the buffering.

HANDLING PRIMITIVE DATA TYPES


Reading Writing Primitive Data Types
The basic reading and writing streams provide read/write methods that can only be used
for reading/writing bytes or characters. If we want to read/write the primitive data types such as
integers and doubles, we can use filter classes as wrappers on existing reading and writing
streams to filter data in the original stream.
The two filter classes used for creating “data streams” for handling primitive types are
DatalnputStream and DataOutputStream.

CONCATENATING AND BUFFERING FILES


The SequenceInputStream creates a single input stream from multiple input sources. This
example program, Concatenate, uses SequenceInputStream to implement a concatenation utility
that sequentially concatenates files together in the order they are listed on the command line.

RANDOM ACCESS FILES


This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called file pointer, by

Prepared by Mrs.R.Padma Page 74


JAVA PROGRAMMING

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.

int readInt() It reads a signed 32-bit integer from this file.


String readUTF() It reads in a string from this file.
seek(long It sets the file-pointer offset, measured from the beginning of this file,
void
pos) at which the next read or write occurs.

INTERACTIVE INPUT AND OUTPUT


Program of Inventory Management
import java.io.*;
import java.util.*;
class Inventory
{
static DataInputStream din = new DataInputStream(System.in);
static StringTokenizer st;
public static void main(String[] args) throws IOException
{

Prepared by Mrs.R.Padma Page 75


JAVA PROGRAMMING

DataOutputStream dos = new DataOutputStream(


new FileOutputStream(\"Invent.txt\"));

//Reading from the console


System.out.print(\"Enter code number : \");
System.out.flush();
st = new StringTokenizer(din.readLine());
int code = Integer.parseInt(st.nextToken());

System.out.print(\"Enter Item : \");


System.out.flush();
st =new StringTokenizer(din.readLine());
int item = Integer.parseInt(st.nextToken());

System.out.print(\"Enter Cost of Item : \");


System.out.flush();
st =new StringTokenizer(din.readLine());
double cost = new Double(st.nextToken()).doubleValue();

//Writing to the file Invent.txt


dos.writeInt(code);
dos.writeInt(item);
dos.writeDouble(cost);
dos.close();

//processing data from the file


DataInputStream dis = new DataInputStream( new
FileInputStream(\"Invent.txt\"));
int codeNumber = dis.readInt();
int totalItems = dis.readInt();
double itemCost = dis.readDouble();

Prepared by Mrs.R.Padma Page 76


JAVA PROGRAMMING

double totalCost = totalItems * itemCost;

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

Prepared by Mrs.R.Padma Page 77

You might also like