Sie sind auf Seite 1von 76

OBJECT oriented program with java Module-I Object oriented concepts Introduction: Java is a high-level, third generation programming

language, like C, FORTRAN, malltalk, !erl, and man" others# $no%ing ho% to program in C or, &etter "et, C'', %ill certainl" help "ou to learn Java more (uickl", &ut "ou don)t need to kno% C to learn Java# A Java compiler %on)t compile C code, and most large C programs need to &e changed su&stantiall" &e*ore the" can &ecome Java programs# +hat)s most special a&out Java in relation to other programming languages is that it lets "ou %rite special programs called applets that can &e do%nloaded *rom the Internet and pla"ed sa*el" %ithin a %e& &ro%ser# Java language is called as an O&,ect-Oriented !rogramming language and &e*ore &egining *or Java, %e have to learn the concept o* OO!s -O&,ect-Oriented !rogramming.# There are some &asic concepts o* o&,ect oriented programming as *ollo%s: /# O&,ect 0# Class 1# 2ata a&straction 3# 2ata encapsulation 4# Inheritance 5# !ol"morphism 6# 2"namic &inding /# O&,ect: O&,ects are important runtime entities in o&,ect oriented method# The" ma" characteri7e a location, a &ank account, and a ta&le o* data or an" entr" that the program must handle# 8ach o&,ect holds data and code to operate the data# O&,ect can interact %ithout having to identi*" the details o* each other9s data or code# It is su**icient to identi*" the t"pe o* message received and the t"pe o* repl" returned &" the o&,ects# 0# Classes

/|!age

A class is a set o* o&,ects %ith similar properties -attri&utes., common &ehaviour -operations., and common link to other o&,ects# The complete set o* data and code o* an o&,ect can &e made a user de*ined data t"pe %ith the help o* class# The o&,ects are varia&le o* t"pe class# A class is a collection o* o&,ects o* similar t"pe# Classes are user de*ined data t"pes and %ork like the &uild in t"pe o* the programming language# Once the class has &een de*ined, %e can make an" num&er o* o&,ects &elonging to that class# 8ach o&,ect is related %ith the data o* t"pe class %ith %hich the" are *ormed# As %e learned that, the classi*ication o* o&,ects into various classes is &ased on its properties - tates. and &ehaviour -methods.# Classes are used to distinguish are t"pe o* o&,ect *rom another# The important thing a&out the class is to identi*" the properties and procedures and applica&ilit" to its instances# 1# 2ata A&straction 2ata a&straction re*ers to the act o* representing important description %ithout including the &ackground details or e:planations# Classes use the concept o* a&straction and are de*ined as a list o* a&stract attri&utes such as si7e, cost and *unctions operate on these attri&utes# The" summari7e all the important properties o* the o&,ects that are to &e created# Classes use the concepts o* data a&straction and it is called as A&stract 2ata T"pe -A2T.# 3# 2ata 8ncapsulation 2ata 8ncapsulation means %rapping o* data and *unctions into a single unit -i#e# class.# It is most use*ul *eature o* class# The data is not eas" to get to the outside %orld and onl" those *unctions %hich are enclosed in the class can access it# These *unctions provide the &oundar" &et%een O&,ect9s data and program# This insulation o* data *rom direct access &" the program is called as 2ata hiding# 4# Inheritance Inheritance is the process &" %hich o&,ects o* one class can get the properties o* o&,ects o* another class# Inheritance means one class o* o&,ects inherits the data and &ehaviours *rom another class# Inheritance maintains the hierarchical classi*ication in %hich a class inherits *rom its parents# Inheritance provides the important *eature o* OO! that is reusa&ilit"# That means %e can include additional characteristics to an e:isting class %ithout modi*ication# This is possi&le deriving a ne% class *rom e:isting one#

0|!age

In other %ords, it is propert" o* o&,ect-oriented s"stems that allo% o&,ects to &e &uilt *rom other o&,ects# Inheritance allo%s openl" taking help o* the commonalit" o* o&,ects %hen constructing ne% classes# Inheritance is a relationship &et%een classes %here one class is the parent class o* another -derived. class# The derived class holds the properties and &ehaviour o* &ase class in addition to the properties and &ehaviour o* derived class# 5# !ol"morphism -!ol" means ;man" and morph means ;*orm.# !ol"morphism means the a&ilit" to take more than one *orm# !ol"morphism pla"s a main role in allocate o&,ects having di**erent internal structures to share the same e:ternal inter*ace# This means that a general class o* operations ma" &e accessed in the same manner even though speci*ic activities associated %ith each operation ma" di**er# !ol"morphism is &roadl" used in implementing inheritance# It means o&,ects that can take on or assume man" di**erent *orms# !ol"morphism means that the same operations ma" &ehave di**erentl" on di**erent classes# <ooch de*ines pol"morphism as the relationship o* o&,ects man" di**erent classes &" some common super class# !ol"morphism allo%s us to %rite generic, reusa&le code more easil", &ecause %e can speci*" general instructions and delegate the implementation detail to the o&,ects involved# 6# 2"namic <inding <inding re*ers to the linking o* a procedure call to the code to &e e:ecuted in response to the call# 2"namic &inding means that the code related %ith a given procedure call is not kno%n until the time o* the call at run time# 2"namic &inding is associated pol"morphism and inheritance#

1|!age

Java

istor!"

Java is a general-purpose, o&,ect-oriented programming language developed &" un =icros"stems o* > A in /??/#Originall" called Oak &" James @osling -one o* the inventor o* the language.# Java %as invented *or the development o* so*t%are *or consumer electronic devices like TAs, tosters, etc# The main aim had to make ,ava simple, porta&le and relia&le# Java Authors: James , Arthur Aan , and others Follo%ing ta&le sho%s the "ear and &eginning o* Java#

3|!age

Bear /??C

!rogress un decided to developed so*t%are that could &e used *or electronic devices# And the pro,ect called as @reen !ro,ect head &" James @osling# Announcement o* a ne% language named ;Oak The team veri*ied the application o* their ne% language to manage a list o* home appliances using a hand held device# The +orld +ide +e& appeared on the Internet and trans*ormed the te:t-&ased inter*ace to a graphical rich environment# The team developed a ne% +e& &ro%sed called ;Dot Java to locate and run Applets# Oak %as renamed to Java, as it did not survive ;legal registration# =an" companies such as Netscape and =icroso*t

/??/ /??0

/??1

/??3

/??4

/??5

announced their support *or Java# Java language is no% *amous *or Internet programming as %ell as a general purpose OO language# un releases Java 2evelopment $it-J2$ /#/. un releases o*t%are 2evelopment $it tandard 8nterprise

/??6 /??E /???

- 2$ /#0. un releases Java 0 plat*orm 8dition -J0 8. and 8dition-J088.# J0 8 %ith 2$ /#1 %as released# J0 8 %ith 2$ /#3 %as released# J0 8 %ith J2$ 4#C %as released#

0CCC 0CC0 0CC3

4|!age

J#$# %eatures" As %e kno% that the Java is an o&,ect oriented programming language developed &" un =icros"stems o* > A in /??/# Java is *irst programming language %hich is not attached %ith an" particular hard%are or operating s"stem# !rogram developed in Java can &e e:ecuted an"%here and on an" s"stem# Features o* Java are as *ollo%s: /# Compiled and Interpreted 0# !lat*orm Independent and porta&le 1# O&,ect- oriented 3# Ro&ust and secure 4# 2istri&uted 5# Familiar, simple and small 6# =ultithreaded and Interactive E# Digh per*ormance ?# 2"namic and 8:tensi&le /# Compiled and Interpreted: <asicall" a computer language is either compiled or interpreted# Java comes together &oth these approach thus making Java a t%o-stage s"stem# Java compiler translates Java code to <"te code instructions and Java Interpreter generate machine code that can &e directl" e:ecuted &" machine that is running the Java program# 0# !lat*orm Independent and porta&le: Java supports the *eature porta&ilit"# Java programs can &e easil" moved *rom one computer s"stem to another and an"%here# Changes and upgrades in operating s"stems, processors and s"stem resources %ill not *orce an" alteration in Java programs# 5|!age

This is reason %h" Java has &ecome a trend" language *or programming on Internet %hich interconnects di**erent kind o* s"stems %orld%ide# Java certi*ies porta&ilit" in t%o %a"s# First %a" is, Java compiler generates the &"tecode and that can &e e:ecuted on an" machine# econd %a" is, si7e o* primitive data t"pes are machine independent# 1# O&,ect- oriented: Java is trul" o&,ect-oriented language# In Java, almost ever"thing is an O&,ect# All program code and data e:ist in o&,ects and classes# Java comes %ith an e:tensive set o* classesF organi7e in packages that can &e used in program &" Inheritance# The o&,ect model in Java is trou&le-*ree and eas" to enlarge# 3# Ro&ust and secure:Java is a most strong language %hich provides man" securities to make certain relia&le code# It is design as gar&age Gcollected language, %hich helps the programmers virtuall" *rom all memor" management pro&lems# Java also includes the concept o* e:ception handling, %hich detain serious errors and reduces all kind o* threat o* crashing the s"stem# ecurit" is an important *eature o* Java and this is the strong reason that programmer use this language *or programming on Internet# The a&sence o* pointers in Java ensures that programs cannot get right o* entr" to memor" location %ithout proper approval# 4# 2istri&uted: Java is called as 2istri&uted language *or construct applications on net%orks %hich can contri&ute &oth data and programs# Java applications can open and access remote o&,ects on Internet easil"# That means multiple programmers at multiple remote locations to %ork together on single task# 5# imple and small: Java is ver" small and simple language# Java does not use pointer and header *iles, go to statements, etc# It eliminates operator overloading and multiple inheritance# 6# =ultithreaded and Interactive: =ultithreaded means managing multiple tasks simultaneousl"# Java maintains multithreaded programs# That means %e need not %ait *or the application to complete one task &e*ore starting ne:t task# This *eature is help*ul *or graphic applications# E# Digh per*ormance: Java per*ormance is ver" e:traordinar" *or an interpreted language, ma,orl" due to the use o* intermediate &"tecode# Java architecture is also designed to reduce overheads during runtime# The incorporation o* multithreading improves the e:ecution speed o* program# 6|!age

?# 2"namic and 8:tensi&le: Java is also d"namic language# Java is capa&le o* d"namicall" linking in ne% class, li&raries, methods and o&,ects# Java can also esta&lish the t"pe o* class through the (uer" &uilding it possi&le to either d"namicall" link or a&ort the program, depending on the repl"# Java program is support *unctions %ritten in other language such as C and C'', kno%n as native methods# COM&#'I(O) I) J#$# #)* C++ Java Java is true O&,ect-oriented language# Java does not support operator overloading# It supports la&els %ith loops and statement &locks Java does not have template classes as in C''# Java compiled into &"te code *or the is independent on operating s"stem# 5 Java does not support multiple inheritance o* classes &ut it supports 6 E ? /C // inter*ace# Runs in a protected virtual machine# Java does not support glo&al varia&le# 8ver" varia&le should declare in class# Java does not use pointer# It trictl" en*orces an o&,ect oriented programming paradigm# There are no header *iles in Java# C'' C'' is &asicall" C %ith O&,ect-oriented e:tension# C'' supports operator overloading# It supports goto statement# C'' has template classes# ource code can &e %ritten to &e plat*orm o* plat*orm#C'' t"picall" compiled into machine code# C'' supports multiple inheritance o* classes# 8:poses lo%-level s"stem *acilities# C'' support glo&al varia&le# C'' uses pointer# It Allo%s &oth procedural programming and o&,ect-oriented programming# +e have to use header *ile in C''#

/ 0 1 3 4

Java Airtual =achine# The source code independent and %ritten to take advantage

JAAA 2evelopment $it -J2$. J2$ is so*t%are, %hich hold all the components o* JAAA program# It means, it holds the develop mint kit o* JAVA program# All the components reside %ithin the H&inI director" o* HJ2$I# The components are as *ollo%s# E|!age

JAAAC -JAAA Compiler. JAAA -JAAA Interpreter. JAAA! -JAAA 2isa&ler. JAAA doc -JAAA 2ocument. Applet vie%er -JAAA %e& <ro%ser.

Dence, to develop the JAVA program, %e must have J2$ so*t%are in our s"stem# J2$ comes in di**erent versions J2$/#/, J2$/#0, J2$/#1, J2$/#3, - - - - - - - J2$0#1, J2$0#5# Actuall" JAAA program is divided into t%o t"pes A!I A!!J8T A!I A!I stands *or application program inter*ace# A!I program runs independentl" through compiler K Interpreter *rom the 2os G prompt# It has the main -. method# >sing di**erent per G de*ined A!I packages develops A!I program# A!!J8T It is %indo%s &ased program that is generall" used to develop the %e& page# It generall" used to develop the %e& pages# It cannot &e run indecentl" through interpreter &ecause it has no main -. method# It can &e run through JAAA %e& &ro%ser %ith the help o* DT=J *ile# Java 8nvironment: Java environment includes a num&er o* development tools, classes and methods# The development tools are part o* the s"stem kno%n as Java 2evelopment $it -J2$. and the classes and methods are part o* the Java tandard Ji&rar" -J J., also kno%n as the Application !rogramming Inter*ace -A!I.# Java 2evelopment kit -J2$. G The J2$ comes %ith a set o* tools that are used *or developing and running Java program# It includes: /# Appletvie%er- It is used *or vie%ing the applet. 0# Javac-It is a Java Compiler. 1# Java-It is a ,ava interpreter. 3# Javap-Java diassem&ler,%hich convert &"te code into program description. ?|!age

4# Javah-It is *or ,ava C header *iles. 5# Javadoc-It is *or creating DT=J document. 6# Jd&-It is Java de&ugger. For compiling and running the program %e have to use *ollo%ing commands: a. ,avac -Java compiler. In ,ava, %e can use an" te:t editor *or %riting program and then save that program %ith ;#,ava e:tension# Java compiler convert the source code or program in &"tecode and interpreter convert ;#,ava *ile in ;#class *ile# "nta:: C:L,avac *ilename#,ava I* m" *ilename is ;a&c#,ava then the s"nta: %ill &e C:L,avac a&c#,ava &. ,ava-Java Interpreter. As %e learn that, %e can use an" te:t editor *or %riting program and then save that program %ith ;#,ava e:tension# Java compiler convert the source code or program in &"tecode and interpreter convert ;#,ava *ile in ;#class *ile# "nta:: C:L,ava *ilename I* m" *ilename is a&c#,ava then the s"nta: %ill &e C:L,ava a&c CR8ATIN@ The ource FileM aving JAAA !rogram As %e kno% that JAAA is plat*orm independent language, so it has no o%n editor to %rite JAAA program# +e can %rite JAAA program in an" te:t editor -Jike Notepad, +ord!ad, 2os 82IT, 8dit !lus etc.# JAAA program is saved %ith e:tension H# JAAAI %hose primar" name must &e same as the main class name# A class under %hich main -. method reside, is kno%n as main class# ince JAAA is %indo%s &ased 2os-supported so*t%are, thatNs %h" the e:tension ma" &e o* a characters# JAAA cannot use on complete 2os-&ased "stem# H# JAAAI File is kno%n as source *ile# /C | ! a g e

=odule-0 Java programming language imple Java !rogram: class First!rogram O pu&lic static void main- tring argsPQ. O "stem#out#println-;This is m" *irst program.F R R The *ile must &e named ;First!rogram#,ava to e(uivalent the class name containing the main method# Java is case sensitive# This program de*ines a class called ;First!rogram# A class is an o&,ect oriented term# It is designed to per*orm a speci*ic task# A Java class is de*ined &" its class name, an open curl" &race, a list o* methods and *ields, and a close curl" &race# The name o* the class is made o* alpha&etical characters and digits %ithout spaces, the *irst character must &e alpha&etical# The line ;pu&lic static void main - tring PQ args . sho%s %here the program %ill start running# The %ord main means that this is the main method G The JA= starts running an" program &" e:ecuting this method *irst# The main method in ;First!rogram#,ava consists o* a single statement "stem#out#println-SThis is m" *irst programS.F The statement outputs the character &et%een (uotes to the console# A&ove e:planation is a&out ho% to %rite program and no% %e have to learn %here to %rite program and ho% to compile and run the program# For this reason, the ne:t e:planation is sho%ing the steps# /# 8dit the program &" the use o* Notepad# // | ! a g e

0# ave the program to the hard disk# 1# Compile the program %ith the ,avac command#-Java compiler. 3# I* there are s"nta: errors, go &ack to Notepad and edit the program# 4# Run the program %ith the ,ava command#-Java Interpreter. 5# I* it does not run correctl", go &ack to Notepad and edit the program# 6# +hen it sho%s result then stop# Actuall" JAAA program is divided into t%o t"pes A!I A!!J8T A!I A!I stands *or application program inter*ace# A!I program runs independentl" through compiler K Interpreter *rom the 2os G prompt# It has the main -. method# >sing di**erent per G de*ined A!I packages develops A!I program# A!!J8T It is %indo%s &ased program that is generall" used to develop the %e& page# It generall" used to develop the %e& pages# It cannot &e run indecentl" through interpreter &ecause it has no main -. method# It can &e run through JAAA %e& &ro%ser %ith the help o* DT=J *ile# CR8ATIN@ The ource FileM aving JAAA !rogram As %e kno% that JAAA is plat*orm independent language, so it has no o%n editor to %rite JAAA program# +e can %rite JAAA program in an" te:t editor -Jike Notepad, +ord!ad, 2os 82IT, 8dit !lus etc.# JAAA program is saved %ith e:tension H# JAAAI %hose primar" name must &e same as the main class name# A class under %hich main -. method reside, is kno%n as main class# ince JAAA is %indo%s &ased 2os-supported so*t%are, thatNs %h" the e:tension ma" &e o* a characters# JAAA cannot use on complete 2os-&ased "stem# H# JAAAI File is kno%n as source *ile# CO=!IJIN@ AN2 R>NNIN@ JAAA !RO@RA= Compiling O* JAAA !rogram

/0 | ! a g e

A*ter creating the source *ile, %e must have to compile the JAAA program &" using# JAAA compiler -JAAAC.# The s"nta: o* compiling JAAA program is as *ollo%s# C:LT ,avac *ile name# Java C:L,dk/#1L&inT ,avac *ile name# Java 2uring compilation process, JAAA compiler checks the s"ntactical as %ell as linking errors# I* an" errors or %arnings e:ist in our program then it displa"s all the errors and %arnings %ith their message at a time on 2os-screen# The error statement is also displa"ed %ith caret -U. sign, %hich indicts the error position on 2os-screen# 8:: 8rror: statement missingF "stem#out#print -H<ANTII.U I* our program has onl" %arnings then %e can run the program &ut it ma" e**ect in the output# I* our program has no an" errors then again the 2os-prompt %ill appear %ithout an" message# I* the compilation is success*ul, then the JAAA compiler converts %hole source code into intermediate code, kno%n as <BT8 code# <BT8 code is similar to machine code &ut not a complete machine code# The <BT8 code is created according to the processor t"pe o* our s"stem and it is holding on the primar" memor" &" the JA= -JAAA vertical =achine.# The <BT8 code holds the source code as %ell as the link *iles# It is same as the o&,ect *ile -#o&,. o* CMC''# The compilation process is as *ollo%s#

Running O* JAAA !rogram A*ter success*ul compilation, %e can run the JAAA program &" using JAAA interpreter -JAAA.# The s"nta: o* using interpreter is as *ollo%s# C:LT ,ava *ile name

/1 | ! a g e

The JAAA interpreter -JAAA. used the <BT8 code converted &" JAAA compiler and converts that <BT8 code into the =achine code according to the machine# Dence, JAAA interpreter creates the e:ecuta&le *ile o* JAAA %hose e:tension the e:ecuta&le *ile o* JAAA %hose e:tension is H# ClassI#

8:ecuta&le File -#Class.

JAAA Airtual =achine -JA=. JA= is a temporar" memor" space created on the primar" memor" -RA=., %hich holds the <BT8 Code o* JAAA program# Interpreter pick up the <BT8 code *rom this temporar" space and creates an e:ecuta&le *ile according to the machine, %hich helps in the running o* program# This temporar" are a is ,ust treated as a virtual or logical machine, &ecause it handles the ,ava program# ThatNs %h", this virtual machine is kno%n as JAAA AIRT>AJ =ACDIN8 -JA=.# The JA= can &e represented in *igure as *ollo%s#

Fig: - JA= tructure O* JAAA !rogram Jike other languages, ,ava has also a de*erent structure, %hich must &e *ollo%ed &" each JAAA program to do JAAA program propert"# The structure is as *ollo%s# 2ocumentation ection Optional /3 | ! a g e

!ackage 2eclaration ection Optional Import ection 8ssential Inter*ace 2eclaration ection Optional >ser-2e*ine Class ection Optional =ain Class ection Optional 2ocumentation ection In this section, %e can %rite the in*ormation a&out the program# All the statements are treated as the commented tatements# There are t%o "m&ols used to make comments# a. MM To make single line comment at a time# &. LV - - - - - - -VM To make comment a range o* line at a time# c. !ackage 2eclaration ection In this section, %e can create the user-de*ined packages# !ackage is a container o* holding di**erent class and a container o* holding di**erent classes and a class is a container o* holding di**erent methods# The concept o* packages is same as the header *ile o* package is same as the header *ile o* CMC''# Import ection In this section, %e use or import the pre-de*ined packages or classes# As %e kno% that JAAA is a *all" o&,ect oriented languages# o, it does are the mem&er *unction o* an" classes# o, to use the pre-de*ined methods in our program, %e must have to use the corresponding classes and packages also in our program in import section# The s"nta: o* importing package and class is as *ollo%s# Import ,ava#packagename#classnameF Or Import $e"%ord ,ava# super !ackage The *irst s"nta: stands *or a particular class +here as the second s"nta: stands *or all classes o* the given packages# All the prede*ined packages reside %ithin a super package named HJAAAI# /4 | ! a g e !ackage name package name # V F class name

The list o* pre-de*ined packages is as *ollo%s# Java# Jang -&" de*ault imported. Java#>til Java#Net Java#Applet Java#a%t Java#s%ing 8:: Import ,ava#lang# VF Import ,ava#lang#mathF Import ,ava#util#vectorF It is same as the link section o* CMC''#

Inter,ace *eclaration (ection In this section, %e can create an" num&er o* use-de*ined inter*aces# An inter*ace is a class like entr" in %hich %e can also kept varia&les and methods together# <ut the method %ithin inter*ace cannot de*ine %ithin it# -ser-*e,ine Class *eclaration (ection In this section, %e can create an" num&er o* user-de*ine classes according to our need# Main Class *eclaration (ection In this section, %e have to declare main class# It is essential part o* each JAAA program# A class, under %hich the main methods reside, is kno%n as main class# The e:ecution o* each program is started *rom the main method# method class# "n: - class Wclass nameT O pu&lic static void main -string args PQ. O /5 | ! a g e ---o, each program must have one and one main

R R NA=IN@ CONA8NTION OF JAAA !AC$A@8, CJA 8:: Jang, util, a%t, s%ing, applet etc# o* t%o or more than t%o %ords, then the *irst letter o* each %ord must &e in upper case# 8:: tring, Applet, Thread, Aector, 2ataInput team, and Jotion!ane, etc# The *irst letter o* pre-de*ined methods must &e stated %ith lo%er case# I* it is in com&ination o* t%o or more than t%o %ord must &e in upper case e:cept the *irst %ord# 8:: parseInt -., charAt -., readJine -., start -., paint -., sho%Input2ialog -. etc The a&ove naming connection must &e *ollo%ed *or pre-de*ined packages, classes and methods# <ut %e should *ollo% these rules %ith use-de*ined packages, classes and methods also# AN2 =8TDO2

All the letters o* pre-de*ined packages must &e %ritten in lo%er case# /# The *irst letter o* pre-de*ined classes must &e stated %ith upper case# I* it is in com&ination

MO*-.E-II $#'I#B.E( #)* *#T#T/&E( Aaria&les: Aaria&les are la&els that e:press a particular position in memor" and connect it %ith a data t"pe# 2eclaration o* varia&les: The *irst %a" to declare a varia&le: This speci*ies its data t"pe, and reserves memor" *or it# It assigns 7ero to primitive t"pes and null to o&,ects# dataT"pe varia&leNameF The second %a" to declare a varia&le: This speci*ies its data t"pe, reserves memor" *or it, and puts an initial value into that memor"# The initial value must &e o* the correct data t"pe# dataT"pe varia&leName X initialAalueF The *irst %a" to declare t%o varia&les: all o* the same data t"pe, reserves memor" *or each# dataT"pe varia&leNameOne, varia&leNameT%oF The second %a" to declare t%o varia&les: &oth o* the same data t"pe, reserves memor", and puts an initial value in each varia&le# /6 | ! a g e

dataT"pe varia&leNameI X initialAalueI, varia&leNameIIXinitialAalueIIF Aaria&le name: >se onl" the characters Ya9 through Y79, YA9 through YZ9, YC9 through Y?9, character Y[9, and character Y\9# A name cannot include the space character# 2o not &egin %ith a digit# A name can &e o* an" realistic length# >pper and lo%er case count as di**erent characters# A name cannot &e a reserved %ord -ke"%ord.# A name must not previousl" &e in utili7ed in this &lock o* the program#

Constant" Constant means *i:ed value %hich is not change at the time o* e:ecution o* program# In Java, there are t%o t"pes o* constant as *ollo%s: Numeric Constants Integer constant ]Real constant Character Constants ]Character constant ] tring constant

/# Integer Constant: An Integer constant re*ers to a series o* digits# There are three t"pes o* integer as *ollo%s: a. 2ecimal integer 8m&edded spaces, commas and characters are not alloed in &et%een digits# For e:ample: 01 3// 6,CC,CCC /6#11 &. Octal integer It allo%s us an" se(uence o* num&ers or digits *rom C to 6 %ith leading C and it is called as Octal integer# /E | ! a g e

For e:ample: C// CC C304 c. De:adecimal integer : It allo%s the se(uence %hich is preceded &" C^ or C: and it also allo%s alpha&ets *rom YA9 to YF9 or Ya9 to Y*9 -YA9 to YF9 stands *or the num&ers Y/C9 to Y/49. it is called as De:adecimal integer# For e:ample: C:6 CC^ CA0< 0# Real Constant It allo%s us *ractional data and it is also called as *loating point constant#It is used *or percentage, height and so on# For e:ample: C#C013 C#666 -/#01 1# Character Constant It allo%s us single character %ithin pair o* single coute# For e:ample: YNA9 YN69 3# (tring Constant It allo%s us the series o* characters %ithin pair o* dou&le coute# For e:ample: I+8JCO=8 H I8N2 OF !RO@RA=I I<B8 _<B8I IAI 01 (!mbolic constant"

/? | ! a g e

In Java program, there are man" things %hich is re(uires repeatedl" and i* %e %ant to make changes then %e have to make these changes in %hole program %here this varia&le is used# For this purpose, Java provides 9*inalN ke"%ord to declare the value o* varia&le as *ollo%s: "nta:: *inal t"pe "m&olic[nameXvalueF For e:ample: I* I %ant to declare the value o* YN!IN then: *inal *loat !IX1#/34? the condition is, "m&olic[name %ill &e in capital letter- it sho%s the di**erence &et%een normal varia&le and s"m&olic name. and do not declare in method# <ackslash character constant: Java support some special character constant %hich are given in *ollo%ing ta&le# Constant 9L&9 9LtN 9LnN 9LLN 9LI 9LNI Comments: A comment is a note %ritten to a human reader o* a program# The program compiles and runs e:actl" the same %ith or %ithout comments# Comments start %ith the t%o characters HMMI -slash slash.# Those characters and ever"thing that *ollo%s them on the same line are ignored &" the ,ava compiler# 8ver"thing &et%een the t%o characters HMVIand the t%o characters HVMI are uno&served &" the compiler# There can &e man" lines o* comments &et%een the HMVI and the HVMI# Importance <ack space Ta& Ne% line <ackslash ingle coute 2ou&le coute

Command line arguments: Command line arguments are parameters that are supplied to the application program at the time o* invoking its e:ecution# The" must &e supplied at the time o* its e:ecution *ollo%ing the *ile name# In the main -. method, the args is con*irmed as an arra" o* string kno%n as string o&,ects# An" argument provided in the command line at the time o* program e:ecution, are accepted to the arra" args as its elements# >sing inde: or su&scripted entr" can access the individual elements o* an arra"# The num&er o* element in the arra" args can &e getting %ith the length parameter# 0C | ! a g e

For e:ample: class Add O pu&lic static void main- tring argsPQ. O int aXInteger#parseInt-argsPCQ.F int &XInteger#parseInt-argsP/Q.F int cXa'&F "stem#out#println-;Addition isX'c.F R R output: c:L,avac Add#,ava c:L,ava Add 4 0 6 *ata t!pes i# ii# A data t"pe is a scheme *or representing values# An e:ample is int %hich is the Integer, a data t"pe# Aalues are not ,ust num&ers, &ut an" manner o* data that a computer can process# The data t"pe de*ines the kind o* data that is represented &" a varia&le# As %ith the ke"%ord class, Java data t"pes are case sensitive# primitive data t"pe non-primitive data t"pe numeric means Integer, Floating points Non-numeric means Character and <oolean

There are t%o t"pes o* data t"pes

In primitive data t"pes, there are t%o categories

In non-primitive t"pes, there are three categories classes arra"s

0/ | ! a g e

inter*ace

Follo%ing ta&le sho%s the datat"pes %ith their si7e and ranges# 2ata t"pe &"te &oolean char short Int long *loat dou&le i7e -&"te. / / 0 0 3 E 3 E Range -/0E to /06 True or *alse A-Z,a-7,C-?,etc# -1065E to 10656 -a&out. -0 million to 0 million -a&out. -/C8/E to /C8/E -1#381E to 1#38/E -/#681CE to /#681CE

i# Integer data t!pe: Integer data t"pe can hold the num&ers -the num&er can &e positive num&er or negative num&er.# In Java, there are *our t"pes o* integer as *ollo%s: &"te short int long

+e can make integer long &" adding Yl9 or YJ9 at the end o* the num&er# ii# %loating point data t!pe: It is also called as Real num&er and %hen %e re(uire accurac" then %e can use it# There are t%o t"pes o* *loating point data t"pe# *loat dou&le It is represent single and dou&le precision num&ers# The *loat t"pe is used *or single precision and it uses 3 &"tes *or storage space# It is ver" use*ul %hen %e re(uire accurac" %ith small degree o* precision# <ut in dou&le t"pe, it is used *or dou&le precision and uses E &"tes o* storage space# It is use*ul *or large degree o* precision# iii# Character data t!pe: It is used to store single character in memor"# It uses 0 &"tes storage space# iv# <oolean data t"pe:

00 | ! a g e

It is used %hen %e %ant to test a particular condition during the e:cution o* the program# There are onl" t%o values that a &oolean t"pe can hold: true and *alse# <oolean t"pe is denoted &" the ke"%ord &oolean and uses onl" one &it o* storage# Follo%ing program sho%s the use o* data t"pes# !rogram: import ,ava#io#2ataInput treamF class cc0 O pu&lic static void main- tring argsPQ. thro%s 8:ception O 2ataInput tream s/Xne% 2ataInput tream- "stem#in.F &"te rollnoF int marks/,marks0,marks1F *loat avgF "stem#out#println-S8nter roll num&er:S.F rollnoX<"te#parse<"te-s/#readJine-..F "stem#out#println-S8nter marks m/, m0,m1:S.F marks/XInteger#parseInt-s/#readJine-..F marks0XInteger#parseInt-s/#readJine-..F marks1XInteger#parseInt-s/#readJine-..F avg X -marks/'marks0'marks1.M1F "stem#out#println-SRoll num&er isXS'rollno.F "stem#out#println-SAverage isXS'avg.F R R Output: C:LccT,ava cc0 8nter roll num&er: C6

01 | ! a g e

8nter marks m/, m0,m1: 55 66 EE Roll num&er isX6 Average isX66#C Mi2ing *ata t!pes: Java allo%s mi:ing o* constants and varia&les o* di**erent t"pes in an e:pression, &ut during assessment it hold to ver" strict rules o* t"pe conversion# +hen computer consider operand and operator and i* operands are di**erent t"pes then t"pe is automaticall" convert in higher t"pe# Follo%ing ta&le sho%s the automatic t"pe conversion#
Char B!te (hort Int .ong %loat double int int int int long *loat dou&le int int int int long *loat dou&le int int int int long *loat dou&le int int int int long *loat dou&le long long long long long *loat dou&le *loat *loat *loat *loat *loat *loat dou&le dou&le dou&le dou&le dou&le dou&le dou&le dou&le

TO$8N ON JAAA A Java program is &asicall" a set o* classes# A class is de*ined &" a set o* declaration statements and methods or *unctions# =ost statements contain e:pressions, %hich e:press the actions carried out on in*ormation or data# mallest indivisual thing in a program are kno%n as tokens# The compiler recogni7es them *or &uilding up e:pression and statements# There are *ive t"pes o* token as *ollo%s: i# ii# iii# iv# Jiterals Identi*iers Operators eparators

03 | ! a g e

I# Jiterals: Jiterals in Java are a se(uence o* characters -digits, letters and other characters. that characteri7e constant values to &e stored in varia&les# Java language speci*ies *ive ma,or t"pes o* literals are as *ollo%s: Integer literals II# Identi*iers: Identi*iers are programmer-created tokens# The" are used *or naming classes, methods, varia&les, o&,ects, la&els, packages and inter*aces in a program# Java identi*iers *ollo% the *ollo%ing rules: The" can have alpha&ets, digits, and the underscore and dollar sign characters# The" must not start %ith a digit# >ppercase and lo%ercase letters are individual# The" can &e o* an" length# Identi*ier must &e meaning*ul, easil" understanda&le and descriptive# Floating point literals Character literals tring literals <oolean literals

For e:ample: !rivate and local varia&les like ;length# Name o* pu&lic methods and instance varia&les &egin %ith lo%ercase letter like ;addition III# $e"%ords: $e"%ords are important part o* Java# Java language has reserved 4C %ords as ke"%ords# $e"%ords have speci*ic meaning in Java# +e cannot use them as varia&le, classes and method# Follo%ing ta&le sho%s ke"%ords#
Java Reserved Keywords
Abstract Char Double Float instanceof null short throw volatile boolean Class Else For Int Package Static !hrows "hile break const extends goto interface private super transient byte continue false if long protected switch true case default final implements native public synchroni ed try catch do finally import new return this void

04 | ! a g e

IA#Operator: Java carries a &road range o* operators# An operator is s"m&ols that speci*" operation to &e per*ormed ma" &e certain mathematical and logical operation# Operators are used in programs to operate data and varia&les# The" *re(uentl" *orm a part o* mathematical or logical e:pressions# Categories o* operators are as *ollo%s: /# Arithmetic operators 0# Jogical operators 1# Relational operators 3# Assignment operators 4# Conditional operators 5# Increment and decrement operators 6# <it %ise operators /# Arithmetic operators: Arithmetic operators are used to make mathematical e:pressions and the %orking out as same in alge&ra# Java provides the *undamental arithmetic operators# These can operate on &uilt in data t"pe o* Java# Follo%ing ta&le sho%s the details o* operators # Operator ' M V ` ImportanceM signi*icance Addition u&traction 2ivision =ultiplication =odulo division or remainder +hen &oth operands in the e:pression are integers then the e:pression is called Integer e:pression and the operation is called Integer arithmetic# +hen &oth operands in the e:pression are real then the e:pression is called Real e:pression and the operation is called Real arithmetic# +hen one operand in the e:pression is integer and other is *loat then the e:pression is called =i:ed =ode Arithmetic e:pression and the operation is called =i:ed =ode Arithmetic operation#

05 | ! a g e

0# Jogical operators: +hen %e %ant to *orm compound conditions &" com&ining t%o or more relations, then %e can use logical operators# Follo%ing ta&le sho%s the details o* operators# Operators aa KK b 1# Relational Operators: +hen evaluation o* t%o num&ers is per*ormed depending upon their relation, assured decisions are made# The value o* relational e:pression is either true or *alse# Follo%ing ta&le sho%s the details o* operators Operator T W bX TX WX 3# Assignment Operators: Assignment Operators is used to assign the value o* an e:pression to a varia&le and is also called as horthand operators# Aaria&le[name &inar"[operator X e:pression Follo%ing ta&le sho% the use o* assignment operators# imple Assignment Operator AXA'/ AXA-/ AXAM-<'/. AXAV-<'/. AXAMC AXA`C tatement Operators A'X/ A-X/ AMX-<'/. AVX-<'/. AMXC A`XC %ith shorthand ImportanceMsigni*icance @reater than Jess than Not e(ual to @reater than or e(ual to Jess than or e(ual to ImportanceMsigni*icance Jogical G OR Jogical GAN2 Jogical GNOT

No% the *ollo%ing program sho%s the use o* operators# class Assoptr O pu&lic static void main - tring argsPQ. 06 | ! a g e

O int a X /CF int & X 1CF int c X 1CF a'X/F &-X1F cVX6F "stem#out#println-Sa X S 'a.F "stem#out#println-S& X S'&.F "stem#out#println-Sc X S'c.F R R Output: a X // & X /E c X 1/C 4# Conditional Operators: The character pairc: is a ternar" operator o* Java, %hich is used to construct conditional e:pressions o* the *ollo%ing *orm: 8:pression/c 8:pression1: 8:pression1 The operatorc : %orks as *ollo%s: 8:pression/ is evaluated i* it is true then 8:pression1 is evaluated and &ecomes the value o* the conditional e:pression# I* 8:pression/ is *alse then 8:pression1 is evaluated and its value &ecomes the conditional e:pression# No% the *ollo%ing program sho%s the use o* operators# class Coptr O pu&lic static void main - tring argsPQ. O int a X /CF int & X 1CF 0E | ! a g e

int cF cX-aT&.ca:&F "stem#out#println-Sc X S 'c.F cX-aW&.ca:&F "stem#out#println-Sc X S 'c.F R R Output: c X 1C c X /C 5# IncrementLdecrement operator IncrementLdecrement operator is used to increase or decrease the value o* a varia&le &" one -/.# H''I Is kno%n as increment operator and H- -His kno%n as decrement operator#

8:: -

int a X 4F a''F ''aF a--F --aF aX5 e(uivalent to aXa'/F aX6 e(uivalent to aXa'/-F aX5 e(uivalent to aXa-/F aX4 e(uivalent to aXa-/F

There are t%o t"pes o* incrementLdecrement operator: !ost-*i: incrementLdecrement operator# !re-*i: incrementLdecrement operator# &ost-%i2 Increment3*ecrement Operator: +hen incrementMdecrement operator is used a*ter an operand then it is kno%n as post-*i: incrementMdecrement operator# 8:: int aX4,&F &Xa''F aX5 &X4 In this case, the assignment operation per*ormed at *irst and then the incrementLdecrement operation is per*ormed# 8:: 0? | ! a g e cX&-aX3

&X4 Then it is e(uivalent to &X a and a--# &re-%i2 Increment3*ecrement Operator: +hen incrementMdecrement operator is used &e*ore an operand then it is kno%n as pre-*i: incrementMdecrement operator# 8:: int aX4,&F &X''aF cX&-aX5 &X5 aX4 &X4 In this case, the incrementMdecrement operator per*ormed at *irst then the assignment operation is per*ormed# The statement &X ''aF is e(uivalent to ''a and &X a 41 Bit 5ise Operators" <it %ise operator e:ecute single &it o* their operands# Follo%ing ta&le sho%s &it %ise operator: Operator a K KX aX U WW TT d ImportanceM signi*icance <it%ise OR <it%ise AN2 <it%ise AN2 assignment <it%ise OR assignment <it%ise 8:clusive OR Je*t shi*t Right shi*t One9s complement

No% the *ollo%ing program sho%s the use o* operators# -/. !rogram class <optr/ O pu&lic static void main - tring argsPQ. O int a X 3F int & X aWW1F 1C | ! a g e

"stem#out#println-Sa X S 'a.F "stem#out#println-S& X S '&.F R R Output: a X3 & X/5 IA# (eparator" eparators are s"m&ols# It sho%s the separated code# The" descri&e *unction o* our code# Name -. OR PQ F , # use !arameter

in

method

de*inition,

containing statements *or conditions,etc# It is used *or de*ine a code *or method and classes It is used *or declaration o* arra" It is used to sho% the separate statement It is used to sho% the separation in identi*ier in varia&le declarartion It is used to sho% the separate package name *rom su&-packages and classes, separate varia&le and method *rom re*erence varia&le#

Control ,low statements: Control statements are used to provide the *lo% o* e:ecution %ith condition# In ,ava program, control structure is can divide in three parts: I# election statement Iteration statement Jumps in statement election tatement: election statement is also called as 2ecision making statements &ecause it provides the decision making capa&ilities to the statements#

1/ | ! a g e

In selection statement, there are t%o t"pes: i* statement s%itch statement These t%o statements are allo%s "ou to control the *lo% o* a program %ith their conditions# i* tatement: The Hi* statementI is also called as conditional &ranch statement# It is used to program e:ecution through t%o paths# The s"nta: o* Hi* statementI is as *ollo%s: "nta:: i* -condition. O tatement /F tatement 0F ### R else O tatement 1F tatement 3F ### R The Hi* statementI is a commanding decision making statement and is used to manage the *lo% o* e:ecution o* statements# The Hi* statementI is the simplest one in decision statements# A&ove s"nta: is sho%s t%o %a"s decision statement and is used in com&ination %ith statements# I*-else tatements It is kno%n as dou&le &locked conditional statements #It means, it has TR>8 parts as %ell as FAJ 8 part# I* the given condition is TR>8 then the TR>8 part is e:ecuted other%ise FAJ 8 part is e:ecuted# "nta:: i* -condition. O 10 | ! a g e

______## ______## R else O ______## ______## R False part True part

NOT8: +hen %e have to %rite onl" one statement in conditional statement then it is not need to use curl" &race ONM OFF# <ut it is good practice to use curl" &race in all situations# s%itch statement: In Java, s%itch statement check the value o* given varia&le or statement against a list o* case values and %hen the match is *ound a statement-&lock o* that case is e:ecuted# %itch statement is also called as multi%a" decision statement# "nta:: s%itch-condition.MM condition means case value O case value-/:statement &lock/F&reakF case value-0:statement &lock0F&reakF case value-1:statement &lock1F&reakF _ de*ault:statement &lock-de*aultF&reakF R tatement aF The condition is &"te, short, character or an integer# Aalue-/, value-0, value-1_are constant and is called as la&els# 8ach o* these values is matchless or uni(ue %ith the statement# tatement &lock/, tatement &lock0, tatement &lock1 #are list o* statements %hich contain one statement or more than one statement# Case la&el is al%a"s end %ith H:I -colon.# )esting o, i, else (tatement Syn: 11 | ! a g e

i* -condition. O ____# ____# i* -condition. O ____## ____## R else O ____ ____ R R else O ____ ____ The else part then %e have to use Jadder o* i* statement# I* condition is true then onl" Hpart/I%ill &e e:ecuted, other%ise condition0 %ill &e checked# It conditon0 is true then onl" Hpart0I in &e e:ecuted, other%ise condition1 %ill &e checked# I* condition1 is true then onl" Hpart1I %ill &e e:ecuted other%ise Hpart3I %ill &e e:ecuted Syn: 13 | ! a g e

I* -condition /. O ____# ____# R else i* -condition 0. O ____ ____ R else i* -condition 1. O ____# ____# R else O ____# !art1 !art0 !art /

____# R .ooping (tatement

!art3

14 | ! a g e

Jooping statement is used to repeat a set o* statements again K again until the given condition remains true# It means, it is used to repeat a certain task *or a certain period# The condition given in the looping statement must &e o* <oolean t"pe# There are three looping statement supported &" JAAA#

Jike C'', JAAA also supports three looping statement /# *or loop 0# %hile loop 1# do %hile loop /# ,or loop: It is a Jooping statement, %hich is used to e:ecute a set o* statements again K again until the given condition remains true# "n: - *or -initiali7ation partF conditional partF incrementMdecrement part. O ___# ___# R 0# 5hile-loop" It is also a looping statement, %hich is used to repeat a set o* statements again K again until the given condition remain TR>8# "n: - %hile -condition. O ___# ___# ___# IncrementMdecrement partF R 15 | ! a g e <od" o* %hile loop

8:: int aX/F %hile -aWX/CC. O "stem#out#println -'a.F a''F R 11 do-while loop" It is also a looping statement, %hich is used to e:ecute a set o* statement again K again until the given condition remains TR>8# "n: do O ___# ___# ___# IncrementMdecrement partF R %hile -condition.F

The &asic di**erence &et%een %hile-loop and do-%hile loop is that the &od" o* do-%hile loop must e:ecute at least once time either the given condition is TR>8 or FAJ 8# This is so &ecause in this case &od" appears &e*ore condition *urther e:ecution o* do-%hile loop depends on the condition#<ut the &od" o* *or-loop and %hile-loop must &e e:ecuted at *east one time %hen the given condition remains TR>8 at least one time# Other%ise, %hole &od" is skipped &" the control#

16 | ! a g e

#''#/ Arra" is a user-de*ined data t"pe, %hich is used to store the homogenous t"pes o* values# In another %ord, %e can also sa" that it is also a varia&le, %hich can store more than one values o* some data t"pe# "n: datat"pe vPQ X ne% datat"pe Psi7eQF Ex: Int aPQ X ne% int P4QF Float &PQ X ne% *loat P/CQF Int PQa X ne% int P4QF The Hne%I ke"%ord initiates the arra" varia&le in memor" i#e# it allocates the memor" space *or arra" varia&le in memor"# It also divides that memor" space in di**erent &locks according to given si7e# Jike cMc'', it also provides a uni(ue inde: num&er to each &lock, starts *rom 7ero -C.# a C Syn: datat"pe vPQF MM2eclaration vPQX ne% datat"pe Psi7eQF Ex: Int aPQF a X ne% int P4QF Declaration with Assignment Syn: datat"pe vPQ X Olist o* valuesRF Ex: 1E | ! a g e MMInstantiation / 0 1 3

Another way of declaring an Array

Int aPQ X O /, 0, 1, 3, 4RF a / C 0 / 1 0 3 1 4 3

+A! to enter /C num&ers in an arra" and print them#

import ,ava#io#2ataInput treamF class arra" O pu&lic static void main - tring argsPQ. O int aPQXne% intP/CQF int iF 2ataInput tream o&, X ne% 2ataInput tream- "stem#in.F tr" O *or-iXCFiW/CFi''. O "stem#out#print-SLn 8NT8R N>=<8R IN ARRAB: -S.F aPiQXInteger#parseInt-o&,#readJine-..F R "stem#out#print-SLn 8NT8R OF ARRAB: -S.F *or -iXCFiW/CFi''. O "stem#out#println-aPiQ.F R R catch -8:ception e. O R R R T/&E( O% #''#/ 1? | ! a g e

ingle 2imensional

=ulti 2imensional Ragged Arra" (ingle *imensional #rra! +hen one dimension is mentioned %ith an arra" varia&le then it is kno%n as single dimensional arra"# Syn: datat!pe v67 8 new datat!pe 6si9e7: The memor" space is allocated &" arra" varia&le name either hori7ontall" or verticall"# This space is divided into di**erent &lock according to the given si7e# 8ach &lock is assigned an inde: num&er, starts *rom 7ero?C.# Ex: Int aPQ X ne% int P4QF C / 4 0 1 3

To kno% the length o* arra" s"stem#out#print -a# length.F A

I@N=8NT OF ON8 ARRAB INTO ANOTD8R

>nlike cMc'', JAAA provides the *acilit" o* assigning one arra" into another arra"# Ex: int a PQ X ne% int P4QF int & PQ X aF In this case the si7e o* arra" H&I is automatic assigned as HaI# int a PQ X O/, 0, 1, 3, 4RF Multi *imensional ; *ouble *imensional #rra! +hen t%o dimensions are mentioned %ith an arra" varia&le then it is kno%n as 2ou&le 2imensional arra"# Ex: 2atat"pe v PQPQ X ne% datat"pe Psi7eQPsi7eQF In this case, the *irst Hsi7eI stands *or Hro%I value and the second Hsi7eI stands *or HcolumnI value# 3C | ! a g e

o the memor" space is divided into di**erent Hro%I and HcolumnI aMc to the given values# Ex: Int aPQPQ X ne% int P1QP1QF C C / 0 / 0
40

8ach ro% and column is assigned an inde: num&er, starts *rom 7ero -C.# And the value is assigned or retrieved &" the com&ination o* ro% K column inde: num&er# Assignment aPCQP0Q X 3C aP0QP/Q X 4C To kno% the length Ex: int aPQPQ X ne% int P1QP3QF "stem#out#print -a# length.F "stem#out#print -aPCQ#length.F Ex: int aPQPQ X ne% int P0QP1QF C C & / so, the arra" H&I is also allocated the space same as HaI# Ex: int a PQPQ X OO/, 0, 1,R,O3, 4, 5RRF 3/ | ! a g e / 0 ro% num&er -1. column num&er -3.

Assignment o* One 22A To Another

C
1

/
2

0
3

C a / int & PQPQ X aF C


1

/
2

0
3

C & /

30 | ! a g e

MO*-.E-III C.#(( HCJA I is a user-de*ine data t"pe, %hich provides a unit under %hich %e can kept the varia&les and under %hich %e can kept the varia&le and methods together# The varia&les declared %ithin class are kno%n as 2ata mem&er and the methods declared %ithin class are kno%n as mem&er method# Class W class nameT O *riendl" int mF private int aF protected *loat &F pu&lic void */ -. O ---------R R OBJECT O&,ect is also a varia&le, %hich is declared &" the class name# It means, class name is used as a data t"pe to declare a varia&le i#e# o&,ects# ThatNs %h", class is kno%n as used-de*ined data t"pe# +hen an o&,ect o* an" class is created, then the memor" space is allocated &" the o&,ect name and then the mem&er o* that class reside %ithin that o&,ect area# o %e must have to create the o&,ect o* an" class# The s"nta: o* declaring an o&,ect is as *ollo%s# Class name o&,ect name X ne% class name -.F =em&er =ethod 2ata =em&ers

31 | ! a g e

In this line, the o&,ect is declared as %ell as instantiated# It means, the a&ove line can &e &reak do%n into t%o lines# Class name o&,ectF MM2eclaration O&,ect name X ne% class name -.F MMInstantiation# HNe%I ke"%ord: - Hne%I ke"%ord is used to instantiate the o&,ect in memor" at run-time# It means, it esta&lished the linking &et%een class and o&,ect# Jet us suppose the *ollo%ing class Class A O int aF pu&lic void */ -. O ------R R +hen %e declare the Ho&,ectI o* class A like# A o&,F Then it %ill take the memor" space &ut that memor" is no% *illed up %ith HN>JJI# It means no an" mem&ers o* Hclass A Hreside %ithin o&,ect area so %e cannot use an" mem&ers through this o&,ect# Method Overloading It is the *eature o* oops languages through %hich %e can create more than one *unction having same name &ut di**erent parameters# Thus, %hen %e create more than one *unction having same name &ut di**erent *ormat arguments %ithin same class then it is kno%n as method overloading# And all such *unction is called overloaded *unctionsMmethods# The parameters -*ormed argument. ma" &e di**erent in overloaded *unctions cither in t%o %a"s# 8ither the num&er o* *ormal arguments must &e di**erent# Or, the data t"pe o* *ormed arguments must &e di**erent# Ex: Class A O 33 | ! a g e

pu&lic void */ -. O ------R pu&lic void */ -int a. O ------R pu&lic void */ -int a. O ------R pu&lic void */ -*loat a. O ------R pu&lic void */ -int a *loat &. O ------R pu&lic void */ -*loat a int &. O ------R Constructor 34 | ! a g e

It is also a mem&er method %ithin class %hose name is same as the class name# It means, a *unctionMmethod, %hich is created &" the class name in pu&lic mode, is kno%n as constructor# E2" Class A O pu&lic A -. Constructor O ------R R %eatures o, Constructor Constructor name must &e same as class name# It must &e created in *riendl"Mpu&lic mode onl"# It cannot return an" value# o there is no an" return t"pe mentioned &e*ore constructor name# 8ven HvoidI is also not used# Constructor can receive the num&ers# o, *ormal argument can &e mentioned in an" num&er o* an" data t"pe# Constructor is activated automaticall" %here an o&,ect o* that class is initiated in memor"# o, it is not called e:plicitl" like other mem&er method# Calling O, Constructor Constructor is the *irst method %ithin class, %hich is activated automaticall" a*ter running the program# It is called implicitl" %henever an o&,ect o* that class is initiated in memor"# That is, %hen the o&,ect is loaded into memor", constructor is activated# @enerall" constructor is used to initials the data mem&er automaticall" at run-time or to per*orm some certain action at run-time automaticall"# E2" Class A O pu&lic A-. O "stem#out#print-HLn D8JJOI.F R 35 | ! a g e Class = O pu&lic static void main- - - - -. O A o&,/ X ne% A -.F A o&,0 X ne% A -.F

RF

R R O>T!>T Dello Dello

T!pe o, constructor There are three t"pe o* constructor supported &" JAAA# /# 2e*ault Constructor 0# !arameteri7ed Constructor 1# Cop" Constructor /# *e,ault Constructor" # constructor having no an" *ormal argument is called 2e*ault Constructor# Ex: Class A O pu&lic A- . 2e*ault Constructor O ------R R impl" creating the o&,ect o* that class activates de*ault Constructor# 8:: A obj = new A ()

F MM Active

2e*ault Construe

0# &arameteri9ed Constructor" A Constructor having some *ormal argument are called !arameteri7ed Constructor# E2" Class A O

36 | ! a g e

pu&lic A -int a, int &. !arameteri7ed Constructor O ------R R !assing the values %ith o&,ect at the time o* its decollation activates parameteri7ed Constructor#

<1 Cop! Constructor" It is also a t"pe o* parameteri7ed Constructor, in %hich o&,ect is used as *ormal argument o* the same class# Cop" Constructor is used to cop"Massign the value o* one o&,ect into another# Dence, the main di**erence &et%een parameteri7ed and cop" constructor is that parameteri7ed constructor has simple varia&les as *ormal argument %hereas cop" constructor has an o&,ect o* same class as *ormal argument# 8:: Class A O pu&lic A -int a. parameteri7ed Constructor# O ------R pu&lic A -A :. Cop" Constructor O ------R R Cop" Constructor is activated %henever %e pass the o&,ect o* same class %ithin another o&,ect at the time o&,ect creation#

3E | ! a g e

8:: A o&,/ X ne% A -E.F Activates parameteri7ed Constructor A o&,/0X ne% A -o&,/.F Activates Cop" Constructor %inali9e => method It is a destructor in JAAA# 2estructor is mainl" used to destro" the memor" varia&les at the end o* the program# It is also e:ecuted automaticall" %hen our program %ould save the memor" i#e# at the end o* the program# In another %ord, %e can also sa" that %hen the o&,ect is saving the memor" then the destructor is automaticall" e:ecuted#

The class creates the main di**erence &et%een C'' destructor is created &" the class name and *ollo%ed &" tilde -d. sign %here as *inali7e -. method is used as destructor in JAAA# 8:: Class A O pu&lic: *inali7e -. 2estructor O ------R R Class = O p#s#v#m - - - - -. O A o&, X ne% Acr R R

3? | ! a g e

4C | ! a g e

MO*-.E-I$ #dvanced ,eatures o, classes Inheritance: It is the most po%er*ul and use*ul *eature o* oops through %itch %e can create o%e or more than one class *rom an e:isting class#A class *rom %hich another class is created is kno%n as parent class super class or &ase class and a class, %hich is created &" another, class is kno%n as child class, su& class or derived class# The s"nta: o* deriving a class in JAAA is as *ollo%s# Class ?sub class name@ e2tends ?parent class name@ A ------B 8:: Class A O ------R class < e:tends A O ------R Dence Hclass <I is the child class o* Hclass AI# %eature o, the Inheritance The main *eature o* the inheritance is that the child class can use the protected as %ell as pu&lic mem&er o* parent class %ithin it# o, %e can call the parent class mem&er methods &" the

4/ | ! a g e

o&,ect o* child class outside the class# Dence, there is no need to create an o&,ect o* parent class separatel"# Child class ma" also have some e:tra properties# Class A O private int aF protected int &F pu&lic void */ -. O ------R R class < e:tends A O pu&lic void *0 -. O a X 0CF & X 3CF R R T!pe O, Inheritance There are three t"pes o* inheritance supported &" JAVA. i# ii# iii# ingle Inheritance =ultilevel Inheritance Dierarchical Inheritance i1 (ingle Inheritance In this case single Inheritance, there is one parent class and one child class# 8:: !arent class 40 | ! a g e
Class A

Class = O p#s#v#m -- - - -. O < o&, X ne% < -.F O&,#*/ -.F O&,#*0 -.F R R =emor" =anagement
Class A Int a Int b Void f1 () { class B int b void f1 () { ---

void f2 ()

2erived *orm
Class B

Child class

8:: Class A O ------R class < e:tends A O ------R In this case, the child class o&,ect can us the mem&er o* its parent class also# ii1 Multilevel Inheritance In this case, a class is derived *rom this derived class and so on this t"pe at inheritance is kno%n as =ultilevel Inheritance# 8:: -

!arent class

Class A

41 | ! a g e

Class B

Intermediate !arent class

Class C

Child class

Ex: Class A O ------R class < e:tends A O ------R class C e:tends < O ------R In this case, i* %e create an o&,ect o* HclassI then %e can handle the mem&er o* all the three classes through that o&,ect, &ecome Hclass CI is indirectl" linked %ith Hclass AI through Hclass <I# iii1 ierarchical Inheritance +hen more than class is derived *rom a class and again one or more than one class is derived *rom an" o* the derived class %hen this t"pe o* inheritance is kno%n as Dierarchical Inheritance# 8:: Class A

43 | ! a g e

Class B

Class C

Class !

Class "

Class #

This inheritance automaticall" creates a HtrueI like structure# ThatNs %h"F it is given the name Dierarchical Inheritance# In this case, i* %e create an o&,ect o* innermost child class then %e can handle all the mem&er o* a&ove related parent classes# I)TE'%#CE It is also a most use*ul *eature o* JAVA, %hich provides a unit like class, in %hich %e can keep the varia&les or methods# In another %ord, %e can also sa" that inter*ace is a class like entit" %hich provides a unit in %hich the varia&les and methods can &e kept together# (!n" Inter*ace Winter*ace nameT O 2ata t"pe list o* varia&les return t"pe method name -.F R The main di**erent &et%een class and inter*ace is that the methods o* inter*ace cannot &e de*ined %ithin it can &e declared onl"# +here as the method o* class must &e de*ined %ithin the class# All the varia&les de*ined %ithin inter*ace are Hpu&licI HstaticI K H*inalI &" de*ault# And the methods %ithin inter*ace are Hpu&licI K HstaticI &" de*ault#

44 | ! a g e

E2" Inter*ace int */ O Int a X /CF void */ -.F R <" de*ault Inter*ace int */ O !u&lic static *inal int a X /CF !u&lic static void */ -.F R

Implementing #n Inter,ace As %e kno% that the method o* inter*ace can not &e de*ined %ithin it# o, it must &e implementing &" a class# That is, %e implementing &" a class# That is, %e must esta&lish the inheritance relation &et%een class and inter*ace# Dence, %e must have to create a child class o* inter*ace &" implementing it and override all the methods o* inter*ace %ithin the class# The s"nta: o* implementing a class &" inter*ace is as *ollo%s# Syn: Class Wclass nameT implements Winter*ace nameT O ---------R Ex: Inter*ace int */ O Int a X /CF Aoid */ -.F R Class A implements int */ O !u&lic void */ -. O 45 | ! a g e

------RR calling A o&, X ne% A -.F O&,# */ -.F Int */ o&,F O&, X ne% A -.F O&,# */ -.F I* a class does not override the method o* inter*ace then that class must &e declared as HA&stractI class Ex: Inter*ace int */ O !u&lic static void */ -.F R A&stract class A implements int */ O !u&lic void *0 -. O ------R R &#CC#DE" !ackage is a container o* holding di**erent classes and class is a container o* holding di**erent methods# It is same as the concept o* header *ile in CMC''# +hen %e need to use an" pre-de*ined method in our program then %e must have to use the corresponding class and package in our program# There are t%o t"pes o* packages# /# s"stem package -A!I package. 0# user de*ined package (!stem pacEage -A!I package.: All the pre-de*ine packages are kno%n as s"stem package or A!I -Application !rogram Inter*ace. package# The" hold di**erent pre-de*ined classes# 46 | ! a g e

The list o* s"stem packages are as *ollo%s# a# Java#lang: -Dolds the standard inputMoutput classes *or printing t"pes, strings, math *unction, threads and e:ception# There are the classes that JAVA compiler itsel* user and there*ore the" are automaticall" imported# &# Java#util: -It holds the language utilit" classes such as vectors, hash ta&les, random num&er, data etc# c# Java#io: -It holds the standard inputMoutput classes# &uttons, list, menus etc# e# Java#net: -It holds classes *or net%orking# *# Java#applet: -It holds classes *or creating and implementing applets# g# Javax#s%ing: -It holds classes o* di**erent @>I controls# d# Java#a%t: -It holds the classes *or graphical user inter*ace# It contain classes *or %indo%,

Dence, %e can sa" that all the s"stem packages are kept either in t%o super package G H java OR Hjavax # o %e use the *ollo%ing s"nta: to use an" s"stem package and its classes in our program#

Import super package# A!I package# ClassnameF Or Import super package# A!I package# V F tands *or all classes# Ex: Import java# Jang# =athF Import java# io# VF Import java# >til# vectorF Import javax# s%ing# VF -ser de,ined pacEage Jike header *ile o* CMC'', %e can also create our package in java, in %hich %e can de*ine an" num&er o* classes to use in an" program like s"stem packages# These, a package created &" user are kno%n as user-de*ined package# 4E | ! a g e

To add a class into package, %rite the *ollo%ing code# !ackage Wpackage nameT !u&lic class Wclass nameT O ---------R (teps o, creating a user-de,ined pacEage %ollowing step are ,ollowed to create a user-de,ined pacEage# +OR$IN@ 2IR8CTORB C:L,dk /#1L&inT Create a director"

Ex: C:L,dk /#1L&inT md demo 8nter into this director"#

Ex: C:L,dk /#1L&inT cd demo C:L,dk /#1L&in L demoT Open the editor and create H#,avaI source *ile to add a class into a package# It is sho%n as *ollo%s#

Ex: C:L,dk /#1L&inT 82IT

4? | ! a g e

!ackage demoF !u&lic class Add O !u&lic void sum -. O Int aX /C, & X 0C, cF C X a ' &F "stem#out#print -HLn um X H ' c.F R R Note

Add# Java

=ain class is not declared in packages# o, it can not &e run, onl" compiled# Compile this HJavaI *ile#

Ex: C:L,dk /#1L&inL demoT cd # # # C:L,dk /#1L&inT ,avac demoLAdd#,ava C:L,dk /#1L&inT Create another H#,avaI surce *ile on the current director"# It has the main-method class#

Ex: C:L,dk /#1L&inT 82IT import demo# VF class 2main O !u&lic static void main -string args PQ. O Add o&, X ne% Add -.F O&,# sum -.F R R Compile an run this H#JavaI *ile# 2main# Java

Ex: -

5C | ! a g e

C:L,dk /#1L&inT ,avac 2main #,ava C:L,dk /#1L&inT ,ava 2main

&'OD'#M( 'E.#TI)D J#$# F1 5#& to print a message M#*E %O' E#C


5/ | ! a g e

OT E'G1

class made O pu&lic static void main- tring argsPQ. O "stem#out#println-S=ade For 8ach OtherS.F R R

H1 5#& to print the sum o, two numbers


class sum O pu&lic static void main- tring argsPQ. O int aX/C,&X0C,cF cXa'&F "stem#out#println-S um o* t%o num&er: -S'c.F R R

<1 5#& to pass one integer valueI one ,loat value and one character value ,rom command line and print them1
class print O pu&lic static void main- tring argsPQ. O int aXCF *loat *XC#C*F char cX)MC)F aXInteger#parseInt-argsPCQ.F *XFloat#valueO*-argsP/Q.#*loatAalue-.F cX-argsP0Q#charAt-C..F "stem#out#print -SLn Integer Aalue: - S'a.F "stem#out#print-SLn Float Aalue: - S'*.F "stem#out#print-SLn Character Aalue: - S'c.F R 50 | ! a g e

J1 5#& to input two values ,rom command line and print their sum1
class sum O pu&lic static void main- tring argsPQ. O int aXC,&XC,cF aXInteger#parseInt-argsPCQ.F &XInteger#parseInt-argsP/Q.F cXa'&F "stem#out#print-SLn um O* T%o Aalue: - S'c.F R R

01 5#& to input two values ,rom command line and swap them1
class s%apping O pu&lic static void main- tring argsPQ. O int a,&,cF aXInteger#parseInt-argsPCQ.F &XInteger#parseInt-argsP/Q.F "stem#out#print-SLn <e*ore s%apping Aalue A: - S'a.F "stem#out#print-SLn <e*ore s%apping Aalue <: - S'&.F cXaF aX&F &XcF

51 | ! a g e

"stem#out#print-SLn A*ter s%apping Aalue A: - S'a.F "stem#out#print-SLn A*ter s%apping Aalue < : - S'&.F R R

K1 5#& to input a number ,rom command line and checE whether it is palindrome or not1 class palindrome
O pu&lic static void main- tring argsPQ. O int num,rXC,:,num/F numXInteger#parseInt-argsPCQ.F num/XnumF %hile-numTC. O :Xnum`/CF numXnumM/CF rXrV/C':F R i*-rXXnum/. O "stem#out#println -SThis is !alindromeS.F R else O "stem#out#println -SThis is Not !alindromeS.F R R R

53 | ! a g e

41 5#& to input a number ,rom command line and checE it per,ect sLuare number1
class s(ure O pu&lic static void main- tring argsPQ. O int num,divX/,rem,(,cXCF numXInteger#parseInt-argsPCQ.F %hile -divWXnum. O remXnum`divF (XnumMdivF i*-divXX(KKremXXC. O "stem#out#println -SNum&er is !er*ect (uareS.F cX/F &reakF R divXdiv'/F R i*-cXXC. O "stem#out#println -SNum&er is Not !er*ect (ureS.F R R R

M1 5#& to input a number and print its ,actorial in ,ollowing ,ormat1 F NH N < NJ 8 HJ
pu&lic class *act O 54 | ! a g e

pu&lic static void main- tring argsPQ. O int a,cX/,iF aXInteger#parseInt-argsPCQ.F *or-iX/FiWXaFi''. O cXcViF "stem#out#print-i'SVS.F R "stem#out#print-SXS'c.F R R

O1 5#& to print the sum o, all those numbers which are passed ,rom command line1
class inputsum O pu&lic static void main- tring argsPQ. O int a,sXC,iF *or-iXCFiWargs#lengthFi''. O aXInteger#parseInt-argsPiQ.F sXs'aF R "stem#out#print-SLn Total umXS's.F R R

FP1 5#& to input some number ,rom command line and print the number o, arguments passed ,rom command line and also print the greatest among all number1
55 | ! a g e

class grator O pu&lic static void main- tring argsPQ. O int num,i,aXC,&XCF *or-iXCFiWargs#lengthFi''. O numXInteger#parseInt-argsPiQ.F i*-aWnum. O aXnumF R R &Xargs#lengthF "stem#out#print-SLn N>=<8R OF AR@>=8NT XS'&.F "stem#out#print-SLn @R8ATOR N>=<8R I XS'a.F R R

FF1 5#& to input principalI reat Q interest ,rom command line and print the simple interest1 E2" - (i 8 p N r N t;FPP 8 HPP N 0 N H;FPP8HPP
pu&lic class interest O pu&lic static void main- tring argsPQ. O int p,r,t,siXCF pXInteger#parseInt-argsPCQ.F rXInteger#parseInt-argsP/Q.F tXInteger#parseInt-argsP0Q.F siX-pVrVt.M/CCF "stem#out#println -SinterestXS'si.F R R 56 | ! a g e

FH1 5#& to solve the ,ollowing e2pression1 F;.F+H;.H+<;.<+ - - - - -- n;.n 8?


import ,ava#io#2ataInput treamF class solve O pu&lic static void main - tring argsPQ. O int n,*X/,rXC,i,,F 2ataInput tream in X ne% 2ataInput tream- "stem#in.F tr" O "stem#out#print-SLn 8NT8R TD8 RAN@8: -S.F nXInteger#parseInt-in#readJine-..F *or-iX/FiWXnFi''. O *or-,X/F,WXiF,''. O *X*V,F R rXr'-iM*.F "stem#out#print-i'SMS'i'SbS'S'S.F R "stem#out#print-SL&S.F "stem#out#print-SXS.F "stem#out#print-r.F R catch-8:ception e. O R R R

5E | ! a g e

F<1 5#& to ,ine the rots o a Luadratic eLuation1 #2H+b2+c8P * 8 bH-Jac I, =d8P> then 'oots are eLual RF82H8-b;a I, =d?P>then 'ots are imaginar! I,=d@P> then 'ots are read 2F8-b + d;Ha 2H8-b + d;Ha
import ,ava#io#2ataInput treamF class (uad O pu&lic static void main- tring argsPQ. O dou&le a,&,c,:/,:0,dF 2ataInput tream o&,Xne% 2ataInput tream - "stem#in.F tr" O "stem#out#print-SLn 8NT8R TD8 AAJ>8 FOR A: -S.F aX2ou&le#valueO*-o&,#readJine-..#dou&leAalue-.F "stem#out#print-SLn 8NT8R TD8 AAJ>8 FOR <: -S.F &X2ou&le#valueO*-o&,#readJine-..#dou&leAalue-.F "stem#out#print-SLn 8NT8R TD8 AAJ>8 FOR C: -S.F cX2ou&le#valueO*-o&,#readJine-..#dou&leAalue-.F dX-&V&.--3VaVc.F i*-dWC. O "stem#out#print-SLn ROOT AR8 I=A@INARBS.F R 5? | ! a g e

i*-dXXC. O "stem#out#print-SLn ROOT AR8 8e>AJS.F :/X:0X--&.M-0Va.F "stem#out#print-SLn FIR T ROOTXS':/.F "stem#out#print-SLn 8CON2 ROOTXS':0.F R i*-dTC. O "stem#out#print-SLn ROOT AR8 R8AJXS.F :/X---&.'=ath#s(rt-d..M-0Va.F :0X---&.-=ath#s(rt-d..M-0Va.F "stem#out#print-SLn FIR T ROOTXS':/.F "stem#out#print-SLn 8CON2 ROOTXS':0.F R R catch-8:ception e. O R R R # FJ1 5#& to input one characterI one integer and one ,loat value ,rom Ee!board

and print them1


import ,ava#io#2ataInput treamF class kinput O pu&lic static void main- tring argsPQ. O int aXCF *loat *XC#C*F char cX)LC)F 2ataInput tream o&,Xne% 2ataInput tream- "stem#in.F 6C | ! a g e

tr" O "stem#out#print-SLn 8NT8R CDARACT8R AAJ>8 S.F cX-o&,#readJine-..#charAt-C.F "stem#out#print-SLn 8NT8R INT8@8R AAJ>8 S.F aXInteger#parseInt-o&,#readJine-..F "stem#out#print-SLn 8NT8R FJOAT AAJ>8 S.F *XFloat#valueO*-o&,#readJine-..#*loatAalue-.F "stem#out#print-SLn Character Aalue: - S'c.F "stem#out#print-SLn Integer Aalue: - S'a.F "stem#out#print-SLn Float Aalue: - S'*.F R catch-8:ception e. O "stem#out#print-SLn 2ATA TB!8 =I =ATCDS.F R R

F01 5#& to input two integers values and prints their sum1
import ,ava#io#VF class esum O pu&lic static void main - tring args PQ. thro%s IO8:ception O int a,&,cF <u**eredInput tream &u* X ne% <u**eredInput tream- "stem#in.F Input treamReader In X ne% Input treamReader -&u*.F "stem#out#println-S8NT8R FIR T N>=<8R: -S.F aXInteger#parseInt-In#readJine-..F "stem#out#println-S8NT8R 8CON2 N>=<8R: -S.F &XInteger#parseInt-In#readJine-..F 6/ | ! a g e

cXa'&F "stem#out#println-SsumXS'c.F R R

FK1 5#& to demonstrate the use o, tr! and catch in e2ception handling1
import ,ava#io#2ataInput treamF class demo O pu&lic static void main- tring argsPQ. O int a,&,cF 2ataInput tream o&, X ne% 2ataInput tream - "stem#in.F tr" O "stem#out#print-SLn 8nter numerator: -S.F aXInteger#parseInt-o&,#readJine-..F "stem#out#print-SLn 8nter 2enominator: -S.F &XInteger#parseInt-o&,#readJine-..F cXaM&F "stem#out#print-SLn 2iv XS'c.F R catch -8:ception e. O "stem#out#print-SLn 8rror: 2ivision &" ZeroS.F R R R

F41 5#& to print the in,inite table on userSs choice is starting ,rom H1
import ,ava#io#2ataInput treamF class ta&le/ 60 | ! a g e

O pu&lic static void main- tring argsPQ. O int tX0,num,iF char chX)B)F 2ataInput tream o&, X ne% 2ataInput tream- "stem#in.F tr" O %hile-chXX)B)aachXX)"). O *or-iX/FiWX/CFi''. O numXtViF "stem#out#print-SLnS't'SVS'i'SXS'num.F R

"stem#out#print-SLn 2O BO> +ANT TO 88 N8^T TA<J8 -BMN.: -S.F chX-o&,#readJine-..#charAt-C.F i*-chXX)B)aachXX)"). O t''F R R R catch -8:ception e. O R R R

FM1 5#& to enter FP number in an arra! and print them1


import ,ava#io#2ataInput treamF 61 | ! a g e

class arra" O pu&lic static void main - tring argsPQ. O int aPQXne% intP/CQF int iF 2ataInput tream o&, X ne% 2ataInput tream- "stem#in.F tr" O *or-iXCFiW/CFi''. O "stem#out#print-SLn 8NT8R N>=<8R IN ARRAB: -S.F aPiQXInteger#parseInt-o&,#readJine-..F R "stem#out#print-SLn 8NT8R OF ARRAB: -S.F *or -iXCFiW/CFi''. O "stem#out#println-aPiQ.F R R catch -8:ception e. O R R R

FO1 5#& to input some number in < N < **# and print the sum o, diagonal elements ,rom . to ' and ' to .#
C / 0

63 | ! a g e

/ 3 6

0 4 E

1 5 ?

/ 0

import ,ava#io#VF class sdda O pu&lic static void main - tring argsPQ. O int aPQPQ Xne% int P1QP1QF int i,,,sumXC,sum/XC,kX0F 2ataInput tream o&, X ne% 2ataInput tream - "stem#in.F tr" O *or-iXCFiW1Fi''. O *or-,XCF,W1F,''. O "stem#out#print-SLn 8NT8R N>=<8R IN 22A: -S.F aPiQP,QXInteger#parseInt-o&,#readJine-..F R R *or-iXCFiW1Fi''. O *or-,XCF,W1F,''. O i*-iXX,. O sumXsum'aPiQP,QF R R R *or-iXCFiW1Fi''. O um/Xsum/'aPiQPkQF kXk-/F R R catch-8:ception e. O R 64 | ! a g e

"stem#out#println-S >= OF 22A: -S'sum.F "stem#out#println-S >= OF 22A: -S'sum/.F R R

65 | ! a g e

Das könnte Ihnen auch gefallen