Java
Java
Java
According to Sun, 3billion devices run Java. There are many devices where Java is currently used. Some of
them are as foliows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as linkedin.com, alibaba.com etc
V Enterprise Applications such as banking applications.
Mobile
/ Embedded System
Smart Card
Robotics
Games,etc.
Iypes of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
Stardalore Applications : Standalone applications are also known as desktop applications or window
based applications. These are traditional software that we need to install on every machine. Examples
of standalone application are Media player, antivirus, etc. AWT(Abstract Window Toolkit) and Swing
used in Javafor creating standalone applications.
Web Applications An application that runs on the server side and creates a dynamic page is called a
web application. Currentiy, Servlet, ISP (lava Server Pages), Struts, Spring. Hibernate, ISF (Java Server
Faces) etc. technologies are used for creating web applications in Java.
Enterprise Applications :An application that is distributed in nature, such as banking applications, etc.
is called an enterprise application.It has advantages like high-level security, load balancing, and
clustering. In Java, EJB(Enterprise Java Beans ) is used for creating enterprise applications.
V Mobile Applications : An applicationwhich is crezted for mobile devices is called a mobile application.
Currently, Android and Java ME (Micro Edition) are used for creating mobile applications.
Aava Virtual Machine :
applications. JVM is the one that actualy
JVMUava Virtual Machine) acts as a run-time engine to run Java
JRE(J ava Runtime Environment).
Calls the main method present in a java code. JVM is a part of means a programmer can develop Java
JaVeappiications are called WORA (Write Once Run Anywhere). This
Java-enabled system without any adjustmnent. This
Code on one system and can expect it to run on any other
sall possible because of JVM.'
translates the source code into byte
Java is both compiled and interpreted language. First the java compiler
byte code instructions to machine code
Code instructions. In the next stage the java interpreter converts the
intermediate code nameBy the
that can be directly executed by the machine running the java program. The
computer within the
yiecode pioduced by the java coinpiler is for a machine. This machine or simulated
computer is called the Java Virtual Machine (NM)and it exists onty inside the computer memory.
bytecode which is also referred to
The following figure illustrates the process of compiling a java program into
as virtual machine code.
Jave Jva
Progrom Comper Nchne
SourceCoe Byecode
The virtual machine code is not machine specific. The machine specific code (know as
machine code) is generated by the java interpreter by acting as an intermediary between the virtual machine
and the real machine as shown in the figure
Java
Bysecode nterpreter Code
Tasks of JVM:
We need the Java virtual machine for the tasks that it performs wthich are extremely necessary for an
development, invoving Java. Following 3re a few tasks that Java virtual machine does.
Loads the code
V Code verification
V Execution of the code
It provides the run-time environment for the applications
Memory area
Register set
Provides a garbage collection heap
Win32 UNIX macoS
ava Tokens
statements. MoSt
A class is aefined by a set of declaration statements and methods containing executable
statements contain expressions which describe the actions carried out on data. Smallest individual units in d
program are known as tokens. The compiler recognizes them for building up expressions and statementS.
types or
A java program is a collection of tokens, comments and white spaces. Java language includes fIve
tokens. They are Reseved
Reserved or keywords
Identifiers
Literals
Operators
V Separators
Kevords:
Keywords are an essential part of alanguage definition. They implement specificfeatures of the language.
Java language has more than 50 words as keywords. These keywords combined with operators and separators
according to asyntax form definition of the java language.
abstrat ASSert boolean brcak
catch char
bytc
class const continue default
do double clsc cnun
Identifiers :
ldentifiers are programmers-designed tokens. They are used for naming classes, methods variables obiects
follow the following rules
labels packages and interfaces in aprogram. Java identifiers
OOlege. Kurnool
Ihey can have alphabets digitsand the underscore and dollar sign characters.
They must not begin with a digit
Blank spaces, special characters are not allowed except dollar sign(S) and underscore() character.
They must not be a keyword.
Uppercase and lowercase letters are distinct
They can be of any length
Literals :
Literals in java are a sequence ot characters (digits, ietters, and other characters) that represent constant
values to be stored in variables. Java language specifies five major types of literals. They are:
Integer literals (ex:10)
Floating-point literals(ex:25.6)
Character literals (ex:'b')
String literals (ex:"java")
Boolean literals (ex:true)
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
Operator specifyan evaluation or calculation to be performed on data or objects.
Separators:
Separators are symbols used to indicate where groups of code are divided and arranged. They basically
define the shape and function of our code.
parentheses () :Used for defining precedence in expressions and Used to contain the values o
automatically initialized arrays.
braces {):Todefine a block of code for classes, methods and used to contain the values
brackets []: Used to declare array types
semicolon: : Used to separate statements
declaration
comma, :Used to separate consecutive identifiers in a variable
period . :Usedto separate package names from sub-packages andclasses.
éatures of Java
Java isalanguage that has become successful and popular because of the following teatures
Platform independent : The Java programs compiled on one operating system can be transferred and
executed on any Operating System without modifications. This can be achieved through an application
called Java Virtual Machine or simply JVM, as follows: Once we create the java source code, we
Compile it using Java Compiler.The compiler then creates something called Java Byte code.This byte
Code can be copied and executed anywhere, even on mobile phones. Thus, Java is also called an
Architecture Neutra! Language.
Object-oriented : Java is apurely object-oriented language. This means that every 0OP concept is
Supported by Java. Object-oriented means WE organize our software as a conmbination of different
types of objects that incorporate both data and behavior.
Compiled and interpreted : Java is a language that provides both compilation and interpretation of
programs. Once the java program is created, it is compiled by Java Compiler. This compiled code (Byte
code) can be executed using Java Interpreter.
Multi-Threaded : With this feature, Java supports "Multitasking". Multitasking is when multiple jobs
are executed simultaneously. Multitasking improves CPU and Main Memory Utilization.
Dynamic :This is one of the important features that made Java popular. Assume that we created 100
functions in a program. In no case, would all the functions are executed. But, in languages like C,
whether it's required or not, all the functions are loaded into memory, which results in wasting
memory. However, in Java, a function is not loaded into the memory until you call the function. So,
furctionsare only loaded when they are calied (i.e.,at run-time).
Simple, small, and familiar: The Java program is easy to build and implement when compared
languages like C and C++ because most of the concepts in these languages that people felt were
difficult or confusing have been eliminated in Java. Also, the concepts in C and C++ that programmers
have enjoyed are included in Java.
V Robust and Secure : As a robust language, Java provides many safeguards to ensure reliable code. lt
aiso provides an exception handling concept to handle logical errors that may crash a system.
As a secured Language, Java makes sure that programs cannot gain access to memory locations
without proper authorization.
Distributed :Java is a distributed language for creating networking applications, and it can share data
and programs. Java applications provide mechanisms to open and access objects remotely.
V High Performance : Java architecture is designed to reduce overheads during run-time. The concept
multithreading in Java also increases the execution speed of Java programs.
Variables, Constants and Datatypes:
Variables:
A variable is an identifier that denotes a stor age location used to store s data value. Unlike constants that
remain unchanged during the execution of aprogram Avariable may take different values at different imnes
during the execution of the program.
roflert t . t opr,ont:
A variable name can be chosn by the programmcr in a me aningfu! we so 2 to
the program.
Java Constant
Numerie Character
cestant Ceastant
Integer constants :
An integer constant refers to a sequence of digits. There are three types of integers, namely,
Decimal integers : Decinmal integers consist of a set of digits, 0 through 9 preceded by an optional
minus sign.
Valid examples of decimal integer constants are 123 -321 0 654321
Octal integers: An octal integer constant is a sequence of any combination of digits from 0 to 7.Octal
integer always starts with 0. The digits 8 and 9 are not valid in octal notation.
The examples of valid integer constants in octal notation are 024, 0, 0578, and 0123.
Hexadecimal integers:Hexadecimal integer constants consist of digits 0 to9 and alphabets "a" to""
or "A" to "F", These constants are precededbyOx. Letter "A" to "F" represents the numbers 10to 15.
The valid examples of hexadecimal integer constants are Ox23, 0x58, Ox9F, Ox, etc. "x can also be
either small or capital.
Real constants:
Integer numbers are inadequate to represent quantities that vary continuously such distances heights
temperatures prices and so on. These quantities are represented by numbers containing fractional parts like
17.548. such numbers are called real (or floating point) constants.
Character constants:
Single character constants : A single character constant(or simply character constant) contains a single
character enclosed within a pair of singlequote marks.
Examples: '5'
String constants : Astring constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.
Examples : "hello java" "1997" "welldone" "?.." "5+3" "X"
Backslash character constants :
Javasupports some special backslash example the
constants that are used in output methods. For
symbol \n' stands for newline character although they
Note that each one of them represents one character
Onsist of two characters. Thesecharacter.
characters combinations are known as escape seyuc
Backslash character constants
Constant meaning
back space
form feed
new line
carriage return
horizontal tab
4" single quote
double quote
backslash
To declare any variable as constant, we use final modifiers. It is also
known as non-access modifiers.
Example:fina! double PRICE=432.78;
étatypes :
Every variable in java has a data type. Data types specify the size and type of values that can be stored. Java
language is rich in its data types. The variety of data types available allow the programmer to select the type
appropriate to the needs of the application.
Integer types :
integer types can hold whole numbers such as 123, -96 and 5639. The size of the values that can be stored
depends on the integer data type we choose. Java supports four types of integers they are byte, short, int and
long. Java does not support the concept of unsigned types and therefore all java values are signed meaning
they can be positive or negative. The memory size and range of allthe four integer data types are...
integer
Byte Long
BSC., IV Sem
Java String length): The Java String length) method tells the length of the string. It
returns count of total number of characters present in the String. For example:
Java String concat() : The Java String concat() method combines a specific string at
the end of another string andultimately returns a combined string. It is like
another string. For example:
appending
Juva String lsEnpy:This : l ecks whether the String contains arything or
not. If the java String is Empty, it returns true else false.
For examnple:
JavaString Trimn) : The java string trim() method renmoves the leading and trailing
spaces. It checks the unicode value of space character ("u0020') before and after the
string. If it exists, then removes the spaces and return the omitted string. For example:
Java String toLower Case():The java string toLowerCase() method converts all the
characters of the String to lower case. For example:
Java String toUpper): The Java String toUpperCase) method converts all the
characters of the String to upper case. For example:
char charAt(int index): It returns the character at the\specified
index value slhould be between 0 to length) -1 botlh index.]Specificd
inclusive. It throws
IndexOutOfBoundsExccption if index<0|>= length of String.
Creating Sub Packagein a Package, AUUes
Polymorphism
Greck words 'poly' mcans many and morphos rncans
Pólymorphism came from the two
Polymorphism is the process of defining samemethod with different implernentation.
for1ms.
Polymorphism with variable:
Let us take following example,
float a=15.5f;
int x-(int)a;
charged by using a cast operator.
In the second linc, the actual data type of the variable in taken as it is, it becomes flvat
Even if 'a' is float type, it is converted into int type. If 'a' is
int. This means 'a' exits in two
type and because we converted, it can take the form of an
'conversion.
forms. This also comes under polymorphism, which is called
Polymorphism using Methods:
Polymorphis1 with methods we can implement in two ways one is method overloading and
another one is method overriding.
Method overloading is one of the java's most exciting and useful feature. Through this we
achieve polymorphism.
The facility to define two or more methods within the same class that share the same
name,as long as their parameters declarations are different is called method overloading.
V Method overloading used when objcct are required to perfor1n similar tasks but using
different parameters. When we call a method in an objcct, java matches up the method
name first and then the number and type of parameters to decide which one of the
definitions to execute.This process is known as polymorphism.
Overloaded methods must differ in type or order or number of their parameters. That is
cach parameter list should be unique.
E.g.: int mymethod(int,int);
intmymethod(long, long);
void mymethod(float);
E[ample program:
class Overloading
voidadd(int a,int b)
System.out.printin("'sum="+(a +b)):
Dert. of Comp1tcr Scicnce
Degrce College, knl.
/1ypeCasting
of
Types of Data Types: the predefined data types
are
Primitive Data Tyype: In Java, the primnitive dala Lypes Java has 8 primitive data types
Java. Thcy specifythe size and type of any standard values.
namcly byte, short, int, long, float. double, char and boolcan. Data Type or Non-primitive
Object
Reference Data Type: These are also referred to as to any particular objects.
Unlike the
because they refer
Ype. Thcy arc s0-called ones are created by the users
in Java. Ixampies
-primitive
1*mwve dala types, the non
DClud arrays, strings, classcs, interfaces etc.
another data
Type Casting:
method or process that converts a data type into
n Java, (ype casting is
a
automatic conversion is done by the
The
lype in both ways manually and automatically.
programmer.
compiler and manualconversion performed by the
Casting Primitive Data Types:
There are two typcs of type casting.
Widening Type Casting
Narrowing Type Casting
is
Widening Type Casting: Converting a lower data type into a higher one
doWn.
called widening type casting. It is also known as implicit conversion or casting
byte - short ->char -> int -> long -> float -> double
It is donc automatically. It is safe because there is no chance to lose data. It takes place
when:
Bothdata types must be compatible with cach other.
Thetarget lype mnust be larger than the source type.
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, thechar and Boolcan data type% are not compatible with each other.
public class WideningT ypeCasting
publicsatic void main(Stringl ]args)
int x-7, lautomatically converts the integer type into long type
Packages
A package can be detined as a group of similar types of classes, interface.
cnumeration and sub-package. Using package it becomes easier to locate the related classes.
Packages
Built-in Packages
These packages consist of alarge number of classes which are a part of Java AP
Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Containsclassed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List.
Dictionary and support : for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
Exception handling in java
Introduction program to go wrong.An error may produce an
can make a system
Errors are the wrongs that execution of the programn abruptly or even may cause the
the
incorrectoutput or may teriminate
to crash.
Txpes of Errors
into two categories
Errors nay broadly be classified
Compile-time errors
V Run-time errors
Compile-Time Errors
displayed by the Java compiler and therefore these errors
and
Allsyntax errors will be detected compiler displays an error, it will not
create the
Run-Time Errors
may compile successfully creating the .class file but may not run properly.
Sometimes a program may terminate due to errors such as
logic or
due to Wrong
Such programsmay produce wrong results are:
stackOverflow. Most common run-time errors
V Dividing an integer by zero array
Accessing an element that is out of the bounds of an
incompatible class or type
Trying to storea value into an array of an
of its subclasses
Trying to cast an instance of a class to one
value for a method
Passing a parameter that is not in avalid range or
thread
Trying to illegally change the state of a
Atempting to use a negative size for an array.
acces_ a method or a variabl
Using anullobject reference as a legitimate object reference to
Converting invalid string toa number
Accessing a character that is out of bounds of a string
Multithreaded Programming
Multithreading is a conceptual programming paradigm where a program (process) is divided
into two ormore subprograms (processes), which can be implemented at the same time in parallel.
A thread is similar to a program that nas a single flow of control. It has a beginning, a body,
and an end, and executes commands sequentially, In fact, all main programs in our earlier examples
can be called single threaded programs. Every program will have at least one thread.
A unique property of Java is its support for multi threading. That is, Java enables us to use
multiple flows of control in developing programs. Each flow of control may be thought of as a
Separate tiny program (or module) known as a Thrcad that runs in parallel to others. A program that
contains multiple flows of control is known as multithreaded program.
It is important to remember that threads running in parallel do not really mean that they
actually run at the same time. Since all the threads are running on a single processor, the flow of
eXecution is shared between the threads. The Java interpreter handles the switching of control between
the threads in such a way that it appear; they are running concurrently.
Multithreading is useful in anumber of ways, Itenables programmer to do multiple things at
one timne. They can divide a long program into threads and execute them in parallel.
Main Thread
switching switching
The above diagram illustrates a Java program with four threads, one
thread is actually the main method module, which is designed to main and three others, The main
threads, namely A,B and C. create and start the other three
CCeating Threads
Creating threads in Java is simple. Threads arc implemented in the form
of objects
contain a method called run). The run() method is the heart and soul of any thread. It makes up that
entire body of a thread and is the only method in which the the
typical un( ) would appear as follows: thread's behavior can be implenmented. A
Life Cycle of a Thread
states it can enter. They include;
During the life time ofathread, there are many
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
variety of
It can move from one state to another via a
A thread is always in one of these five states.
ways as shown in the following figure...
sleep()
suspend( ) resume() stop( )
wait( ) notify( )
Blocked
Idle Thread
(Not runnable)
Newborn State
When we create athreadobject, the thread is born and is said to be in newborn state. The thread is
not yet scheduled for running. At this state, we can do only one of the following things with it:
. Schedule it for running using start( ) method.
2. Killit using stop( ) method.
Runnable State
The rurnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is the thread has joined the queue of threads that are waiting for
cxccution, If allthreads have equal priority, then they are given time slots for execution in round robin
fashion, i.e., first-come, first-serve manner. The thread that relinquishes control joins the queue at the
cnd and agaín waits for its tun. Thís process of assigning tíme to thrcads is known as time-slicing.
However, if we want a thread to relinquish control to another thread to equal priority before
its turn comes, we can do so by using the yield() method.
yield()
Running State
Running means that the processor has given its time to the thread for its execution. The thread
runs until it relinquishes control on its own or it is preempted by a higher priority thread. A running
thread my relinquish its control in one of the following situations.
1. It has been suspended using suspend( ) method. Asuspended thread can be revived by using
the resumc() method, This approach is useful when we want to suspend a thread for Some
time due to certain reason, but do not want to kill it.
suspend( )
resumel
after t )
Ssreams in Java:- Stream is a sequence of objects that supports various methods which can h.
pipeliaed toproduce the desired result.
The features of Java stream are
A stream is not a datastructure instead it takes input from the Collections. Arrays or J/O channels.
Streams don't change the original data siructure: they only provide the result as per the pipelined
methods.
Each intermediate operation is lazily executed and returns a stream as a result: hence various
intermediate operations can be pipelined. Terminal operations mark the end of the stream and
return the result.
S8eam Ciassc FileinputStream
ByteArraylnputStream
BufferedlnputStream
Byte stLean (chaactea InputStream FilterlnputStream
DatalnputStream
INput outpt Reade waitee ObjectinputStream
OutputSteam BufferedOutputstream
FilterOutpUbuE
ObjectOutputStream
Concept of Streams
In file processing, input refers tothe flow of data into a program and outputmeans the flow of data out of
a prograin. Input to a program may come from the keyboard, the nouse, the memory, the disk, a network. o
another program. Similarly, output from a program may go to the sereen . the printer. the memory, the disk. a
network, or another program. These input and output devices share certain common characteristics such as
unidirectional movement of data, treating data as a sequence of bytes or characters and support to the sequential
access to the data.
Java uses the concept of streams to represent the ordered sequence of data A stream presents a uniform,
easy-to-use, objectoriented interface between the program and the input,output devices.
Astream in Java is a path along which data flows (like a river or a pipe along which water flows), It has
sOurce (of data) and adestination (for that data) .Both the source and the destination may be physical devices o
programs or other streams in the same program.
Inputstream Outputstream
JAVA
Source APPLICATION Destinaton
READ Write
Lócal and Romote Applets
wils 1wi i l a
We cul Cmbed applets into Weh pages in Iwo ways. One, we Lan
Chbed them into Web pages. Second, we can download an applet tro) 4reDole çonipuk SyslEii
then embcd it into a Web page.
An apnlet developed locally and stored in alocal svslem js known 4s 4 loeal Hpplet Wlien a
lHal
Web page is trying to find alocal applet, i does not need to use the Internel 4d Whereloe lhe
Sy slem does not require the Internet connection, it simply earches the directories in lle local syste'm
and Locates and loads the specified applet.
LAcal Appls!
LOcal Syssm
A remote applet is that which is developed by someone else and storcd on a remote compuler
connected to the Internet. If our system is connected to the Internet, we can download the remote applet
onto our system via Internet and run it
Remote
Applet
In order to locate and load a remote applet we must know the applet's address on the Wcb. This
address is known as UnifonResource Locator (URL) and must be spccified in the applet's HTML
document as the value of the CODEBASE attribute.
I/code here...
This requires that the applet code imports the java.awt package that contains the Graphics class. All
output operations of an applet are performed using the methods defined in the Graphics class.
Example:
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
g.drawString("Hello Java...",20,20);