Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 44

Java is an object-oriented programming language developed by James Gosling and colleagues

at Sun Microsystems in the early 1990s. Unlie conventional languages !hich are generally
designed either to be compiled to native "machine# code$ or to be interpreted %rom source code at
runtime$ Java is intended to be compiled to a bytecode$ !hich is then run "generally using J&'
compilation# by a Java (irtual Machine.
'he language itsel% borro!s much synta) %rom * and *++ but has a simpler object
model and %e!er lo!-level %acilities. Java is only distantly related to JavaScript$ though they have
similar names and share a *-lie synta).
History
Java !as started as a project called ,-a, by James Gosling in June 1991. Gosling.s
goals !ere to implement a virtual machine and a language that had a %amiliar *-lie notation but
!ith greater uni%ormity and simplicity than */*++. 'he %irst public implementation !as Java 1.0 in
1990. &t made the promise o% ,1rite -nce$ 2un 3ny!here,$ !ith %ree runtimes on popular
plat%orms. &t !as %airly secure and its security !as con%igurable$ allo!ing %or net!or and %ile
access to be limited. 'he major !eb bro!sers soon incorporated it into their standard
con%igurations in a secure ,applet, con%iguration. popular 4uicly. 5e! versions %or large and
small plat%orms "J677 and J6M7# soon !ere designed !ith the advent o% ,Java 6,. Sun has not
announced any plans %or a ,Java 8,.
&n 1999$ Sun approached the &S-/&7* J'*1 standards body and later the 7cma
&nternational to %ormali:e Java$ but it soon !ithdre! %rom the process. Java remains a proprietary
de %acto standard that is controlled through the Java *ommunity ;rocess. Sun maes most o% its
Java implementations available !ithout charge$ !ith revenue being generated by speciali:ed
products such as the Java 7nterprise System. Sun distinguishes bet!een its So%t!are
<evelopment =it "S<=# and 2untime 7nvironment "J27# !hich is a subset o% the S<=$ the
primary distinction being that in the J27 the compiler is not present.
Philosophy
'here !ere %ive primary goals in the creation o% the Java language>
1. &t should use the object-oriented programming methodology.
6. &t should allo! the same program to be e)ecuted on multiple operating systems.
8. &t should contain built-in support %or using computer net!ors.
?. &t should be designed to e)ecute code %rom remote sources securely.
0. &t should be easy to use by selecting !hat !as considered the good parts o% other object-
oriented languages.
'o achieve the goals o% net!oring support and remote code e)ecution$ Java programmers
sometimes %ind it necessary to use e)tensions such as *-2@3$ &nternet *ommunications
7ngine$ or -SGi.
Object orientation
'he %irst characteristic$ object orientation ",--,#$ re%ers to a method o% programming and
language design. 3lthough there are many interpretations o% --$ one primary distinguishing idea
is to design so%t!are so that the various types o% data it manipulates are combined together !ith
their relevant operations. 'hus$ data and code are combined into entities called objects. 3n object
can be thought o% as a sel%-contained bundle o% behavior "code# and state "data#. 'he principle is
to separate the things that change %rom the things that stay the sameA o%ten$ a change to some
data structure re4uires a corresponding change to the code that operates on that data$ or vice
versa. 'his separation into coherent objects provides a more stable %oundation %or a so%t!are
system.s design. 'he intent is to mae large so%t!are projects easier to manage$ thus improving
4uality and reducing the number o% %ailed projects.
3nother primary goal o% -- programming is to develop more generic objects so that so%t!are can
become more reusable bet!een projects. 3 generic ,customer, object$ %or e)ample$ should have
roughly the same basic set o% behaviors bet!een di%%erent so%t!are projects$ especially !hen
these projects overlap on some %undamental level as they o%ten do in large organi:ations. &n this
sense$ so%t!are objects can hope%ully be seen more as pluggable components$ helping the
so%t!are industry build projects largely %rom e)isting and !ell-tested pieces$ thus leading to a
massive reduction in development times. So%t!are reusability has met !ith mi)ed practical
results$ !ith t!o main di%%iculties> the design o% truly generic objects is poorly understood$ and a
methodology %or broad communication o% reuse opportunities is lacing. Some open source
communities !ant to help ease the reuse problem$ by providing authors !ith !ays to disseminate
in%ormation about generally reusable objects and object libraries.
Platform independence
'he second characteristic$ plat%orm independence$ means that programs !ritten in the Java
language must run similarly on diverse hard!are. -ne should be able to !rite a program once
and run it any!here.
'his is achieved by most Java compilers by compiling the Java language code ,hal%!ay, to
bytecode "speci%ically Java bytecode#Bsimpli%ied machine instructions speci%ic to the Java
plat%orm. 'he code is then run on a virtual machine "(M#$ a program !ritten in native code on the
host hard!are that interprets and e)ecutes generic Java bytecode. Curther$ standardi:ed libraries
are provided to allo! access to %eatures o% the host machines "such as graphics$ threading and
net!oring# in uni%ied !ays. 5ote that$ although there.s an e)plicit compiling stage$ at some point$
the Java bytecode is interpreted or converted to native machine instructions by the J&' compiler.
'here are also implementations o% Java compilers that compile to native object code$ such as
G*J$ removing the intermediate bytecode stage$ but the output o% these compilers can only be
run on a single architecture.
Sun.s license %or Java insists that all implementations be ,compatible,. 'his resulted in a legal
dispute !ith Microso%t a%ter Sun claimed that the Microso%t implementation did not support the
2M& and J5& inter%aces and had added plat%orm-speci%ic %eatures o% their o!n. &n response$
Microso%t no longer ships Java !ith 1indo!s$ and in recent versions o% 1indo!s$ &nternet
7)plorer cannot support Java applets !ithout a third-party plug-in. Do!ever$ Sun and others have
made available Java run-time systems at no cost %or those and other versions o% 1indo!s.
'he %irst implementations o% the language used an interpreted virtual machine to achieve
portability. 'hese implementations produced programs that ran more slo!ly than programs
compiled to native e)ecutables$ %or instance !ritten in * or *++$ so the language su%%ered a
reputation %or poor per%ormance. More recent J(M implementations produce programs that run
signi%icantly %aster than be%ore$ using multiple techni4ues.
'he %irst techni4ue is to simply compile directly into native code lie a more traditional compiler$
sipping bytecodes entirely. 'his achieves good per%ormance$ but at the e)pense o% portability.
3nother techni4ue$ no!n as just-in-time compilation "J&'#$ translates the Java bytecodes into
native code at the time that the program is run !hich results in a program that e)ecutes %aster
than interpreted code but also incurs compilation overhead during e)ecution. More sophisticated
(Ms use dynamic recompilation$ in !hich the (M can analy:e the behavior o% the running
program and selectively recompile and optimi:e critical parts o% the program. <ynamic
recompilation can achieve optimi:ations superior to static compilation because the dynamic
compiler can base optimi:ations on no!ledge about the runtime environment and the set o%
loaded classes. J&' compilation and dynamic recompilation allo! Java programs to tae
advantage o% the speed o% native code !ithout losing portability.
;ortability is a technically di%%icult goal to achieve$ and Java.s success at that goal has been
mi)ed. 3lthough it is indeed possible to !rite programs %or the Java plat%orm that behave
consistently across many host plat%orms$ the large number o% available plat%orms !ith small errors
or inconsistencies led some to parody Sun.s ,1rite once$ run any!here, slogan as ,1rite once$
debug every!here,.
;lat%orm-independent Java is ho!ever very success%ul !ith server-side applications$ such as
1eb services$ servlets$ and 7nterprise Java@eans$ as !ell as !ith 7mbedded systems based on
-SGi$ using 7mbedded Java environments.
Automatic garbage collection
-ne idea behind Java.s automatic memory management model is that programmers should be
spared the burden o% having to per%orm manual memory management. &n some languages the
programmer allocates memory to create any object stored on the heap and is responsible %or later
manually deallocating that memory to delete any such objects. &% a programmer %orgets to
deallocate memory or !rites code that %ails to do so in a timely %ashion$ a memory lea can occur>
the program !ill consume a potentially arbitrarily large amount o% memory. &n addition$ i% a region
o% memory is deallocated t!ice$ the program can become unstable and may crash. Cinally$ in non
garbage collected environments$ there is a certain degree o% overhead and comple)ity o% user-
code to trac and %inali:e allocations.
&n Java$ this potential problem is avoided by automatic garbage collection. 'he programmer
determines !hen objects are created$ and the Java runtime is responsible %or managing the
object.s li%ecycle. 'he program or other objects can re%erence an object by holding a re%erence to
it "!hich$ %rom a lo!-level point o% vie!$ is its address on the heap#. 1hen no re%erences to an
object remain$ the Java garbage collector automatically deletes the unreachable object$ %reeing
memory and preventing a memory lea. Memory leas may still occur i% a programmer.s code
holds a re%erence to an object that is no longer neededBin other !ords$ they can still occur but at
higher conceptual levels.
'he use o% garbage collection in a language can also a%%ect programming paradigms. &%$ %or
e)ample$ the developer assumes that the cost o% memory allocation/recollection is lo!$ they may
choose to more %reely construct objects instead o% pre-initiali:ing$ holding and reusing them. 1ith
the small cost o% potential per%ormance penalties "inner-loop construction o% large/comple)
objects#$ this %acilitates thread-isolation "no need to synchroni:e as di%%erent threads !or on
di%%erent object instances# and data-hiding. 'he use o% transient immutable value-objects
minimi:es side-e%%ect programming.
*omparing Java and *++$ it is possible in *++ to implement similar %unctionality "%or e)ample$ a
memory management model %or speci%ic classes can be designed in *++ to improve speed and
lo!er memory %ragmentation considerably#$ !ith the possible cost o% e)tra development time and
some application comple)ity. &n Java$ garbage collection is built-in and virtually invisible to the
developer. 'hat is$ developers may have no notion o% !hen garbage collection !ill tae place as it
may not necessarily correlate !ith any actions being e)plicitly per%ormed by the code they !rite.
<epending on intended application$ this can be bene%icial or disadvantageous> the programmer is
%reed %rom per%orming lo!-level tass$ but at the same time loses the option o% !riting lo!er level
code.
Syntax
'he synta) o% Java is largely derived %rom *++. Do!ever$ unlie *++$ !hich combines the synta)
%or structured$ generic$ and object-oriented programming$ Java !as built %rom the ground up to be
virtually %ully object-oriented> everything in Java is an object !ith the e)ceptions o% atomic
datatypes "ordinal and real numbers$ boolean values$ and characters# and everything in Java is
!ritten inside a class.
Applet
Java applets are programs that are embedded in other applications$ typically in a 1eb page
displayed in a 1eb bro!ser.
// Dello.java
import java.applet.3ppletA
import java.a!t.GraphicsA
public class Dello e)tends 3pplet E
public void paint"Graphics gc# E
gc.dra!String",Dello$ !orldF,$ G0$ 90#A
H
H
'his applet !ill simply dra! the string ,Dello$ !orldF, in the rectangle !ithin !hich the applet !ill
run. 'his is a slightly better e)ample o% using Java.s -- %eatures in that the class e)plicitly
e)tends the basic ,3pplet, class$ that it overrides the ,paint, method and that it uses import
statements.
IF-- Dello.html --J
IhtmlJ
IheadJ
ItitleJDello 1orld 3ppletI/titleJ
I/headJ
IbodyJ
Iapplet codeK,Dello, !idthK,600, heightK,600,J
I/appletJ
I/bodyJ
I/htmlJ
3n applet is placed in an D'ML document using the IappletJ D'ML element. 'he applet tag has
three attributes set> codeK,Dello, speci%ies the name o% the 3pplet class and !idthK,600,
heightK,600, sets the pi)el !idth and height o% the applet. "3pplets may also be embedded in
D'ML using either the object or embed element$ although support %or these elements by 1eb
bro!sers is inconsistent.
Servlet
Java servlets are server-side Java 77 components that generate responses to re4uests %rom
clients.
// Dello.java
import java.io.MA
import java).servlet.MA
public class Dello e)tends GenericServlet E
public void service"Servlet2e4uest re4uest$ Servlet2esponse response#
thro!s Servlet7)ception$ &-7)ception
E
response.set*ontent'ype",te)t/html,#A
;rint1riter p! K response.get1riter"#A
p!.println",Dello$ !orldF,#A
p!.close"#A
H
H
'he import statements direct the Java compiler to include all o% the public classes and inter%aces
%rom the java.io and java).servlet pacages in the compilation. 'he Dello class e)tends the
GenericServlet classA the GenericServlet class provides the inter%ace %or the server to %or!ard
re4uests to the servlet and control the servlet.s li%ecycle.
'he Dello class overrides the service"Servlet2e4uest$ Servlet2esponse# method de%ined by the
Servlet inter%ace to provide the code %or the service re4uest handler. 'he service"# method is
passed a Servlet2e4uest object that contains the re4uest %rom the client and a Servlet2esponse
object used to create the response returned to the client. 'he service"# method declares that it
thro!s the e)ceptions Servlet7)ception and &-7)ception i% a problem prevents it %rom responding
to the re4uest.
'he set*ontent'ype"String# method in the response object is called to set the M&M7 content type
o% the returned data to ,te)t/html,. 'he get1riter"# method in the response returns a ;rint1riter
object that is used to !rite the data that is sent to the client. 'he println"String# method is called to
!rite the ,Dello$ !orldF, string to the response and then the close"# method is called to close the
print !riter$ !hich causes the data that has been !ritten to the stream to be returned to the client.
Swing application
S!ing is the advanced graphical user inter%ace library %or the Java S7 plat%orm.
// Dello.java
import java).s!ing.MA
public class Dello e)tends JCrame E
Dello"# E
set<e%ault*lose-peration"1indo!*onstants.<&S;-S7N-5N*L-S7#A
add"ne! JLabel",Dello$ !orldF,##A
pac"#A
H
public static void main"StringOP args# E
ne! Dello"#.set(isible"true#A
H
H
'he import statement directs the Java compiler to include all o% the public classes and inter%aces
%rom the java).s!ing pacage in the compilation. 'he Dello class e)tends the JCrame classA the
JCrame class implements a !indo! !ith a title bar !ith a close control.
'he Dello"# constructor initiali:es the %rame by %irst calling the set<e%ault*lose-peration"int#
method inherited %rom JCrame to set the de%ault operation !hen the close control on the title bar
is selected to 1indo!*onstants.<&S;-S7N-5N*L-S7Bthis causes the JCrame to be disposed
o% !hen the %rame is closed "as opposed to merely hidden#$ !hich allo!s the J(M to e)it and the
program to terminate. 5e)t a ne! JLabel is created %or the string ,Dello$ !orldF, and the
add"*omponent# method inherited %rom the *ontainer superclass is called to add the label to the
%rame. 'he pac"# method inherited %rom the 1indo! superclass is called to si:e the !indo! and
layout its contents.
'he main"# method is called by the J(M !hen the program starts. &t instantiates a ne! Dello
%rame and causes it to be displayed by calling the set(isible"boolean# method inherited %rom the
*omponent superclass !ith the boolean parameter true. 5ote that once the %rame is displayed$
e)iting the main method does not cause the program to terminate because the 31' event
dispatching thread remains active until all o% the S!ing top-level !indo!s have been disposed.
Loo and feel
'he de%ault loo and %eel o% GU& applications !ritten in Java using the S!ing toolit is very
di%%erent %rom native applications. &t is possible to speci%y a di%%erent loo and %eel through the
pluggable loo and %eel system o% S!ing. *lones o% 1indo!s$ G'= and Moti% are supplied by
Sun. 3pple also provides an 34ua loo and %eel %or Mac -S Q. 'hough prior implementations o%
these loo and %eels have been considered lacing$ S!ing in Java S7 G addresses this problem
by using more native !idget dra!ing routines o% the underlying plat%orms. 3lternatively$ third party
toolits such as !)?j or S1' may be used %or increased integration !ith the native !indo!ing
system.
Lac of OO purity and facilities
Java.s primitive types are not objects. ;rimitive types hold their values in the stac rather than
being re%erences to values. 'his !as a conscious decision by Java.s designers %or per%ormance
reasons. @ecause o% this$ Java is not considered to be a pure object-oriented programming
language. Do!ever$ as o% Java 0.0$ autobo)ing enables programmers to !rite as i% primitive types
are their !rapper classes$ and %reely interchange bet!een them %or improved %le)ibility. Java
designers decided not to implement certain %eatures present in other -- languages$ including>
M multiple inheritance
M operator overloading
M class properties
M tuples
Java !untime "nvironment
'he Java 2untime 7nvironment or J27 is the so%t!are re4uired to run any application deployed
on the Java ;lat%orm. 7nd-users commonly use a J27 in so%t!are pacages and 1eb bro!ser
plugins. Sun also distributes a superset o% the J27 called the Java 6 S<= "more commonly
no!n as the J<=#$ !hich includes development tools such as the Java compiler$ Javadoc$ and
debugger.
'hese tutorials !ill introduce you to Java programming Language. Rou.ll compile and run your
very o!n Java application$ using Sun.s J<=. &t is e)tremely easy to learn java programming sills$
and in these parts$ you.ll learn ho! to !rite$ compile$ and run Java applications. @e%ore you can
develop corejava applications$ you.ll need to do!nload the Java <evelopment =it "J#$#.
PA!%&'
Java Dello 1orld ;rogram
Java *omments
Java <ata and (ariables
Java *ommand Line 3rguments
PA!%&(
Java 3rithmetic -perators
Java 3ssignment -perators
Java &ncrement and <ecrement -perators
Java 2elational -perators
Java @oolean -perators
Java *onditional -perators
PA!%&)
Java &%-else Statement
Java Loops "!hile$ do-!hile and %or loops#
Java 3rithmetic e)pressions
PA!%&*
Methods
3rrays
*lasses and -bjects
&nter%aces
PA!%&+
*atching 7)ceptions
Cile &/- and Streams
Do! to mae e)ecutable jar %iles in J<=S
JA,A SO-!." .O#"
How to /nstall Java
'hese instructions are to help you do!nload and install Java on your personal computer. Rou
must install Java be%ore installing 7clipse$ and you !ill need both.
#ownloading and /nstalling Java On 0indows1
Prevent "rrors lie &&2 3javac3 is not recogni4ed as an internal or external command
1. Go to http155java6sun6com and do!nload the latest (ersion o% Jave S<= or any Jace S<= as
per your re4uirement and install on your system.
6. 3ccept all o% the de%aults and suggestions$ but mae sure that the location !here Java !ill be
installed is at the top level o% your *> drive. *lic on ,Cinish., Rou should have a directory "%older#
named *>Tj6sd1.0.0N0?$ !ith sub%olders *>Tj6sd1.0.0N0?Tbin and *>Tj6sd1.0.0N0?Tlib
?. Modi%y your system variable called ,PA%H, "so that programs can %ind !here Java is located#.
'o do this %or 1indo!s 6000 or Q;$ either right-clic on the My *omputer icon or select ,System,
on the control panel. 1hen the !indo! titled ,System ;roperties, appears$ choose the tab at the
top named ,3dvanced., 'hen$ clic on ,7nvironment (ariables., &n the bottom !indo! that sho!s
system variables$ select ,;ath, and then clic on ,7dit..., 3dd *>Tj6sd1.0.0N0?Tbin as the %irst
item in the list. 5ote that all items are separated by a semicolon$ !ith no spaces around the
semicolon. Rou should end up !ith a path variable that loos something lie
*>Tj6sd1.0.0N0?TbinA*>T1&55'Tsystem86A*>T1&55'A*>T1&55'Tsystem86T1bem
Cor 1indo!s 9U or M7$ open the %ile 3U'-7Q7*.@3' in 5otepad. Rou should %ind a line in this
%ile that begins
S7' ;3'DK...
Modi%y this line to add *>Tj6sd1.0.0N0?TbinA immediately a%ter the e4uals sign.
0. Modi%y or create a system variable called ,.LASSPA%H7, as %ollo!s. &n the lo!er ,System
(ariables, pane choose ,5e!..., and type in (ariable 5ame ,*L3SS;3'D, and value "note that
it begins !ith dot semicolon#
.A*>Tj6sd1.0.0N0?Tlib
G. 'o test Java to see i% everything is installed properly$ open a command !indo! "a <-S
!indo!# and type the command ,javac, 'he result should be in%ormation about the Usage o%
javac and its options. &% you get a result that ,.javac. is not recogni:ed as an internal or e)ternal
command$ operable program or batch %ile, then there is a problem and Java !ill not !or
correctly.
Java Hello 0orld Program
-ur %irst application !ill be e)tremely simple - the obligatory ,Dello 1orld,. 'he %ollo!ing is the
Dello 1orld 3pplication as !ritten in Java. 'ype it into a te)t %ile or copy it out o% your !eb
bro!ser$ and save it as a %ile named HelloWorld.java. 'his program demonstrates the te)t output
%unction o% the Java programming language by displaying the message ,Dello !orldF,. Java
compilers e)pect the %ilename to match the class name.
3 java program is de%ined by a public class that taes the %orm>
public class program-name {

optional variable declarations and methods

public static void main(String[] args) {
statements
}

optional variable declarations and methods

}
Source *ode
&n your %avorite editor$ create a %ile called Dello1orld.java !ith the %ollo!ing contents>
/MM Comment
M <isplays ,Dello 1orldF, to the standard output.
M/
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!") !!"isplays t#e enclosed
String on t#e Screen $onsole
}

}
'o compile Java code$ !e need to use the .javac. tool. Crom a command line$ the command to
compile this program is>
javac Dello1orld.java
Cor this to !or$ the javac must be in your shell.s path or you must e)plicitly speci%y the path to
the program "such as c>Tj6seTbinTjavac Dello1or.java#. &% the compilation is success%ul$ javac !ill
4uietly end and return you to a command prompt. &% you loo in the directory$ there !ill no! be a
Dello1orld.class %ile. 'his %ile is the compiled version o% your program. -nce your program is in
this %orm$ its ready to run. *hec to see that a class %ile has been created. &% not$ or you receive
an error message$ chec %or typographical errors in your source code.
Rou.re ready to run your %irst Java application. 'o run the program$ you just run it !ith the java
command>
java Dello1orld
Sample 2un
Dello !orldF
'he source %ile above should be saved as my%irstjavaprog.java$ using any standard te)t editor
capable o% saving as 3S*&& "eg - 5otepad$ (i#. 3s an alternative$ you can do!nload the source %or
this tutorial.
HelloWorld.%ava
Note: &t is important to note t#at you use t#e 'ull name (it# e)tension
(#en compiling (%avac HelloWorld.%ava) but only t#e class name (#en
running (%ava HelloWorld).
Java .omments
'he Java programming language supports three inds o% comments>
/M te)t M/
'he compiler ignores everything %rom /M to M/.
/MM documentation M/
'his indicates a documentation comment "doc comment$ %or short#. 'he compiler ignores this ind
o% comment$ just lie it ignores comments that use /M and M/. 'he J<= javadoc tool uses doc
comments !hen preparing automatically generated documentation.
// te)t
'he compiler ignores everything %rom // to the end o% the line.
7)ample
Java denotes comments in three !ays>
1. <ouble slashes in %ront o% a single line comment>
int iK0A // Set the integer to 0
6. Matching slash-asteris "/M# and asteris-slash "M/# to bracet multi-line comments>
/M
Set the integer to 0
M/
int iK0A
8. Matching slash-double asteris "/MM# V asteris-slash"M/# %or Javadoc automatic hyperte)t
documentation$ as in
/MM
'his applet tests graphics.
M/
public class test3pplet e)tends appletE...
or
/MM
M 3steriss inside the comment are ignored by javadoc so they
M can be used to mae nice line marers.
MM/
'he S<= tool javadoc uses the latter /MM ..M/ comment style !hen it produces hyperte)t pages to
describe a class.
Java #ata and ,ariables
'here are U primitive data types. he U primitive data types are numeric types. 'he names o% the
eight primitive data types are>
byte short int long float double char boolean
'here are both integer and floating point primitive types. &nteger types have no %ractional partA
%loating point types have a %ractional part. -n paper$ integers have no decimal point$ and %loating
point types do. @ut in main memory$ there are no decimal points> even %loating point values are
represented !ith bit patterns. 'here is a %undamental di%%erence bet!een the method used to
represent integers and the method used to represent %loating point numbers.
/nteger Primitive #ata %ypes
%ype Si4e !ange
byte U bits -16U to +169
short 1G bits -86$9GU to +86$9G9
int 86 bits "about#-6 billion to +6 billion
long G? bits "about#-1071U to +1071U
8loating Point Primitive #ata %ypes
%ype Si4e !ange
%loat 86 bits -8.?7+8U to +8.?7+8U
double G? bits -1.97+80U to 1.97+80U
Examples
int yr K 600GA
double rats K U916 A
Cor each primitive type$ there is a corresponding wrapper class. 3 !rapper class can be
used to convert a primitive data value into an object$ and some type o% objects into primitive data.
'he table sho!s primitive types and their !rapper classes>
primitive type 0rapper type
byte @yte
short Short
int &nt
long Long
%loat Cloat
double <ouble
char *haracter
boolean @oolean
(ariables only e)ist !ithin the structure in !hich they are de%ined. Cor e)ample$ i% a variable is
created !ithin a method$ it cannot be accessed outside the method. &n addition$ a di%%erent
method can create a variable o% the same name !hich !ill not con%lict !ith the other variable. 3
java variable can be thought o% as a little bo) made up o% one or more bytes that can hold a value
o% a particular data type>
Syntax1 variabletype variablename K dataA
Source *ode ( demonstrating declaration of a variable )
class e)ample
E
public static void main " StringOP args #
E
long ) K 168A //a declaration o% a variable named ) !ith a datatype o% long
System.out.println",'he variable ) has> , + ) #A
H
H
Source *ode
public class MaxDemo {
public static void main(String args[]) {
//integers
byte largestByte = ByteM!"#$!%&'(
s)ort largestS)ort = S)ortM!"#$!%&'(
int largest*nteger = *ntegerM!"#$!%&'(
long largest%ong = %ongM!"#$!%&'(
//real numbers
+loat largest,loat = ,loatM!"#$!%&'(
double largestDouble = DoubleM!"#$!%&'(

//ot)er primitive types
c)ar a-)ar = .S.(
boolean aBoolean = true(
//Display t)em all
Systemoutprintln(/largest byte value is / 0 largestByte 0 //)(
Systemoutprintln(/largest s)ort value is / 0 largestS)ort 0 //)(
Systemoutprintln(/largest integer value is / 0 largest*nteger 0 //)(
Systemoutprintln(/largest long value is / 0 largest%ong 0 //)(
Systemoutprintln(/largest +loat value is / 0 largest,loat 0 //)(
Systemoutprintln(/largest double value is / 0 largestDouble 0 //)(
1
1
Sample 2un
'he largest byte value is 169.
'he largest short value is 869G9.
'he largest integer value is 61?9?U8G?9.
'he largest long value is 966889608GU0?990U09.
'he largest %loat value is 8.?06U68078U.
'he largest double value is 1.999G9818?UG68109780U.
Java .ommand Line Arguments
'his class demonstrates ho! command line arguments are passed in Java. 3rguments are
passed as a String array to the main method o% a class. 'he %irst element "element 0# is the %irst
argument passed not the name o% the class.

Source *ode
3n e)ample that prints in the command line arguments passed into the class !hen e)ecuted.
public class 2ead!rgs
{
public static +inal void main(String args[])
{
+or (int i=3(i4argslengt)(00i)
{
Systemoutprintln( args[i] )(
1
1
1
Sample 2un
1ith the %ollo!ing command line$ the output sho!n is produced.
java 2ead3rgs :ero one t!o three
Otpt!
'he %ollo!ing command line arguments !ere passed>
argO0P> :ero
argO1P> one
argO6P> t!o
argO8P> three
PA!%&(
Java 3rithmetic -perators
Java 3ssignment -perators
Java &ncrement and <ecrement -perators
Java 2elational -perators
Java @oolean -perators
Java *onditional -perators
Java Arithmetic Operators
'he Java programming language has includes %ive simple arithmetic operators lie are
9 :addition;7 & :subtraction;7 < :multiplication;7 5 :division;$ and = :modulo;6 'he %ollo!ing
table summari:es the binary arithmetic operators in the Java programming language.
'he relation operators in Java are> **$ !*$ +$ ,$ +*$ and ,*. 'he meanings o% these
operators are>
-se !eturns true if
op1
9
op6
op1 added to op6
op1
&
op6
op6 subtracted %rom op1
op1
<
op6
op1 multiplied !ith op6
op1
5
op6
op1 divided by op6
op1
=
op6
*omputes the remainder o% dividing op1 by op6
'he %ollo!ing java program$ 3rithmetic;rog $ de%ines t!o integers and t!o double-precision
%loating-point numbers and uses the %ive arithmetic operators to per%orm di%%erent arithmetic
operations. 'his program also uses + to concatenate strings. 'he arithmetic operations are
sho!n in bold%ace.
public class -rit#metic.rog {
public static void main(String[] args) {
!!a 'e( numbers
int i * /0
int % * 10
double ) * /0.2
double y * 10.2
!!adding numbers
System.out.println("-dding")
System.out.println(" i 3 % * " 3 (i 3 %))
System.out.println(" ) 3 y * " 3 () 3 y))
!!subtracting numbers
System.out.println("Subtracting")
System.out.println(" i 4 % * " 3 (i 4 %))
System.out.println(" ) 4 y * " 3 () 4 y))
!!multiplying numbers
System.out.println("5ultiplying")
System.out.println(" i 6 % * " 3 (i 6 %))
System.out.println(" ) 6 y * " 3 () 6 y))
!!dividing numbers
System.out.println(""ividing")
System.out.println(" i ! % * " 3 (i ! %))
System.out.println(" ) ! y * " 3 () ! y))
!!computing t#e remainder resulting
!!'rom dividing numbers
System.out.println("5odulus")
System.out.println(" i 7 % * " 3 (i 7 %))
System.out.println(" ) 7 y * " 3 () 7 y))
}
}
Java Assignment Operators
&t.s very common to see statement lie the %ollo!ing$ !here you.re adding something to
a variable. Java (ariables are assigned$ or given$ values using one o% the assignment operators.
'he variable are al!ays on the le%t-hand side o% the assignment operator and the value to be
assigned is al!ays on the right-hand side o% the assignment operator. 'he assignment operator is
evaluated %rom right to left$ so a K b K c K 0A !ould assign 0 to c$ then c to b then b to a.
i K i + 6A
Dere !e say that !e are assigning i.s value to the ne! value !hich is i+6.
3 shortcut !ay to !rite assignments lie this is to use the +K operator. &t.s one operator symbol so
don.t put blans bet!een the + and K.
i +K 6A // Same as ,i K i + 6,
'he shortcut assignment operator can be used %or all 3rithmetic -perators i.e. Rou can use this
style !ith all arithmetic operators "+$ -$ M$ /$ and even W#.
Dere are some e)amples o% assignments>
//assign 1 to
//variable a
int a K 1A
//assign the result
//o% 6 + 6 to b
int b K 6 + 6A
//assign the literal
//,Dello, to str
String str K ne! String",Dello,#A
//assign b to a$ then assign a
//to dA results in d$ a$ and b being e4ual
int d K a K bA
Java /ncrement and #ecrement Operators
'here are 6 &ncrement or decrement operators -J ++ and --. 'hese t!o operators are
uni4ue in that they can be !ritten both be%ore the operand they are applied to$ called pre%i)
increment/decrement$ or a%ter$ called post%i) increment/decrement. 'he meaning is di%%erent in
each case.
Example
) K 1A
y K ++)A
System.out.println"y#A
prints 6$ but
) K 1A
y K )++A
System.out.println"y#A
prints 1
Source *ode
//-ount to ten
class 8pto9en {
public static void main (String args[]) {
int i
'or (i*/ i +*/0 i33) {
System.out.println(i)
}
}
}
1hen !e !rite i++ !e.re using shorthand %or i K i + 1. 1hen !e say i-- !e.re using shorthand %or i
K i - 1. 3dding and subtracting one %rom a number are such common operations that these
special increment and decrement operators have been added to the language. '
'here.s another short hand %or the general add and assign operation$ 3*. 1e !ould normally
!rite this as i 3* /2. 'hus i% !e !anted to count %rom 0 to 60 by t!o.s !e.d !rite>
Source *ode
class -ount5o56enty {
public static void main (String args[]) {
int i
'or (i*0 i +*10 i 3* 1) { !!:ote &ncrement ;perator by 1
System.out.println(i)
}

} !!main ends #ere
}
3s you might guess there is a corresponding -K operator. &% !e !anted to count do!n %rom t!enty
to :ero by t!os !e could !rite> 4*
class -ount5o7ero {
public static void main (String args[]) {
int i
'or (i*10 i ,* 0 i 4* 1) { !!:ote "ecrement ;perator by 1
System.out.println(i)
}
}
}
Java !elational Operators
3 relational operator compares t!o values and determines the relationship bet!een
them. Cor e)ample$ FK returns true i% its t!o operands are une4ual. 2elational operators are used
to test !hether t!o values are e4ual$ !hether one value is greater than another$ and so %orth. 'he
relation operators in Java are> **$ !*$ +$ ,$ +*$ and ,*. 'he meanings o% these operators are>
-se !eturns true if
op1
2
op6
op1 is greater than op6
op1
2>
op6
op1 is greater than or e4ual to op6
op1
?
op6
op1 is less than to op6
op1
?>
op6
op1 is less than or e4ual to op6
op1
>>
op6
op1 and op6 are e4ual
op1
@>
op6
op1 and op6 are not e4ual
(ariables only e)ist !ithin the structure in !hich they are de%ined. Cor e)ample$ i% a variable is
created !ithin a method$ it cannot be accessed outside the method. &n addition$ a di%%erent
method can create a variable o% the same name !hich !ill not con%lict !ith the other variable. 3
java variable can be thought o%
'he main use %or the above relational operators are in *-5<&'&-53L phrases 'he %ollo!ing java
program is an e)ample$ 2elational;rog$ that de%ines three integer numbers and uses the
relational operators to compare them.
public class <elational.rog {
public static void main(String[] args) {
!!a 'e( numbers
int i * =>
int % * ?1
int @ * ?1
!!greater t#an
System.out.println("Areater t#an...")
System.out.println(" i , % * " 3 (i , %)) !!'alse
System.out.println(" % , i * " 3 (% , i)) !!true
System.out.println(" @ , % * " 3 (@ , %)) !!'alse
!!(t#ey are eBual)
!!greater t#an or eBual to
System.out.println("Areater t#an or eBual to...")
System.out.println(" i ,* % * " 3 (i ,* %)) !!'alse
System.out.println(" % ,* i * " 3 (% ,* i)) !!true
System.out.println(" @ ,* % * " 3 (@ ,* %)) !!true
!!less t#an
System.out.println("Cess t#an...")
System.out.println(" i + % * " 3 (i + %)) !!true
System.out.println(" % + i * " 3 (% + i)) !!'alse
System.out.println(" @ + % * " 3 (@ + %)) !!'alse
!!less t#an or eBual to
System.out.println("Cess t#an or eBual to...")
System.out.println(" i +* % * " 3 (i +* %)) !!true
System.out.println(" % +* i * " 3 (% +* i)) !!'alse
System.out.println(" @ +* % * " 3 (@ +* %)) !!true
!!eBual to
System.out.println("DBual to...")
System.out.println(" i ** % * " 3 (i ** %)) !!'alse
System.out.println(" @ ** % * " 3 (@ ** %)) !!true
!!not eBual to
System.out.println(":ot eBual to...")
System.out.println(" i !* % * " 3 (i !* %)) !!true
System.out.println(" @ !* % * " 3 (@ !* %)) !!'alse
}
}
Java Boolean Operators
The Boolean logical operators are : | , & , ^ , ! , || , && , == , != . Java supplies
a primitive data type called Boolean, instances of which can take the value true or false
only, and have the default value false. The major use of Boolean facilities is to implement
the expressions which control if decisions and while loops.
These operators act on Boolean operands according to this table
A B A|B A&B A^B !A
false false false false false true
true false true false true false
false true true false true true
true true true true false false
| t#e ;< operator
& t#e -:" operator
^ t#e E;< operator
! t#e :;9 operator
|| t#e s#ort4circuit ;< operator
&& t#e s#ort4circuit -:" operator
== t#e DF8-C 9; operator
!* t#e :;9 DF8-C 9; operator
xample
class Bool1
public static void main!"tring args#$%
&& these are boolean variables
boolean A = true'
boolean B = false'
"(stem)out)println!*A|B = *+!A|B%%'
"(stem)out)println!*A&B = *+!A&B%%'
"(stem)out)println!*!A = *+!!A%%'
"(stem)out)println!*A^B = *+!A^B%%'
"(stem)out)println!*!A|B%&A = *+!!A|B%&A%%'
,
,
Java .onditional Operators
Java has the conditional operator. &t.s a ternary operator -- that is$ it has three operands
-- and it comes in t!o pieces$ S and >$ that have to be used together. &t taes the %orm

Aoolean&expression S expression&' > expression&(

'he J(M tests the value o% Aoolean&expression. &% the value is true$ it evaluates
expression&'A other!ise$ it evaluates expression&(. Cor

7)ample
i% "a J b# E
ma) K aA
H
else E
ma) K bA
H
Setting a single variable to one o% t!o states based on a single condition is such a common use
o% i%-else that a shortcut has been devised %or it$ the conditional operator$ S>. Using the conditional
operator you can re!rite the above e)ample in a single line lie this>
ma) K "a J b# S a > bA
PA!%&)
Java &%-else Statement
Java Loops "!hile$ do-!hile and %or loops#
Java (ariables and 3rithmetic 7)pressions
Java /f&"lse Statement
"he if#else class of statements shold have the following form!
i% "condition# E
statementsA
H
i% "condition# E
statementsA
H else E
statementsA
H
i% "condition# E
statementsA
H else i% "condition# E
statementsA
H else E
statementsA
H
3ll programming languages have some %orm o% an i' statement that allo!s you to test
conditions. 3ll arrays have lengths and !e can access that length by re%erencing the variable
arrayname.lengt#. 1e test the length o% the args array as %ollo!s>
Source *ode
// 5)is is t)e 8ello program in 9ava
class Hello {
public static void main (String args[]) {

!6 :o( letGs say #ello 6!
System.out.print("Hello ")
i' (args.lengt# , 0) {
System.out.println(args[0])
}
}
}
*ompile and run this program and toss di%%erent inputs at it. Rou should note that there.s no
longer an 3rray&nde)-ut-%@ounds7)ception i% you don.t give it any command line arguments at
all.
1hat !e did !as !rap the System.out.println(args[0]) statement in a conditional test$
i' (args.lengt# , 0) { }. 'he code inside the braces$
System.out.println(args[0])$ no! gets e)ecuted i% and only i% the length o% the args array
is greater than :ero. &n Java numerical greater than and lesser than tests are done !ith the J and
I characters respectively. 1e can test %or a number being less than or e4ual to and greater than
or e4ual to !ith IK and JK respectively.
'esting %or e4uality is a little tricier. 1e !ould e)pect to test i% t!o numbers !ere e4ual by using
the K sign. Do!ever !e.ve already used the K sign to set the value o% a variable. 'here%ore !e
need a ne! symbol to test %or e4uality. Java borro!s *.s double e4uals sign$ KK$ to test %or
e4uality. Lets loo at an e)ample !hen there are more then 1 statement in a branch and ho!
braces are used inde%initely.
Source *ode
import %ava.io.6
class :umber9est
{
public static void main (String[] args) t#ro(s &;D)ception
{
Hu''ered<eader stdin * ne( Hu''ered<eader ( ne(
&nputStream<eader( System.in ) )
String inS
int num
System.out.println("Dnter an integer number")
inS * stdin.readCine()
num * &nteger.parse&nt( inS ) !! convert inS to int
using (rapper classes
i' ( num + 0 ) !! true4branc#
{
System.out.println("9#e number " 3 num 3 " is negative")
System.out.println("negative number are less t#an
Iero")
}
else !! 'alse4branc#
{
System.out.println("9#e number " 3 num 3 " is
positive")
System.out.print ("positive numbers are greater ")
System.out.println("or eBual to Iero ")
}
System.out.println("Dnd o' program") !! al(ays e)ecuted
}
}

3ll conditional statements in Java re4uire boolean values$ and that.s !hat the KK$ I$ J$ IK$ and
JK operators all return. 3 boolean is a value that is either true or %alse. Unlie in * booleans are
not the same as ints$ and ints and booleans cannot be cast bac and %orth. &% you need to set a
boolean variable in a Java program$ you have to use the constants true and 'alse. 'alse is
not 0 and true is not non-:ero as in *. @oolean values are no more integers than are strings.
7lse
$ets loo% at some examples of if#else!
//7)ample 1
i%"a KK b# E
c++A
H
i%"a FK b# E
c--A
H
//7)ample 6
i%"a KK b# E
c++A
H
else E
c--A
H
1e could add an else statement lie so>
Source *ode
// 5)is is t)e 8ello program in 9ava
class Hello {
public static void main (String args[]) {

!6 :o( letGs say #ello 6!
System.out.print("Hello ")
i' (args.lengt# , 0) {
System.out.println(args[0])
}
else {
System.out.println("(#oever you are")
}
}
}
Source $ode
public class divisor
E
public static void main"StringOP args#
int a K 10A
int b K 6A
i% " a W b KK 0 #
E
System.out.println"a + , is divisible by ,+ b#A
H
else
E
System.out.println"a + , is not divisible by , + b#A
H
H
5o! that Dello at least doesn.t crash !ith an 3rray&nde)-ut-%@ounds7)ception !e.re still not
done. java Dello !ors and Java Dello 2usty !ors$ but i% !e type java Dello 7lliotte 2usty
Darold$ Java still only prints Dello 7lliotte. Let.s %i) that.
1e.re not just limited to t!o cases though. 1e can combine an else and an i' to mae an else
i' and use this to test a !hole range o% mutually e)clusive possibilities.
$ets loo% at some examples of if#else#if!
//7)ample 1
i%"color KK @LU7## E
System.out.println",'he color is blue.,#A
H
else i%"color KK G2775# E
System.out.println",'he color is green.,#A
H
//7)ample 6
i%"employee.isManager"## E
System.out.println",&s a Manager,#A
H
else i%"employee.is(ice;resident"## E
System.out.println",&s a (ice-;resident,#A
H
else E
System.out.println",&s a 1orer,#A
H
Source *ode
// 5)is is t)e 8ello program in 9ava
class Hello {
public static void main (String args[]) {

!6 :o( letGs say #ello 6!
System.out.print("Hello ")
i' (args.lengt# ** 0) {
System.out.print("(#oever you are")
}
else i' (args.lengt# ** /) {
System.out.println(args[0])
}
else i' (args.lengt# ** 1) {
System.out.print(args[0])
System.out.print(" ")
System.out.print(args[/])
}
else i' (args.lengt# ** =) {
System.out.print(args[0])
System.out.print(" ")
System.out.print(args[/])
System.out.print(" ")
System.out.print(args[1])
}
System.out.println()
}
}
PA!%&*
Methods "&ncludes 2ecursive Methods#
3rrays
*lasses and -bjects
&nter%aces
Bethods :/ncludes !ecursive Bethods;
3 method is a group o% instructions that is given a name and can be called up at any point in a
program simply by 4uoting that name. 7ach calclation part o% a program is called a method.
Methods are logically the same as *.s %unctions$ ;ascal.s procedures and %unctions$ and
Cortran.s %unctions and subroutines.
1hen & !rote System.out.println("Hello World!") in the %irst program !e
!ere using the System.out.println() method. 'he System.out.println() method
actually re4uires 4uite a lot o% code$ but it is all stored %or us in the System libraries. 'hus rather
than including that code every time !e need to print$ !e just call the System.out.println()
method.
Rou can !rite and call your o!n methods too. Methods begin !ith a declaration. 'his can include
three to %ive parts. Cirst is an optional access speci%ier !hich can be public$ private or protected. 3
public method can be called %rom pretty much any!here. 3 private method can only be used
!ithin the class !here it is de%ined. 3 protected method can be used any!here !ithin the
pacage in !hich it is de%ined. Methods that aren.t speci%ically declared public or private are
protected by de%ault. access specifier. 1e then decide !hether the method is or is not static.
Static methods have only one instance per class rather than one instance per object. 3ll objects
o% the same class share a single copy o% a static method. @y de%ault methods are not static. 1e
%inally speci%y the retrn type.
5e)t is the name o% the method.
Source *ode
class Jactorial9est { !!calculates t)e +actorial o+ t)at number
public static void main(String args[]) {
int n
int i
long result
'or (i*/ i +*/0 i33) {
result * 'actorial(i)
System.out.println(result)
}
} !! main ends #ere


static long 'actorial (int n) {
int i
long result*/

'or (i*/ i +* n i33) {
result 6* i
}

return result
} !! 'actorial ends #ere
}
!ecursive Bethods
2ecursion is used !hen a problem can be reduced into one or several problems o% the same
nature$ but a smaller si:e. 'his process is usually repeated until a boundary situation is reached$
!here the problem can be directly solved. Java supports recursive methods$ i.e. even i% you.re
already inside method3"# you can call method3"#.
Example (& 'ecrsive Conterpart of the &bove (actorial )ethod)
nF is de%ined as n times n-1 times n-6 times n-8 ... times 6 times 1 !here n is a positive integer. 0F
is de%ined as 1. 3s you see nF K n time "n-1#F. 'his lends itsel% to recursive calculation$ as in the
%ollo!ing method>
public static long +actorial (int n) {
i' (n + 0) {
return 4/
}
else i' (n ** 0) {
return /
}
else {
return n6'actorial(n4/)
}
}
Arrays
3rrays are generally e%%ective means o% storing groups o% variables. 3n array is a group o%
variables that share the same name and are ordered se4uentially %rom :ero to one less than the
number o% variables in the array. 'he number o% variables that can be stored in an array is called
the array.s dimension. 7ach variable in the array is called an element o% the array.
*reating 3rrays
'here are three steps to creating an array$ declaring it$ allocating it and initiali:ing it.
<eclaring 3rrays
Lie other variables in Java$ an array must have a speci%ic type lie byte$ int$ String or double.
-nly variables o% the appropriate type can be stored in an array. Rou cannot have an array that
!ill store both ints and Strings$ %or instance.
Lie all other variables in Java an array must be declared. 1hen you declare an array variable
you su%%i) the type !ith [] to indicate that this variable is an array. Dere are some e)amples>
int[] @
'loat[] yt
String[] names
&n other !ords you declare an array lie you.d declare any other variable e)cept you append
bracets to the end o% the variable type.
3llocating 3rrays
<eclaring an array merely says !hat it is. &t does not create the array. 'o actually create the array
"or any other object# use the ne! operator. 1hen !e create an array !e need to tell the compiler
ho! many elements !ill be stored in it. Dere.s ho! !e.d create the variables declared above> ne(
@ * ne( int[=]
yt * ne( 'loat[>]
names * ne( String[20]
'he numbers in the bracets speci%y the dimension o% the arrayA i.e. ho! many slots it has to hold
values. 1ith the dimensions above can hold three ints$ yt can hold seven %loats and names can
hold %i%ty Strings.
&nitiali:ing 3rrays
&ndividual elements o% the array are re%erenced by the array name and by an integer !hich
represents their position in the array. 'he numbers !e use to identi%y them are called subscripts
or inde)es into the array. Subscripts are consecutive integers beginning !ith 0. 'hus the array
above has elements O0P$ O1P$ and O6P. Since !e started counting at :ero there is no O8P$ and
trying to access it !ill generate an 3rray&nde)-ut-%@ounds7)ception. sbscripts indexes @ @[0]
@[/] @[1] @[=] -rray&nde);ut;'HoundsD)ception
Rou can use array elements !herever you.d use a similarly typed variable that !asn.t part o% an
array.
Dere.s ho! !e.d store values in the arrays !e.ve been !oring !ith>
@[0] * 1
@[/] * 2
@[1] * 41
yt[K] * >.2'
names[?] * "Jred"
'his step is called initiali:ing the array or$ more precisely$ initiali:ing the elements o% the array.
Sometimes the phrase ,initiali:ing the array, !ould be reserved %or !hen !e initiali:e all the
elements o% the array.
Cor even medium si:ed arrays$ it.s un!ieldy to speci%y each element individually. &t is o%ten help%ul
to use 'or loops to initiali:e the array. Cor instance here is a loop that %ills an array !ith the
s4uares o% the numbers %rom 0 to 100.
'loat[] sBuares * ne( 'loat[/0/]
'or (int i*0 i +* 200 i33) {
sBuares[i] * i61
}
Shortcuts
1e can declare and allocate an array at the same time lie this>
int[] @ * ne( int[=]
'loat[] yt * ne( 'loat[>]
String[] names * ne( String[20]
1e can even declare$ allocate$ and initiali:e an array at the same time providing a list o% the initial
values inside bracets lie so>
int[] @ * {/L 1L =}
'loat[] yt * {0.0'L /.1'L =.?'L 4M.N>'L K2.?'L 0.0'L 2K>.M'}
'!o <imensional 3rrays
<eclaring$ 3llocating and &nitiali:ing '!o <imensional 3rrays
'!o dimensional arrays are declared$ allocated and initiali:ed much lie one dimensional arrays.
Do!ever !e have to speci%y t!o dimensions rather than one$ and !e typically use t!o nested %or
loops to %ill the array. 'or
'he array e)amples above are %illed !ith the sum o% their ro! and column indices. Dere.s some
code that !ould create and %ill such an array>
class ,ill!rray {
public static void main (String args[]) {

int[][] 5
5 * ne( int[?][2]

'or (int ro(*0 ro( + ? ro(33) {
'or (int col*0 col + 2 col33) {
5[ro(][col] * ro(3col
}
}

}

}
&n t!o-dimensional arrays 3rray&nde)-ut-%@ounds errors occur !henever you e)ceed the
ma)imum column inde) or ro! inde). Unlie t!o-dimensional * arrays$ t!o-dimensional Java
arrays are not just one-dimensional arrays inde)ed in a %unny !ay.
Multidimensional 3rrays
Rou don.t have to stop !ith t!o dimensional arrays. Java lets you have arrays o% three$ %our or
more dimensions. Do!ever chances are pretty good that i% you need more than three dimensions
in an array$ you.re probably using the !rong data structure. 7ven three dimensional arrays are
e)ceptionally rare outside o% scienti%ic and engineering applications.
'he synta) %or three dimensional arrays is a direct e)tension o% that %or t!o-dimensional arrays.
Dere.s a program that declares$ allocates and initiali:es a three-dimensional array>
class ,ill:D!rray {
public static void main (String args[]) {

int[][][] 5
5 * ne( int[?][2][=]

'or (int ro(*0 ro( + ? ro(33) {
'or (int col*0 col + 2 col33) {
'or (int ver*0 ver + = ver33) {
5[ro(][col][ver] * ro(3col3ver
}
}
}

}

}
7)ample 1 > declaring and initiali:ing 1-dimensional arrays
3n array groups elements o% the same type. &t maes it easy to manipulate the in%ormation
contained in them.
class !rrays;{
public static void main(String args[]){
// t)is declares an array named x 6it) t)e type /array o+ int/ and o+
// si<e ;3= meaning ;3 elements= x[3]= x[;] = = x[>] ( t)e +irst term
// is x[3] and t)e last term x[>] ?@5 x[;3]
int x[] = ne6 int[;3](
// print out t)e values o+ x[i] and t)ey are all eAual to 3
+or(int i=3( i4=>( i00)
Systemoutprintln(/x[/0i0/] = /0x[i])(
// assign values to x[i]
+or(int i=3( i4=>( i00)
x[i] = i( // +or example
// print t)e assigned values o+ x[i] B ;=C==>
+or(int i=3( i4=>( i00)
Systemoutprintln(/x[/0i0/] = /0x[i])(
// t)is declares an array named st t)e type /array o+ String/
// and initiali<es it
String st[]={/+irst/=/second/=/t)ird/1(
// print out st[i]
+or(int i=3( i4=C( i00)
Systemoutprintln(/st[/0i0/] = /0st[i])(
1
1
7)ample 6 > Cind the sum o% the numbers 6.0$ ?.0$ U.9$ 0.0 and U.9
class !rraysC{
public static void main(String args[]){
// t)is declares an array named +l 6it) t)e type /array o+ int/ and
// initiali<e its elements
+loat +l[] = {CD+= ED+= F>+= D3+= F>+1(
// +ind t)e sum by adding all elements o+ t)e array +l
+loat sum = 33+(
+or(int i=3( i4= E( i00)
sum = sum 0 +l[i](
// displays t)e sum
Systemoutprintln(/sum = /0sum)(
1
1
*hec that the sum displayed is 69.U.
7)ample 8 > declaring and initiali:ing 6-dimensional arrays
class !rrays:{
public static void main(String args[]){
// t)is declares a CGdimensional array named x[i][H] o+ si<e E (E elements)
// its elements are x[3][3]= x[3][;]= x[;][3] and x[;][;]
// t)e +irst index i indicates t)e ro6 and t)e second index indicates t)e
// column i+ you t)inI o+ t)is array as a matrix
int x[][] = ne6 int[C][C](
// print out t)e values o+ x[i][H] and t)ey are all eAual to 33
+or(int i=3( i4=;( i00)
+or(int H=3( H4=;( H00)
Systemoutprintln(/x[/0i0/=/0H0/] = /0x[i][H])(
// assign values to x[i]
+or(int i=3( i4=;( i00)
+or(int H=3( H4=;( H00)
x[i][H] = i0H( // +or example
// print t)e assigned values to x[i][H]
+or(int i=3( i4=;( i00)
+or(int H=3( H4=;( H00)
Systemoutprintln(/x[/0i0/=/0H0/] = /0x[i][H])(
// t)is declares a CGdimensional array o+ type String
// and initiali<es it
String st[][]={{/ro6 3 column 3/=/ro6 3 column ;/1= // +irst ro6
{/ro6 ; column 3/=/ro6 ; column ;/11( // second ro6
// print out st[i]
+or(int i=3( i4=;( i00)
+or(int H=3( H4=;( H00)
Systemoutprintln(/st[/0i0/=/0H0/] = /0st[i][H])(
1
1
.lasses and Objects
Collo!ing the principles o% -bject -riented ;rogramming "--;#$ everything in Java is either a
class$ a part o% a class$ or describes ho! a class behaves. -bjects are the physical instantiations
o% classes. 'hey are living entities !ithin a program that have independent li%ecycles and that are
created according to the class that describes them. Just as many buildings can be built %rom one
blueprint$ many objects can be instantiated %rom one class. Many objects o% di%%erent classes can
be created$ used$ and destroyed in the course o% e)ecuting a program. ;rogramming languages
provide a number o% simple data types lie int$ %loat and String. Do!ever very o%ten the data you
!ant to !or !ith may not be simple ints$ %loats or Strings. *lasses let programmers de%ine their
o!n more complicated data types.
3ll the action in Java programs taes place inside class blocs$ in this case the
Dello1orld class. &n Java almost everything o% interest is either a class itsel% or belongs to a
class. Methods are de%ined inside the classes they belong to. 7ven basic data primitives lie
integers o%ten need to be incorporated into classes be%ore you can do many use%ul things !ith
them. 'he class is the %undamental unit o% Java programs. Cor instance consider the %ollo!ing
Java program>
class 8elloJorld {
public static void main (String args[]) {
System.out.println("Hello World")
}
}
class AoodbyeWorld {
public static void main (String args[]) {
System.out.println("Aoodbye $ruel World!")
}
}
Save this code in a single %ile called hellogoodbye.java in your javahtml directory$ and compile it
!ith the command javac hellogoodbye.java. 'hen list the contents o% the directory. Rou !ill see
that the compiler has produced t!o separate class %iles$ Dello1orld.class and
Goodbye1orld.class. %avac #ellogoodbye.%ava
'he second class is a completely independent program. 'ype %ava AoodbyeWorld and then
type %ava HelloWorld. 'hese programs run and e)ecute independently o% each other although
they e)ist in the same source code %ile.
*lass Synta)
Use the %ollo!ing synta) to declare a class in Java>
//*ontents o% Some*lass5ame.java
O public P O " abstract X %inal # P class Some*lass5ame O e)tends Some;arent*lass P O implements
Some&nter%aces P
E
// variables and methods are declared !ithin the curly braces
H
M 3 class can have public or de%ault "no modi%ier# visibility.
M &t can be either abstract$ %inal or concrete "no modi%ier#.
M &t must have the class ey!ord$ and class must be %ollo!ed by a legal identi%ier.
M &t may optionally e)tend one parent class. @y de%ault$ it !ill e)tend java.lang.-bject.
M &t may optionally implement any number o% comma-separated inter%aces.
M 'he class.s variables and methods are declared !ithin a set o% curly braces .EH..
M 7ach .java source %ile may contain only one public class. 3 source %ile may contain any number
o% de%ault visible classes.
M Cinally$ the source %ile name must match the public class name and it must have a .java su%%i).
Dere is an e)ample o% a Dorse class. Dorse is a subclass o% Mammal$ and it implements the
Doo%ed inter%ace.
public class Dorse e)tends Mammal implements Doo%ed
E
//Dorse.s variables and methods go here
H
Lets tae one more e)ample o% 1hy use *lasses and -bjects. Cor instance let.s suppose your
program needs to eep a database o% !eb sites. Cor each site you have a name$ a U2L$ and a
description.
class (ebsite {
String name
String url
String description
}
'hese variables "name$ url and description# are called the members o% the class. 'hey tell you
!hat a class is and !hat its properties are. 'hey are the nouns o% the class. members. 3 class
de%ines !hat an object is$ but it is not itsel% an object. 3n object is a speci%ic instance o% a class.
'hus !hen !e create a ne! object !e say !e are instantiating the object. 7ach class e)ists only
once in a program$ but there can be many thousands o% objects that are instances o% that class.
'o instantiate an object in Java !e use the ne( operator. Dere.s ho! !e.d create a ne! !eb site>
(ebsite ) * ne( (ebsite()
-nce !e.ve got a !ebsite !e !ant to no! something about it. 'o get at the member variables o%
the !ebsite !e can use the . operator. 1ebsite has three member variables$ name$ url and
description$ so ) has three member variables as !ell$ ).name$ ).url and ).description. 1e can use
these just lie !e.d use any other String variables. Cor instance>

(ebsite ) * ne( (ebsite()
).name * "'ree#avaguide.com"
).url * "#ttpO!!(((.'ree%avaguide.com"
).description * "- Pava .rogramming Website"

System.out.println().name 3 " at " 3 ).url 3 " is " 3
).description)
1
JA,A %utorial & .lass #eclaration
& simple *ava class declaration with constrctor declaration!
class simple {
!! $onstructor
simple(){
p * /
B * 1
r * =
}
int pLBLr
}
+n class declaration, yo can declare methods of the class!
class simple {
!! $onstructor
simple(){
p * /
B * 1
r * =
}
int pLBLr
public int add:umbers(int var/L int var1L int var=)
{
return var/ 3 var1 3 var=
}
public void display5essage()
{
System.out.println(""isplay 5essage")
}
}
To invoke the class, you can create the new instance of the class:
// 'o create a ne! instance class
Simple sim K new Simple"#A
// 'o access the methods o% the class
sim.add5umbers"0$1$6#
// 'o sho! the result o% the add5umbers
System6out6println",'he result is , + &nteger.toString"add5umbers"0$1$6###A
"he complete listing of class declaration!
class simple {
!! $onstructor
simple(){
p * /
B * 1
r * =
}
int pLBLr
public int add:umbers(int var/L int var1L int var=)
{
return var/ 3 var1 3 var=
}
public void display5essage()
{
System.out.println(""isplay 5essage")
}
}
class e)ample/{
public static void main(String args[])
{
!! 9o create a ne( instance class
Simple sim * ne( Simple()
!! 9o s#o( t#e result o' t#e add:umbers
System.out.println("9#e result is " 3
&nteger.toString(add:umbers(2L/L1)))
!! 9o display message
sim.display5essage()
}
}
/nterfaces
'here is one thing in Java source code that is neither a class nor a member o% a class. 'hat.s an
inter%ace. 3n inter%ace de%ines methods that a class implements. &n other !ords it declares !hat
certain classes do. Do!ever an inter%ace itsel% does nothing. 3ll the action at least$ happens
inside classes. & class may implement one or more interfaces. "his means that the class
sbscribes to the promises made by those interfaces. -ince an interface promises certain
methods, a class implementing that interface will need to provide the methods specified by the
interface. "he methods of an interface are abstract ## they have no bodies. .enerally, a class
implementing an interface will not only match the method specifications of the interface, it will
also provide bodies ## implementations ## for its methods.

(or example, a -coreConter class might meet the contract specified by the Conting
interface!
interface Conting
/
abstract void increment()0
abstract int get1ale()0
2
-o might a -topwatch, althogh it might have a totally different internal representation. 3oth
wold have increment() and get1ale() methods, bt the bodies of these methods might loo%
4ite different. (or example, a -coreConter for a bas%etball game might implement increment()
so that it conts by 5 points each time, while a -topwatch might call its own increment() method
even if no one else does.
& class that implements a particlar interface mst declare this explicitly!
class -coreConter implements Conting /
....
2
+f a class implements an interface, an instance of that class can also be treated as thogh its type
were that interface. (or example, it can be labeled with a name whose declared type is that
interface. (or example, an instance of class -coreConter can be labeled with a name of type
Conting. +t will also answer tre when as%ed whether it6s an instanceof that interface type! if
my-coreConter is a -coreConter, then my-coreConter instanceof Conting is tre. -imilarly,
yo can pass or retrn a -coreConter whenever a Conting is re4ired by a method signatre.
"he generality of interfaces and the inclsion of mltiple implementations within a single
(interface) type is an extremely powerfl featre. (or example, yo can se a name of type
Conting to label either an instance of -coreCOnter or an instance of -topwatch (and se its
increment() and get1ale() methods) withot even %nowing which one yo6ve got.
PA!%&+
*atching 7)ceptions
Cile &/- and Streams
Do! to mae e)ecutable jar %iles in J<=1.8.1S
.atching "xceptions
3n e)ception is a point in the code !here something out o% the ordinary has happened and the
regular %lo! o% the program needs to be interruptedA an e)ception is not necessarily an error. 3
method !hich has run into such a case !ill thro! an e)ception using the thro!"7)ception*lass#
method. 1hen an e)ception is thro!n it must be caught by a catch statement that should sit right
a%ter a try statement.
// 5)is is t)e 8ello program in 9ava
class Hello {
public static void main (String args[]) {

!6 :o( letGs say #ello 6!
System.out.print("Hello ")
System.out.println(args[0])
}
}
&% you run the program !ithout giving it any command line arguments$ then the runtime system
generates an e)ception something lie$
D)ception in t#read "main" %ava.lang.-rray&nde);ut;'HoundsD)ception at
Hello.main($OQ%ava#tmlQHello.%avaO>)
Since !e didn.t give Dello any command line arguments there !asn.t anything in args[0].
'here%ore Java iced bac this not too %riendly error message about an
,3rray&nde)-ut-%@ounds7)ception.,
!e can %i) this problem by testing the length o% the array be%ore !e try to access its %irst element
"using array.length#. 'his !ors !ell in this simple case$ but this is %ar %rom the only such potential
problem.
0hat is an "xception C
Let us see !hat happens !hen an e)ception occurs and is not handled properly
1hen you compile and run the %ollo!ing program
public class 'estE
public static void main"String strOP#E
int y K 0A
int ) K 1A
// a division by 0 occurs here.
int : K )/yA
System.out.println",a%ter didvision,#A
H
H
'he e)ecution o% the 'est stops and this is caused by the division by :ero at - )/y - an e)ception
has been thro!n but has not been handled properly.
How to handle an "xception C
'o handle an 7)ception$ enclose the code that is liely to thro! an e)ception in a try bloc and
%ollo! it immediately by a catch clause as %ollo!s
public class 'estE
public static void main"String strOP#E
int y K 0A
int ) K 1A
// try bloc to ,S77, i% an e)ception occurs
tryE
int : K )/yA
System.out.println",a%ter didvision,#A
// catch clause belo! handles the
// 3rithmetic7)ception generated by
// the division by :ero.
H catch "3rithmetic7)ception ae#
ESystem.out.println", attempt to divide by 0,#AH
System.out.println", a%ter catch ,#A
H
H
'he output o% the above program is as %ollo!s
attempt to divide by 0
a%ter catch
the statement - System.out.println",a%ter didvision,# - is 5-' e)ecuted$ once an e)ception is
thro!n$ the program control moves out o% the try bloc into the catch bloc.
'he goal o% e)ception handling is to be able to de%ine the regular %lo! o% the program in part o% the
code !ithout !orrying about all the special cases. 'hen$ in a separate bloc o% code$ you cover
the e)ceptional cases. 'his produces more legible code since you don.t need to interrupt the %lo!
o% the algorithm to chec and respond to every possible strange condition. 'he runtime
environment is responsible %or moving %rom the regular program %lo! to the e)ception handlers
!hen an e)ceptional condition arises.
&n practice !hat you do is !rite blocs o% code that may generate e)ceptions inside try-catch
blocs. Rou try the statements that generate the e)ceptions. 1ithin your try bloc you are %ree to
act as i% nothing has or can go !rong. 'hen$ !ithin one or more catch blocs$ you !rite the
program logic that deals !ith all the special cases.
'o start a section o% code !hich might %ail or not %ollo! through you start a try clause>
try
E
// Section o% code !hich might %ail
H
'he try statement is needed in case o% an e)ception. &% the read %ails in some !ay it !ill thro! an
e)ception o% type java.io.&-7)ception. 'hat e)ception must be caught in this method$ or the
method can declare that it !ill continue thro!ing that message. 7)ception handling is a very
po!er%ul tool$ you can use it to catch and thro! e)ceptions and thus group all your error handling
code very !ell and mae it much more readable in larger more comple) applications. 3%ter the try
section there must e)ist one or more catch statements to catch some or all o% the e)ceptions that
can happen !ithin the try bloc. 7)ceptions that are not caught !ill be passed up to the ne)t
level$ such as the %unction that called the one !hich thre! the e)ception$ and so on. .
try
E
// Section o% code !hich might %ail
H
catch "7)ception1'hat*anDappen 7#
E
// things to do i% this e)ception !as thro!n..
H
catch "7)ception6'hat*anDappen 7#
E
// things to do i% this e)ception !as thro!n..
H
Dere.s an e)ample o% e)ception handling in Java using the Dello 1orld program above>
Source *ode
// 5)is is t)e 8ello program in 9ava
class D)ceptionalHello {
public static void main (String args[]) {

!6 :o( letGs say #ello 6!
try {
System.out.println("Hello " 3 args[0])
}
catc# (D)ception e) {
System.out.println("Hello (#oever you are")
}
}
}
Rou may or may not print an error message. &% you !rite an e)ception handler and you don.t
e)pect it to be called$ then by all means put a
System.out.println("DrrorO " 3 e)
'his has the %olo!ing advantages over handling your errors internally>
Rou can react to an error in custom de%ined !ay. 3 read error does not mean that the
program should crash.
Rou can !rite code !ith no !orry about %ailure !hich !ill be handled by the users o% your
class.
Rou can group your error handling code much better.
Rou can mae your application more transactional %ocused !ith nested try catch blocs>
3 simple Java code !hich demonstrates the e)ception handling in Java
'efer to the java &7+ docment to see all exception types that can be handled in *ava.
Source *ode
public class e)cep1
{
public static void main(String args[])
{
int i *0
!!"eclare an array o' strings
String Ho) [] * {"Hoo@"L ".en"L ".encil"}
(#ile(i+?)
{
try
{
System.out.println(Ho)[i])
}
catc#(-rray&nde);ut;'HoundsD)ception e)
{
System.out.println("Subscript .roblem " 3
e)
i33
}
'inally
{
System.out.println("9#is is al(ays
printed.")
}
i33
}
}
}
8ile /5O and Streams
Rou can !rite data to a %ile instead o% the computer screen. Rou can !rite certain data to a %ile
!hile still putting other data on the screen. -r you may need access to multiple %iles
simultaneously. -r you may !ant to 4uery the user %or input rather than accepting it all on the
command line. -r maybe you !ant to read data out o% a %ile that.s in a particular %ormat. &n Java
all these methods tae place as streams. + , Using Cile &/- streams. 'he
System.out.println() statement !e.ve been using all along is an implementation o%
Streams.
& program that writes a string to a file
&n order to use the Java %ile classes$ !e must import the Java input/output pacage "java.io# in the
%ollo!ing manner
import java.io.MA
&nside the main method o% our program$ !e must declare a Cile-utputStream object. &n this case$
!e !ish to !rite a string to the %ile$ and so !e create a ne! ;rintStream object that taes as its
constructor the e)isting Cile-utputStream. 3ny data !e send %rom ;rintStream !ill no! be
passed to the Cile-utputStream$ and ultimately to dis. 1e then mae a call to the println
method$ passing it a string$ and then close the connection.
Source *ode
/K
K ,ile@utput
K Demonstration o+ ,ile@utputStream and LrintStream classes
K/
import HavaioK(
class ,ile@utput
{
public static void main(String args[])
{
,ile@utputStream out( // declare a +ile output obHect
LrintStream p( // declare a print stream obHect
try
{
// -reate a ne6 +ile output stream connected to /my+iletxt/
out = ne6 ,ile@utputStream(/my+iletxt/)(
// -onnect print stream to t)e output stream
p = ne6 LrintStream( out )(
pprintln (/5)is is 6ritten to a +ile my,iletxt/)(
pclose()(
1
catc) ('xception e)
{
Systemerrprintln (/'rror 6riting to t)e +ile my,iletxt/)(
1
1
1
&nteractively communicating !ith the user
7rogram as%ing the ser for their name and then prints a personali8ed greeting.
Source *ode
import HavaioK(
class .ersonalHello {
public static void main (String args[])
{

byte name[] * ne( byte[/00]
int nrRread * 0
System.out.println("Sour name .leaseT")
try {
nrRread * System.in.read(name)
System.out.print("Hello ")
System.out.(rite(nameL0LnrRread)
}
catc# (&;D)ception e) {
System.out.print("& did not get your name.")
}

}

}
&n code that does any signi%icant input or output you.ll !ant to begin by importing all the various
java.io classes. import.java.io.MA Most o% the reading and !riting you do in Java !ill be done !ith
bytes. Dere !e.ve started !ith an array o% bytes that !ill hold the user.s name.
Cirst !e print a 4uery re4uesting the user.s name. 'hen !e read the user.s name using the
System.in.read() method. 'his method taes a byte array as an argument$ and places
!hatever the user types in that byte array. 'hen$ lie be%ore$ !e print ,Dello., Cinally !e print the
user.s name.
'he program doesn.t actually see !hat the user types until he or she types a carriage return. 'his
gives the user the chance to bacspace over and delete any mistaes. -nce the return ey is
pressed$ everything in the line is placed in the array.
2eading 5umbers
-%ten strings aren.t enough. 3 lot o% times you.ll !ant to as the user %or a number as input. 3ll
user input comes in as strings so !e need to convert the string into a number.
'he get:e)t&nteger() method that !ill accept an integer %rom the user. Dere it is>
static int get:e)t&nteger() {

String line

"ata&nputStream in * ne( "ata&nputStream(System.in)
try {
line * in.readCine()
int i * &nteger.value;'(line).intUalue()
return i
}
catc# (D)ception e) {
return 4/
}

} !! get:e)t&nteger ends #ere
2eading Cormatted <ata
&t.s o%ten the case that you !ant to read not just one number but multiple numbers. Sometimes
you may need to read te)t and numbers on the same line. Cor this purpose Java provides the
Stream'oeni:er class.
1riting a te)t %ile
Sometimes you !ant to save your output in a %ile. 'o do this !e.ll need to learn ho! to !rite data
to a %ile.
Source *ode
// Jrite t)e ,a)ren)eit to -elsius table in a +ile
import %ava.io.6
class Ja#r9o$elsius {
public static void main (String args[]) {
double 'a#rL celsius
double lo(erL upperL step
lo(er * 0.0 !! lo(er limit o' temperature table
upper * =00.0 !! upper limit o' temperature table
step * 10.0 !! step siIe
'a#r * lo(er

try {
Jile;utputStream 'out * ne( Jile;utputStream("test.out")
!! no( to t#e Jile;utputStream into a .rintStream
.rintStream my;utput * ne( .rintStream('out)

(#ile ('a#r +* upper) { !! (#ile loop begins #ere
celsius * 2.0 6 ('a#r4=1.0) ! M.0
my;utput.println('a#r 3 " " 3 celsius)
'a#r * 'a#r 3 step
} !! (#ile loop ends #ere

} !! try ends #ere
catc# (&;D)ception e) {
System.out.println("DrrorO " 3 e)
System.e)it(/)
}

} !! main ends #ere
}
'here are only three things necessary to !rite %ormatted output to a %ile rather than to the
standard output>
1. -pen a (ileOtpt-tream using a line lie
Jile;utputStream 'out * ne( Jile;utputStream("test.out")
'his line initiali:es the Cile-utputStream !ith the name o% the %ile you !ant to !rite into.
6. *onvert the Cile-utputStream into a 7rint-tream using a statement lie
.rintStream my;utput * ne( .rintStream('out)
'he ;rintStream is passed the Cile-utputStream %rom step 1.
!. &nstead o% using System.out.println() use my;utput.println(). System.out
and my;utput are just di%%erent instances o% the .rintStream class. 'o print to a
di%%erent .rintStream !e eep the synta) the same but change the name o% the
.rintStream.
2eading a te)t %ile
5o! that !e no! ho! to !rite a te)t %ile$ let.s try reading one. 'he %ollo!ing code accepts a
series o% %ile names on the command line and then prints those %ilenames to the standard output
in the order they !ere listed.
// *mitate t)e &nix cat utility
import %ava.io.6
class cat {
public static void main (String args[]) {

String t#isCine
!!Coop across t#e arguments
'or (int i*0 i + args.lengt# i33) {

!!;pen t#e 'ile 'or reading
try {
Jile&nputStream 'in * ne( Jile&nputStream(args[i])
!! no( turn t#e Jile&nputStream into a "ata&nputStream
try {
"ata&nputStream my&nput * ne( "ata&nputStream('in)

try {
(#ile ((t#isCine * my&nput.readCine()) !* null) { !! (#ile
loop begins #ere
System.out.println(t#isCine)
} !! (#ile loop ends #ere
}
catc# (D)ception e) {
System.out.println("DrrorO " 3 e)
}
} !! end try
catc# (D)ception e) {
System.out.println("DrrorO " 3 e)
}

} !! end try
catc# (D)ception e) {
System.out.println("'ailed to open 'ile " 3 args[i])
System.out.println("DrrorO " 3 e)
}
} !! 'or end #ere

} !! main ends #ere
}
How to mae executable jar files in J#$'6)6'C
&nstructions %or creating an 7)ecutable .jar %ile
Mae or modi%y the Mani%est.MC to RourMani%est.MC.
1# Rour*lass5ame1ithMain is the class name "case sensitive# !ithout .class e)tension
6# 5o e)tra spaces %ollo!ing the Rour*lass5ame !ithMain.
Mani%est-(ersion>1.0
Main-*lass> Rour*lass5ame1ithMain
*reated-by>1.6"Sun Microsystems &nc.#
-n *ommand line > type the %ollo!ing
jar cv%m RourJarCile5ame.jar RourMani%est.MCM
or
jar cv%m RourJarCile5ame.jar RourMani%est.MC -* classes your*lass;ath
<rag-drop the RourJarCile5ame.jar to your destop double clic it$ it runs
&% your program only has System.out.println ",!hatever,#A statements$ it !ill
display nothing. 'he same !ill happen !hen you run it useing java at command line
Rou need some !indo!s code to see it run
&nstructions %or creating a .jar %ile. jar utility comes !ith your J<=1.6.6 &t compresses your %ile
similar to :ip utility$ and more Java.
Rou can use it on any machine installed J<=
*reate a %older name it anything
Mae that %older your current directory
put all your %iles %or turning in "do not put any e)tra# in that directory.
@e sure to put your html %ile$ i% there is one
3t your dos prompt$ !hile you are in the directory that you created $ type in>
jar cv% ;rj06.jarM
'his !ill tae 3LL the %iles in the directory including subdirectories and place them in a .jar %ile
;rj06 that can be replaced by any o% your desired jar %ile name.
'o test it$ you can e)tract the contents o% jar %ile by typing>
jar )v% ;rj06.jar

You might also like