Pit
OS F A See BA.
PNICTOR | Stk ANbA[ Tix: ke
‘Therefore encapsulation isthe abilty to bundle the property and method of the object and alo operate them. isthe macs a 1
of comaining the Information and providing the abstraction as well
etymorphien -Rdescribes the ability ofthe object in belonging to diferent types with speci beravior of ear tYPE S° PY Se
thin one object can be treated ike another and inthis way it can create and define mute level of wtertace_ As ne SAT OES
‘ane nurne multiple form, Polymorphism Is the way that provide the different functionality by the functions taving De same
‘based! on tne signatures of the methods. There are two types of polymorphism first is run-time polymorphism and SECO"
‘compe tee pobymorphism.
Dyromic ding n
tra
iris the way tho provde the maximum functionality toa program fora specie type at runtime Tere are two toe f Bd “6
is dyoame binding and second is sai binding
Java Technology consists of:
1) Java Programming Language
2) Java Virtual Machine JVM)
3) lava Application Programming interfaces (APIs)
A. lave Programing Language
-the language consists of the following: features
1a) Platiorm Independent: The concept of Write-once-run-anywhere (known as the Piatform independent) is ane of the impose
rey feature of java language that makes java as the most powerful language. Not even a single language is oie to this feature 9
Java is oser to this feature. The programs written on one platform can run on any platform provided the piatiorm must have te
NM
‘a Simple: There are various features that make java a simple language. Programs are easy to write and debug Decause jave GOES
‘not use the pointers explicitly. It is much harder to write the java programs that can crash the system Dut we can not say about ME
‘ether programming languages. Java provides the bug free system due to the strong memory management. iso has the aviomatic
‘memory allocation and de-allocation system.
[Hava is designed to be easy for the professional programmer to learn and use.]
‘€) Object Oriented: To be an Object Oriented language, any language must follow at least the four characteristics.
‘© Inheritance: Itis the process of creating the new classes and using the behavior ofthe existing ciasses by extending them
Just to reuse the existing code and adding the adcitional features as needed.
Encapsulation: Itis the mechanism of combining the information and providing the abstraction.
> Polymorphism: As the name suggests one name multiple form, Polymorphism s the way of providing the different
functionality by the functions having the same name based on the signatures of the methods.
«© Dynamic binding: Sometimes we don't have the knowledge of objects about their specific types while weting our code, Ms
‘the way of providing the maximum functionality to @ program about the spect type at runtime.
‘ha the languages like Objective C, C+ fulfils the above four characteristics yet they are not ful object orients languages because
they are structured as well 3s object oriented languages. But in case of avait is fully Object Onente language because obec at
the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. EveryEning in ava
Js object even the primitive datatypes can also be converted into abject by using the wrapper class
fadean, usable, pragmatic approach to objects, not restricted by the need for compatiity with other languages)
EEElava nandies
Nanancles TERA protocols, accessing a resource through ts URL ‘much lke accessing a local file]
©) lnterpreteds Javais an inter
Be of Java as an interpreted language ists error debugging
‘the program gets traced. Ths is how itis diferent to work with Java
{ava programs are compiled into an intermediate representation =| byte
4) can be later interpreted by any JVM (Ser YRT LA, marching)
—sereee by any VM
) can be aso translated into the native machine code for efficienoy}
—=
code:
{2 Robust Java has the strong memory allocation and automatic garbage collection mechanism. it provides the powerful exception
handling and type checking mechanisy
nd ty im as compare to other programming languages. Compiler checks the program whether there
any eror and interpreter checks any Tanne erorand makes the sytem securetfomoresh Avie one a the
java language robust.
{restricts the programmer to find the mistakes early, performs comple-ime (strong typing) and run-time (exception-handting)
checks, manages memory automatically]
{£) Secure: Java does not use memory pointers explicit All the programs in ava are run under an area known asthe sand box
Sxcurty manager determines the acessblty options ofa clas like reading and writing a file tothe local dick ava uses the soc
Key encryption system to allow the java applications to transmit over the internet in the secure encrypted form, The byes nou
Verifier checks the classes after loading,
lnrograms are confined tothe Java execution environment and cannot acces ether parts ofthe computer)
bh) Architecture- Neutrat: Java is an architectural neutral language. The
distributed. In the world of network itis essential that the applications
‘ot only to computer systems but toa wide variety of hardware architecture and operating system architectures. The lave comply
does this by generating byte code instructions, to be easily interpreted on any machine and tobe easily transited inte hate
‘machine code on the fy. The compiler generates an architecure-neutral object fle format to enable a lava application to weecute
‘anywhere on the network and then the compiled code is executed
rowing popularity of networks makes developers think
‘must be able to migrate easily to different computer systems
‘on many processors, given the presence ofthe Java runtime system. Hence Java was designed to support applications on network,
{Java Virwal Machine provides a platform independent environment forthe execution of Java bytecode]
nywhere makes the java language portable provided that the system must have
Portable: The feature Write-once-run-anywhere makes the java language porta
E1Zeyreter forte JVM. lava also has the standard data se respective of operating system or the rscecar
ance: Java uses native code usage, and lightweight process called threads. in the begi
rs ern
ended. ses ecan
by muted ded language. Multithreading means a single program having different threads executing
rateoded pogamiing agua, -
si teste Mute tends eneutenacton seer othe moran cose hs preter or sega,
————————————Multithreading works the similar way 3s multiple processes run on one computer.
‘Murtnreading Brogrammingis avery interesting concept in Java, in mulithveaded programs nt even a single thread disturbs the
‘Secuton of otner thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUS.
{supports multi-threaded programming for writing program that perform concurrent computations}
{) Dynamic: White executing the java program the user can get the required files dynamically from local drive or from a computer
‘thousands of mites away from the user just by connecting with the Internet.
{substantial amounts of run-time type information to verify and resolve access to objects at run-time]
(What is an emmeution platform?
1) An execution platform is the hardware or software environment in which @
‘rogram runs, €-g. Windows 2000, Linux, Solaris or MacOS.
2) Mest platforms can be described as a combination ofthe operating
‘system and hardware,
4ava Execution Platform
‘What is tava Platform?
1) A sofeware-only platform that runs on top of other hardware-based platforms.
2} ava Platform has two components:
42) Java Virtual Machine (JVM) ~ interpretation forthe Java bytecode, ported onto various hardware-based platforms.
'b} The Java Application Programming interface (iava API)
Java Execution Platform
myP rogram java
Javea API
Java Virtual Machine
Hardware-Based Platform
|} save Piatrorm
Java programs are both compiled and interpreted:
‘Steps:
‘ write the Java program
+ compile the program into bytecode
‘execute (interpret) the bytecode on the computer through the Java
Virtual Machine
‘Compilation happens once.
Interpretation occurs each time the program is executed.
What is Java API
1)a large collection of ready-made software components that provide
many useful capabilities, eg. graphical user interface
3) grouped into libraries (packages) of related classes and interfaces,
3) together with JVM insulates Java programs from the hardware and
‘operating system variations
te regent
sc olrclptel aI
2 mand line, only need the Java Virtual Machine to run
—=—_————==E==5Tae eT | Lin CS
\ lavoked twough a “applet” referer
Sr ubases t te cent compu
‘serviets~ Java program running on the w
oe unning onthe web server, capable of responding to HTTP requests made through the network
nce on a web page, dynamically
FF recess Spectra in ove
These are called visiblity modifiers bec
(ed to specify particular characteris
aioe” Eve, yevhene
Metiods and slacses
use they control access to the members ofa class. A modifier isa Java reserved word that is
's ofa programming language construct.
‘an be accessed from anywhere. ‘where the object is visible, 4 h
Se frowns Sane Parckege ¢ Clase ond Supclase te te Sout pacpest O
rosters Pechoge y eras se
Caste cle seme anc ed within the same class to which the methods and fields belong, within its subclasses and
Be sina (emul ec Laut, Commof $e eakerslee! Lec Skctesros .
Methods and fields can. only be accessed within the same class to which
h the method and class belong. Methods and fields are not
‘aible within subclasses and are not inherted within subclasses,
Notes’
Java ls case sensitive
"afhtespace, tabs and newline characters are ignored except when pat of string constants
~ Statements terminate in semicolons,
7 Commas are used to separate words in alist
~ Square brackets are for arrays,
“Curly brackets are used for statement blocks
~ Round brackets are used for operator precedence and argument ists
Kress PACKAGE
Introduction to Java Package
In lava, a package is a group of related types classes and interfaces which provides access protection and name space management
{t0.use those classes and interfaces. Packaging is used to organize classes that belong to the same fle or providing si
functionality. Apart from this italso helps the programme to avoid class name callsion when we use the sa
availabe in other packages. For example two programmers can decide to come up withthe idea of supplying,
long as both of them place their class into different packages.
VOrg eu ve Clases
v New space Coltecsor-
Features of a Java package
lar
classname as
Employee class as
'* The protected members of the lasses can be accessed by each other inthe same package.
‘¢ Itresolves the naming collision for the types t contains.
‘¢ package may have the following types.
(© Interfaces
© Classes
© Enumerated types
‘© Annotations| Naming convention (Rules) for using the packages
Package names are written in all lowercase to avoid conflict withthe names of classes or interfaces
The directory name must be same a5 the name of package thats created using “package” keyword inthe source file
Before running @ program, the class path must be picked up till the main directory (or package) that is used in the program.
tt we are not including any package in our java source file then the source file automatically goes tothe default package.
in general, we start a package name begins with the order from top to bottom level.
In ease of the internet domain the name of the domain i treated in reverse (pref) order.
Secteur wt. Lo Reytverd PAekege.
Vetoes
Data types
‘The data types in the Java programming language are divided into two categories and can be explained using the following
hierarchy structure
GE.) oe
slat 3 fine)
3. bw 2 ewe
>
Primitive Data Types
‘The primitive datatypes are predefined datatypes, which vay old the value ofthe same datatype and value ofa primitive
dats type doit shore te state wth other pintve values. These datatypes are named bya reserves Keyword in
fave programming language
‘There are eight primitive data types supported by Java programming
Ajoyte
B-bit integer type.
“4
ages parcolary when working with data steams
2}short
16-bit integer type.‘s
!
Usage: probably the least used simple type.
ave
32-bit integer type.
Range: 2147483648 to 2147483647.
Baample
int b = -S0000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3) Expressions involving the byte,
to int before calculation,
ong
GA-bit integer type,
‘Range: 9223372036854775808 to 9223372036854775807.
Example:
{ong | = 10000000000000000;
Usages=
short and int values are promoted
11) useful when int type is not large enough to hold the desired value
Sioa:
32-bit floating-point number.
Range: 1.4e-045 to 3.404038.
Bample:
float f= 1.5;
Usage:
1) fractional partis needed
2) large degree of precision is not required
double
{64-bit floating-point number.
Range: 4.9¢-328 to 1.864308.
Example:
double pi = 3.1416;
Usage:
4) accuracy over many iterative caleulations
2) manipulation of arge-valued numbers
Example
17 Compute the area ofa circle.
class rea {
public static void main(String argst)
double pi = 3.1416; // approximate pi value
doubler = 108; // radius of circle
double a=pitr*r,// compute area
System out pintln(“Area of ciceis" +3);
,
)
Tchar
16-bit datatype used to store characters
Range: 010 65536.
example
char e='3'
Usage:
4) Represents both ASCII and Unicode character sets; Unicode defines a
character set with characters found in almost all human languages.
2} Not the same as in C/C++ where chars B-bit and represents ASCI ony
1/ Demonstrate char datatype.
class CharDemo {
—————————————_—_y\
VY public state wold mate(string ares)
teh) charcnt, cht:
enh 88; // code for x
easy;
Systern.out prit{*ch and ch2:");
System.out pritin{chi +" + ch2};
?
} ,
enoen Gig /FALSE)
‘Two-valued type of logical values.
eee
os
oo
io
ee
Se eee
ah
a
ae
ord
‘System.out.printin("b is" +b);
some
oe
Peee eee
es
prea
‘System.out.printin("10 > 9 is" + (10 >9));}}.
JE vartabe, constant and uke in tava
Variable : You can assign the values to the variable once it has been declared. The values of the variable can be changed anywhere in
the program ifthe variable is accessible in that scope. The variable intvariable has been used below to illustrate this.
Constants: Constants are declared using the final keyword. The values ofthe constant can't be changed once itis declared.
LUtera literals an explicit number or string constant used in Java programs.
Java Literals
By Iteral we mean any number, text, or other information that represents a value. This means what you type is what you get. We
tui use literals in addition fo varlables In Java statement, While wrting a source code asa character sequence, we can specify any
Value asa literal such as an integer. This character sequence will specify the syntax based on the value's type. This will give a literal
{asa result. For instance
int month = 10;
Inthe above statement the literal is an integer value i.e 10. The litera
InJave programming language there are some special typeof literals that represent numbers, characters, strings and boolean
valves. Lets have a closer look on each of the following.
Literals express constant values.
‘The form of a literal depends on its type:
1) integer types
2) floating-point types
3) character type
4) boolean type
5) string type
Integer Literals
Writing numbers with diferent bases:
1) decimal ~ 123,
=a
ely aycctal 0179
*,% 3)nexadecimal - 0178
Integer terais ae of type int by default.
Anteger literal written with “L” (e.g. 1231) are of type long.
‘Posting Potot Literals
“Two notations:
1) standard ~ 20005
2) scientine - 2.00053
Floating-point literals are of type double by default.
Floating-point literal written with “F” (e.g. 2.0005E3F) are of type float.
ootean Lerals
‘Two iterals are allowed only: true and false.
‘Those values do not convert to any numerical representation.
tn particular:
1) tae ts not equal to1
2) false is not equal to 0
(Character Uteras
‘Character terals belong to the Unicode character set.
Representation:
1) Visible characters inside quotes, eg. ‘a
2) invisible characters written with escape sequences:
2) \dd octal character ddd
) \wo00r hexadecimal Unicode character coc
OV single quote
d)\" double quote =
@) \ backslash \
A) \r carriage return
2) \nnew ine Newtek
h) \Fform feed =A”
\ttab
)\b backspace
‘String Literals
String is nota simple type.
String literals are character-sequences enclosed in double quotes.
Example:
“Hello World!”
Notes:
4) escape sequences can be used inside string literals
2) string literals must begin and end on the same line
3) unlike in C/C+s, in Java String is not an array of characters
‘Null Literals
‘The final literal that we can use in Java programming isa Null literal. We specify the Null literal in the source code as ‘nul’. To reduce
the number of references to an object, use null itera, The type ofthe null literal is always null. We typically assign null iterals to
object reference variables. For instance
‘An this example an object is referenced by s, We reduce the number of references to an object by assigning null tos.
Variables
Java uses variables to store data.
To allocate memory space fora variable VM requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
+3) optionally, the variable may be assigned an initial value
‘ll done as part of variable declaration,
—————————_—~==_——_—_—I4
4
7
a
Varia @ data type must be one of the following
can ple date Woe.
TA Lig Setinea date type calted a class type:
Options! intial valve
datatype identifier [=value];
Vartapie iaentiver must
“Confirm to tden'
We can declare several variables at the same time:
‘ype identifier [=value], identifier [=value] J;
pamoles:
int, b,c;
intd=3,¢,f=5;
byte hog = 22;
double pi = 3.14159;
char kat ='x'
Dr Constant Declaration
‘variable can be declare as fina
final double P= 3.16;
The value ofthe final variable egnnpt change after ithas been intiaized
Pi = 3.13; is not acceptable [wok oxteepeble
Variable identifiers
Identifiers are assigned to variables, methods and classes.
‘An identifier:
1) starts with a letter, underscore _or dollar $
2) can contain letters, digits, underscore or dolar characters
3) can be of any length
4) it must not be a keyword (€8. cass)
5) it must be unique in its scope
Examples: identifier, userName, _sys_varl, Schange
‘The code of Java programs is written in Unicode, rather than ASCI, so
letters and digits have considerably wider definitions than just a-z and 0-9.
Naming Conventions
‘Conventions are not part ofthe language.
Naming conventions:
1) variable names begin with a lowercase letter
2) class names begin with an uppercase letter
3) constant names are all uppercase
fa variable name consists of more than one word, the words are joined together, and each word after the first begins with an
Uppercase letter. The underscore characteris used only to separate words in constants as they are all caps and thus cannot be case-
delimit.
‘Variable Initialization
During declaration, varlables may be optionally initialized.5
_/ \wtialzation cn be static oF dynamic:
( * 4) atic _intialize with aiteral
inet;
2) dynamic _tntaize with an expression composed of any literals,
‘rabies or method calls avalabe atthe time of inialzation
inm=ne
‘The types of the expression and var
example:
double a=30,b= 40;
double c= Math sqrt(a “a+b );
“Ke variable Scope
‘Scope determines the visibility of program elements with respect to other program element.
tn tava, scope is defined separately for classes and methods:
4) variables defined by a cass have aIglobal2 scope
2) variables defined by a method have a lloca2 seope
We consider the scope of method variables only; clas variables wl be considered later.
Krys casing
General form: (targetType) value
Examples:
2) integer value willbe reduced module byte3s range:
int
byte b= (byte)
2) floating-point value wil be truncate to integer value:
float f Oloeeble b= Feu,
inti=(inys; ket @ = Chet) b;
2.tocal
These are variables declared ina method feonstruto block.
instance
‘These are declared in a class but outside a method. They are also called member or field variables
Eg class Myclass{ 7
Float afloat)
3. statis
SEE enon
int computefint a it b){
spowe, Harp eel New teed .
‘Awhitespace is space tab or new line,
Javais a form-free language that does Not require special indentation.
‘program could be writen like this:
class MyProgram {
public static void main(tringt] ares) {
System out println( "ist va program);
)
)
Te could be also written like this:
class MyProgram { public static void main(String[] args)
{ Syster.out.printn( ‘First Java program."
by Identifiers
id" on the console. The above line calls the printin method of System out class.
lethod does not return any value.
vel, Java programs consist of:
sa erie
sive tor spenaves method aes, vafableames
2 ea tna ica dears or characters that donot begin wth it
aan ee re earl ionic, Vous ted VALUE we a ateene
uot davonanen woeerosene
class MyProgram {
public static void main(String ares)(
aaa ot mtn ret Soe progam)
re of comments which are used. These comments are advantageous:
eed any programing language, ter ae seein of om ote a
so coaere pat they make the programme’ fel convenient to grasp the logic of he program Aout comments
fate roe Ct radeon gre le the eaters ttn nsee eee ee
7
\,
ee ‘used in Java, These are:
Life ees
| "Toads comment to the program, we can use two ashes characters ie /] The ine starting from lashes to the end on
25 acomment. We can write only a single line comment use these slashes. For instance
1/ This comment extends to the end of the ine.
11 This type of commenti called a"sash-stash comment
2. peest isto start with
To add a comment of more than one line, we can precede our comment using /* The precise way to use tis Sto stan wre
elimiter/* and end with delimiter */. Everything in between these two delimiters i discarded by the Java comp.
{J* This comment, a"slash-star" comment, includes multiple lines.
* febegins with the slash-star sequence (with no space between
‘the and '* characters) and extends tothe star-slash sequence.
”
Slash-star comments may also be placed between any Java tokens:
n/a ge eget MAK VALLE
* documentation */ o both, computer and
This ta special typeof comment that indicates documentation comment. This typeof comment is readable to bow, commer es
human. To start the comment, use /** instead of /° and end with */. This type of commenti 2 document
2 an official document on how the cass and its public method work, For instance
pe
* These are used to extract documentation from the Java source,
”
Example
rs
* MyProgram implements application that displays
* a simple message on the standard output
device.
”
class MyProgram
7° The main method ofthe lss-*/
public static void main(String ares){
Heisplay 9g
‘System. out prntn( ‘First Jova program":
)
)
€) Uterals :
‘literal is 2 constant value of certain type.
ftcan be used anywhere values ofthis type are allowed.
Examples:
2)100
bys8.6
ox
aytest” '
lass MyProgram:
Sabha wold main(String] ares
System.out.printin(“My first Java program.”
¥
}
<) Separatorsots
/v {0 parenthesis jists of parameters in method definitions and invocations, _—_—|
z | precedence in expressions, type casts
7 pa
,
[block of code. class definitions, method definitions, Tocal scope,
automatically initialized arrays
(1 prackets eclaring array types, referring to array values
t—-.
\. pameoion terminating statements, chain statements inside the “for”
| statement
, bomma ‘Beparating multiple identifiers in a variable declaration
1 1
Fiod Separate package names from subpackages and classes,
separating an object variable trom its attribute or method
1 Keywords
Keywords are reserved words recognized by Java that cannot be used as
identifiers. Java defines 49 keywords as follows:
‘Control Flow Statements
Java control statements cause the flow of execution to advance and branch based on the changes tothe state of the program,
Control statements are divided into three groups:
4) selection statements allow the program to choose different parts ofthe execution based on the outcome of an expression
2) iteration statements enable program execution to repeat one or more statements
3} jump statements enable your program to execute ina non-linear fashion
Selection Statements
‘ava selection statements allow to control the flow of program's execution
based upon conditions known only during run-time.
‘Java provides four selection statements:
aif 2) if-else 3)f-elseit 4) switeh
1.if Statement
“The i statement is the simpler form of control flow statement. It directs the program to execute 2 certain section of code, This code
Te executed fand only ifthe test evaluates to true. That isthe if statement in Java is 9 test of any boolean expressionGenera form:
i (expression) statement
tt expression evaluates to tre, execute statement, otherwise do nothing. The expression must be oft
‘Simple/Compound Statement
The component statement may be:
1) simple
\lexpresson)statemeni?
2) compound
if (expression) (
statement;
)
art)
System.out prntin( "Greater than 1°}
if(an2) ? n:n2;
ae
or
int larger= (nt
fo
re Soop }f
‘Array ist Preeleu Q6-144 Qof/F-
1 are going to be held in your array, we may us
vided and removed from the list. To set up an ArrayList, ou first have to imy
Syatem. out.printin ("nun
tfyou dont know how many Ker se an Arrays. An Arayist sa dynamic data
structure, meaning ters can be ymca
the java.util library: port the package fror
import ova ut. arayust
onan then create anew Araytst obec
Wrrayse seat = new Array
ery tat you dnt need any square brackets this time.
Notice tet Yr anew aay objets, you can a elements to with
gees. al rt er”
fntTestadal "second tem”
iseTestndl "hid Ker"
listTest.addl 7 )5
put what itis you wantto add tothe Aras You can only add objets, however. The
In between the round brackets of add you
noe tems we've added to thelist above ae tring objects The fourth Rem isa number. 8 willbe 3 nu ect of
integer, rather than the primitive datatype int.
Pein the ist can be referenced by an Index number,
niseTest.gett 3)
This line will get the
‘You can also remove items from af
listtest.removel2}:
‘or you can use the value on thelist:
Fietcldeas ka food. oka
the add method:
and by using the get method:
zero, 30 this will be the fourth item.
item at index position 3 on the list. Index numbers start count
wn Arraylist. You can either use the Index number:AstTest.removel “second item”);
Removing an item will resize the ArrayList, o you have to be careful when trying to get an item on the list when using its Index
number. if we've removed item number 2, then our ist above will contain only 3 items. Trying to get the item with the Index number
3 would then result in an error.
from the user
1. BufferedReader
‘Read Text from Standard 10: Java provides the standard I/O facilities for reading text through either the fle or Keyboard in
‘command line. This program illustrates you how to use standard input to read the user input.
The BufferedReader class isthe subclass ofthe FilterReader clas. BufferedReader class maintains the butfer and buffer state.
BufferedReader class supports the read{) and readLinel) method for input text from a character-input stream. n this program, 3s
You can see that the instance yariabe in ofthe BurferedReader class which reads a single line of text from the input steam.
achage wad SonderdiO,'
Import java-o.*;
public class ReadStandardiO{
public static void main(Stringl] args) throws !OException{
BufferedReader in = new BufferedReader(new inputStreamReader(System.in)};
System out printin(“Enter text
String str=In.readLine();
‘System.out printin( "You entered String
‘System.out printin(str;
,
)
2. Scanner
to read console input you fist construct a scanner that is attached to the standard input stream System.in
‘Scanner in = new Scanner(System.in); = >
Example:
System. out.printn("What is your name"
String namerin.nextLine();
-we use the nextLine method because the input might contain spaces
«to read a single word we use the in.next);
to read an integer we use the nextint() method
System.out.printin("How old Are you");
int age= in.nextint);
The nextOouble method reads the next floating point number
3.J0ptionPane
we inport from the javax.swing.* package
For inputting Strings
String input= JOptionPane.showinputDialog|promptString);
‘String names JOptionPane.showinputDialog("What is your name");
For reading numbers
« the method returns a string not a number
«We use the integer-parselntg or double parseDouble to convert the string tits numeric value
‘String input= JOptionPane.showinputDialog{“How old are you");
int ages Integer parselnt(input)
—public class ReadStandardiO{
public statle void main(Stringl] args) throws lOException{
BufferedReader in = new ButferedReader(new InputStreamReader(System.in))
System.out printin("Enter text :
‘String str= in.readLine();
System.out.printin("You entered String :")
‘System out printin(str};
,
,
Ke _
Some La bee Geos .
Zremmmee Slrnt moat be en lowbee 4
Sungnipanes
1] charatg) Method in tava
unos nour tctanprton
®
Shaie ets
arate
ne
import java.io.*;
class Charat(
public static void main(String ares)
try
BufferedReader object=new ButferedReader(new InputStreamReader(System.in));
‘System out printin("Enter the String");
String s-objectreadlLine();
Intlen=s.length();
‘System.out.printin(len);
‘char char=s.charAt(@);
‘System .out printin(charl};
y
catch(Exception e)
y
)
‘This program reads @ string as input through the keyboard. And first this shows the length ofthe string then find the character at the
4th (mentioned as a parameter of the method) pasition of the string that is retrieved by using charAt() method. The charAt()
method returns a character value for the character atthe given positon ofthe string.
Output this program:
Length 9
charat-i
Aerengtny Method in tava
used to find the length of a string
= This method return the length of this string as an integer value
———————————————_—_—_—_==aTT TTOEOEEE
clas StringLength{
public static vold main(Stringl] ares
tt
BufferedReader object=
new BufferedReader (new inputStreamReader(System.n));
‘ystem.out printin("Eneter string value:
String s=object readLine();
Int len=s length);
‘system out printin(len);
)
catch{Exception e}(})}
NB: Spaces are included when determining the length of the string
String End with Example
Determines whether a gven string ends with pecfied string Itchecks whether the given string starts with the specifed sting &
“false
true oF false by applying endsWith() method and returns Boolean types values either ‘true! oF
Syntax
endswith( string end
This is a Boolean type method that returns ether “true or Ylse.
Import java.iang
public class StrEndWith(
public statie void main(Stringl] ares) {
‘System.out printin("String end with example!
"Welcome to Samfurs";
*Samfurs";
System out.printin( “Given Sti
system out printin( “Ends with
if (str.endsWith(end)}{
system.out printin("The given
)
else
system.out printin(
)
)
)
Output of program:
ste);
end);
string is end with Samfurs");
(The given string isnot end with Sarnfurs"
strendWith java
strendwith
String end with example!
Given String : Welcome to Samfurs
End with : Samfurs
‘The given string is end with Samfurs
uo: You can select a section eg to determine whether the sentence ‘ends with rs
String Start with Example
seen whether the given string tarts om the specified sso javaWith String start}:
This is Boolean type method that returns either ‘true or ‘ase. Itchecks the given string that begins with specified string in the
beginning. it takes a string type parameter such as:
Import java.iang.*;
public class StrStartWith{
public static void main(String] args) {
‘System.out prntln(“String start with example!");
‘String str= "Welcome to Samfurs";
+30
art with: "+ start}
it ot startswith(start)
System .outprintn(“The given string starts with Wel);
)
ese(
System out printn("The given string doesnot start with Wel");
‘Substring
‘The substring extracts section ofthe whole string
Syntax:
substringtint
‘This method is used to find all sub string after index.
Z, soso sarin end:
“sis used tofnd the substring Between start and end pole.
‘The code of the program is given below:
‘public class SubstringExamplel{
public static vold main(String) args
String string = "Samuel Furusa";
System.out.printin("Strng :"+ string);
String substring = string.substring(3);
‘System out.printin("String after 3d index:
+ substring);
substring = string substring(, 2);
‘ystem.out.printin(*Substring (1,2): "+
substring);
)
)
“The output of the program is given below:
Vv Coniafene hou we Cobohen
Xe Lael. v Cake
v Gok wide,Output:
String: Samuel Furusa
‘String after 3 index: uel Furusa.
Substring(1,2}:
rset lt dU cluacles slob eg vtlen 0.
(Se
String t= name1 +name2;
F ‘replacing strings
~replaces old string with a new one.
String replace(char oldchar, char newchar);
String k="Furusa”;
ar eatin / i L
~2 cassis a template that defines what attributes an object can have
you can make one class definition then create objects for that class using the new keyword
an object is an instance of a class
-always use a capital letter for each class
cas deceraton 1 ae
# Sosmcent OF much mypafeince
‘/ffields,constructors and method deciaration
"class containa name several vail dehatins stance vb)
and several method declarations. Aare called members ofthe cass.
“the class bodylbetween th braces) contains al the code that provides forthe lifecycle ofthe object rested from the cassie
1. constructors for initaiing new object declorations forthe lds that provide the. state ofthe class and its objects
2 methods to implement the behavior ofthe cass and its objects
General form of a dass
C Lawneme
class classname { he:
iesarcevarabe ty forsee
Shahn eer es 5 f/Stoue Yor!
type instance-ariable-n;
type method-name-1(parameter-it (..)
type method-name-2(parameter-ist)(..)
type method-name-m(parameterlst){..)
y
2f Example of class
th cles with three variable members:
class Box{
SS"* [double width; ©
double height: fue Hew crm ravforuee Yow tapee
double dept
,
“Anew Bx obectiscreted and anew alu 3
and anew value assqnedto swith va
Box myBox = new Box{); . " te
mmyaoxwith
‘lass BoxDemo {
public static void main(String argsI)){
Box mybox = new Box();
nel
mybox.width = 10;
mybox.height = 20; Y i"
Pees Mole Pa (672)
‘vol = mybox.width * mybox.height * mybox.depth; c . ‘
system out.printin("Volume is" + vol)
j— I—
sun copy ofthe instance variables changing the variables of one object has no fest 0° variables of
Each object has its
another object.
Consider this example:
class BoxDemo2 {
public static void main(String argsO){
Box mybox1 = new Box);
Box mybox2 = new Box);
double vol;
mybox1.width = 10;
‘mybox height = 20;
mybox1.depth = 15;
mybox2.width = 3;
rmybox2.height = 6
mybox2.dept
idth * mybox1 height * mybox1.depth;
vol = mybox1.w!
System out priatin("volume i" + vol;
Sarterybox2. width * mybox2-height* mybor2. depth;
System out.printin("Volume is” + vo)
)
)
Declaring Objects
Deeaining objects of a classis 2140"
) Declare a variable of the classtype:
Box myBox:
‘The value of myBox isa refere
Jrthis moment, the value of myBox sul,
Jp acquire an actual. physical copy ofan oblect and 355
‘the variable. How to do this?
stage process:
nce to an object, fone exists, or mul.
ign its address to
Operator new
Secates memory fora Box object and returns adsress
Box myBox= new Box);
Fine addressis then stor
fed in the myBox reference variable,‘toxd) Is ass constructor -a class may deciare its own constructor or rely on the default constructor provided by the Java
envionment.
Methods
= these are a named group of declaration that can be invoked{executed) when needed
amethod is part ofa class
Method decaration
public double caleulateAnswer (int a, double b, int 2
Iealeuations
¥
HR Method: has 6 components in order.
‘L-modifiers- such as public, private protected
2. return type- the data type of the value returned by the method or void ifthe method does not return a value
3. Method name- the rules for field names apply to method names as well but the convention isa litle diferent
4. The parameter list in parenthesis-this is a comma delimited list of input parameters, preceeded by thei datatype, enclosed by
parenthesis
=f there are no parameters you must:
2) use empty parenthesis C)}
‘5. Exception Uist(optional) for erortrappingtry and catch). f{ 5.
6. The method body enclosed between curly braces- consists ofthe methods code and declaration of loal variables
Kraningamettod J
peter err eT Com.
San ae aee ee eo eeoeN meer Oh ee eee
Foe en er ncaneg rate patecqud compas, Se
ernest ctor meee
Sree
veaee
2 teeth m cj wer te mana chat ob
instance Example
aso
oer
ee eae momar
,
public static void main(Stieng args{I){
oe oracmen
‘System.out printin(calc.add(4,5));
;
}
D+ example? iP
class Box { higtenll Vola bles
double width, height, depth
void volume()
‘system.out print("Volume is");
‘ystem.out printin(width * height * depth);
y
)
When an instance variable is accessed by code that i not part of the class
in which that variable is defined, access must be done through an object:
class BoxDem03 (
public state void main(String ares) (
fox myboxl = new Box!)
Box mybox2 = new Box);»Sayoox with = 10; myx? width = 3;
tmybord.height = 20; mybox2.height=6
‘mybox1 depth = 15; mybox2.depth = 9;
‘mybox1.volume();
smybox2.volumel);
i
a.staticmathads — VO tncfonee Sor revble of ex obec/
use no instance variables of any object ofthe class they are defined in
= they take al the data from parameters and computer something from those para
smeters with no reference to variables
Static Example
public class Calculator{
public static void main(String argslIK
mee HContins he moped
int sum= sti;
‘system. out.printin("The sum is" + sum);
return sum;
)
1
Gres overloading
java supports overleading methods
“itcan distinguish between methods with different signatures
«is means that methods within a class can have the same if they have diferent parameter lists
sed into the method
senna nee are aeentited by te number andthe toe of arguments Pa
caer ere thn one method wih te same me ond same umber of rgument anda
x wars of "eu tl.tevtrl, CF Lr och
soe CA 9, Ant 2 B vary 7)
Jae acne, nto, sat tJ > 1 bff FY of eguem®c]s
okt petnoa overioeding :
Eiiss earculatort a Choong 4 Seren ty pos
ublic add(int a, int b)1 = ee _ >
publte Ane sesatan(rint 8 oer De befech crete ocler of 2, wad
ae ew) oS
poste Float a4d(Flost 2, fort 96
Systen.out .println("float and float”);
return a+b;
)
public float add(flost a, int b){
System-out.printin(“Float and int™
return a+b;
y
puptse static votd main(String [] args)(
Calculator A= new Calculator);
Systen.out.printIn(A.2dd (1,1
Systen.out printhn(A.adé(2.£,10.54));ARNEL SL Tt
S
frsttc Mathod Overloading
Aypolic class Calculator(
public static void main(String args(]){
int 2-10;
Ant b=65
int ge7
calc(a,b);
calc(a,b,8
¥
public static int cale(int s, dnt 3)(
Sint sun= 5433
System.out.println(“The sum 1s” + sun);
return’ sun}
?
public static int cale(int 5, int J,int b){
ne sums 54300;
Systen-out println("The sum 4s" + sun);
return sun, 7
>
3
= constructors
-Rconstructr initializes the instance variables of an objet.
“iis called immediately after the objectis created but before the new operator completes.
K Parenti es.
{Firs syntatcaly smart a method:
2) thas he same name a the name of lass
3) tis written without return type; the default return type ofa class constructor isthe same css
4) Constructors may include parameters of various parameters
5] When a constructors invoked using the new operator the types must match those thet ae specified inthe constructor
defnition
6) When the cass has no constructor, the default constructor automaticly initazesal its instance variables with zero.
examples
cess Bott
double wi :
double a Yorrerple 5
douse dept
Box() {
Fre ouprintn( constructing x"
Sian aornegne = 30, geptn 10
‘double volume(){
return width * height * depth;
y
y
/
lass Box
‘double width;
double height;
double depth;
Box\){
System out printia("Constructing Box")
width = 10; height= 10; depth = 10;
)
‘double volume) {
return width * height * depth;
)
)
——————————_—_—_—_—_—_—_—_—_—==~”“[=={nu
IN “odrs Construct
lass Box {
double width;
double height;
double depth;
Box(double w, double n, double 4) {
width = w; height = h; depth = 4;
)
double volune() { return width * height * depth; }
elas Boxbeno? {
public static void main(String args{]) {
Box myboxi = new Box(12, 28, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = myboxt.volune();
System.out.printin("Volune 1s * + vol);
vol = ybox2.volune();
t
bo —I—
ample 2
public class Cube1{
int length, breadth, height;
public int’ getvolune(){
return (lengeh*breatheheight);
cuber0¢
ength=195,
ietgnt=105
breadthe 1
}
Guber(ine 1, int b, Ant W)C
Length = 15
breadtheb;
heignt=hs
)
public static void main(string (J args){
Cuded evdeodj2= new Cubed);
bet cubeObj2= new Cube1(10, 20,30);
Systen.out printin ("Volume of Cubel 1s:
System.out.printin (“Volune of Cubel is!
tou may Scie tous the sie Fea tat of stance variables,
Te Use ne keyword tito eferto stance vaatles,
ub ss ec Bed
sate aay red haraeX [freed] Cheng
incu
Seteryouble rate nt unt double ed charge
three ate
thst nt
thstred. charge ed char;
,
Finalise) Method
‘Aconstructor helps to initialize an object just afte it has been created.
In contrast, the finalize method is invoked just before the object is
lia j—/——!
+ cubeobjt.getvolume());
4 cubeooj2.getvolune());
Sone now" b
Yortaptes hen
nsfernee eondy |
we we Jars beat
aca!
bee
aIe
4
}
) (2
‘implemented inside a class as:
protected void finalize(){..)
2) implemented when the usual way of removing objects from memory
Isinsufficient, and some special actions has to be carried out
Garbage collection is a mechanism to remove objects from memory when they are no longer needed.
Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many references an object has.
2) It removes an object from memory when it has no longer any references.
13) Thereafter, the memory occupied by the object can be allocated again.
4) The garbage collector invokes the finalize method.
rece
‘A package is both a naming and a visibility control mechanism:
1) Divides the name space into disjoint subsets, tis possible to
‘outside the package.
define classes within a package that are nat accessible by code
fe to define class members that are only exposed to other members
2) Controls the visibility of classes and their members. Its possibl
knowledge of each other, but nt expose that knowledge to other
‘of the same package. Same-package classes may have an intimate
packages.
Package Definition
‘Apackage statement inserted as the fist ine ofthe source fie:
package myPackage;
class MyClass {.)
class MyClass2 {~.)
se, The package statement creates a name space where such classes
‘means that all classes in this file belong to the myPackage packag
sg which has no name.
a caterers omg cas ner apna the deft aca
Toru te te seamen
soclage mPoctoge:
dss vast)
desman (2)
sectage my ucags
Shree
Fone ey eee ; ;
fe Dncpane Nene wus de of Gf caps.
package MyPack: a
ase elmer
foramen
Sate at
Balance(String n, double b) {
rome ol
y
void show {
Hf (bale) System.out print("->> "}
‘System.out.printin{name +": $° + ball;
)
4
class AccountBalance {rs
‘
joe sath wold main(String art)
ance current] = new Balancel
carrent{0} = new Balance(*K. Fielding”, 123.23);
carrent{t] = new Balance("Wil Tell”, 157.02);
current{2] = new Balance(*Tom Jackson”, 12.33);
for be te current{i}.show();
)
K.3. Flelding: $123.23,
‘Will Tell: $157.02
>> Tom Jackson: $-12.33,
‘Access Control
‘Classes and packages are both means of encapsulating and containing the
name space and scope of classes, variables and methods:
4) packages act as a container for classes and other packages
2) classes act as a container for data and code
‘Access control i set separately for classes and class members.
‘Access Control: Members
Four levels of access:
4) a member is availabe in the whole program:
public int variable;
public int method.) {.-}
2) members only available within the sme lass
prvate nt varabe:
Prvateint method).
4) members avlble within the same package faut ars
incvarble;
inerethodt (=)
‘a memberisvobl wii tesame cage at tecurent
rutin ssbb:
protecesinvarabes
ratectedint methodt-1{
protected ink mee cated iio ouside te cen pate
‘ccess control Summary
Ace ed pbc canbe esd om art
-Any member deere vate cannot be sen ouside Cas
Ary mem ee ox ave an acs sein fut a),
then mr le cen ato, ono nase Deen ecloe
sible to al classes within the same package
‘this member protected.E=
ie package subclass
ame package non-sub-class flo
— ———
Blfferent package sub-class ho
biferent package non-sub-class ho
_L
hhe access to classes, constructors, methods and fields are regulated using access modifiers Le. a class can control what information
‘or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and
constructors in your classes. A member has package or default accessibility when no accessibllty modifier Is specified. 7
Access Modifiers
1. private
2. protected
3.defautt
4. public
public access modifier
Fields, methods and constructors deciared public (least restrictive) within a public class are visible to any clas inthe Java program, f
whether these classes are in the same package or In another package.
private access modifier
‘The private (most restrictive fields or methods cannot be used for classes and interfaces. It also cannot be used for fields and
methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be
‘accesses by anywhere outside the enclosing lass. A standard design strategy isto make all elds private and provide publc getter
methods fr them.
protected access modier
‘The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an
interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages.
‘Casses n the same package can also access protected felds, methods and constructors as wel, even i they are not a subclass ofthe
protected member's cass.
itibr /AgtBitsfontsize=I8gt;
default access modifier
Java provides 2 default specifier which is used when no access modifiers present. Any cas, field, method or constructor that has
ro declared access modifier ls accesible only by lasses in the same package. The default modifiers not used for fields and
‘methods within an interface.
Below isa program to demonstrat the use of public, private, protected and default acess modifiers while accessing fields and
methods, The output of each ofthese java files depict the lava access specifiers.
re pat classi SubclassinsamePackage.jova which i present in pckagel package. This java file contains the Base class and 3
‘uoclass within the enclosing cass that belongs tothe same class as shown below.
package pckagel;
class BaseClass {
publicint x= 10;
private int y= 10;
protected int z= 10;
int a= 10; /Implict Default Access Modifier
public int getx){
return xee ee
public void setX(int x) {
thisx= x;
)
private int gety(){
returny;
)
rivate void setv(nty¢
thissy
}
Protected int getz(){
return 2;
Protected void setz(int 2) {
this =2;
Int gerag {
return a;
Void sevatint a) {
this,
)
public class SubclassinSamePackage extends BateClass{
Public stati void main(String are) (
BaseCiass rr = new BaseClass();
‘SubclassinsamePackage subClassObj
Uaccess Modifiers - Public
System.out printin("Value of x
subClass0bj.setX(20),
System.out printin("Value of xi
Udecess Modifiers - Public
}ew SubcassinsamePackagel};
+ subctass0bj);
+ subclassObix);
1, iwe remove the comments it would result ina compilaton
UW, error as the fields and methods being accessed are prnete
7% System out printn("Value of ys: “esubClassObjy)
subClassObjset¥(20};
System.out printin("Value of ys: "+subClassObj,y):*/
access Modifiers - Protected
System.out printin "Value of s:* + subctass0bj2);
subClassObj-setZ(30};
‘System.out printin("Value of s:" + subClassObj2);
Unecess Modifiers - Default
‘System.out printin( "Value of xis:
subClassObj setA(20);
System .out printin("Value of xis: + subClassObj.a);
* + subctassOb}a);yr
alee of218:30
vate of xis: 10
awe ofxis:20
‘he second classi SublasinoiferentPackage ava which spresentin a diferent package then the rst ne, This ava class extends
Fist dss (SubcassinsamePackage java)
import pckaget.*;
‘public class SubciassInDifferentPackage extends SubclassinSamePackage {
public int getZ220){
return
)
public static void main(tring args) {
‘SubClassinDifferentPackage subClassDiffObj = new SubClassinbifferentPackagel);
SubclassinSamePackage subClassOb) = new SubciassinSamePackagel);
‘H1dccess specifiers - Public
System out printn( "Value ofxis:* + subClass0bj.);
subClass0b)setX(30};
System out.printn(*Value of xis: "+ subClassOb) x);
Haccess specifiers - Private
J] weremove the comments t would result in a compliaton
UJ errors the felds and methods being accessed are private
[P System outprintin(Value of yi: “+subclassObjv}
subClassObjsetY(20);
system out printin( "Value of y is: “esubClassObjy:*/
[)hccess specifiers - Protected
71. ifwe remove the comments it would resutin a compilaton
1] error a the fields and methods being accessed are protected.
J Systemout prntin("Value of zs: "*subCass00)2);
subClass0bjsetZ(30),
system out println("Value of zis: “esubClassObi2);*/
Syetem out printin(Value of is:*+ subCassDifObj get2220:
[1access Modifiers - Default
J] Wwe emove the comments it would resut in a compilaton
J] error as the fields and methods being accessed are default
p
‘system out printla("Value of ais: "+subcassO0) 9},
subClassObjsetA(20),
system out printin("Value of ai :"esubctass0b).);
)
output
Value of xis: 10
value of xis :30
Value of 25:10
va ot css sCasinDierentPackage ava which prsentina diferent package then the rst onepublic class ClassinbitferentPackage {
Public static void main(String args()
SubclassinsamePackage subClassObj = new SubclassinSamePackagel);
Udecess Modifiers - Public
‘System out printin( "Value of xis: "+ subClassObj.a);
subClassObj-setX(30);
‘System. out printin("Value of x is:* + subClass0bj
Hpecess Modifiers - Private
11 Miwe remove the comments it would result in a compilaton
J] error asthe fields and methods being accessed are private
7° Systemout printin("Value of ys: "+subClassOb.y);
subClassObjset¥(20);,
‘yster.out printin("Value of ys: “+subClassObj,y;*/
H1hecess Modifiers - Protected
11 Wfwe remove the comments it would result in a compilaton
II erroras the fields and methods being accessed are protected.
7 System out priatin("Value of zis: “rsubClass0bj.2);
subClass0bj.setZ(30};
‘ystem.out prntin("Value of 2s: "+subClass0bj2);
Hnecess Modifiers - Default
11 if we remove the comments it would result in acompilaton
1] error as the fields and methods being accessed are default.
7* System out prntia("Value of ai: “+subClassObj.a);
‘subclassObjsetA(20);
‘ystem.out printin( ‘Value of ais.
‘You can import from another package using the import keyword
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String , double b){
fname =n; bal = b;
)
‘public void show(){
if (baled) System out print("~>> ")
‘ystem.out.printin(name +": $*+ ball;
)
1
“The Importing code has access to the publl elass Balance of the MyPack package and its two public members:
import MyPack.*goss TestBalance {
public static void main(String args) {
Balance test = new Balance("J. J. Jaspers", 9.88);
test show);
y
)
MK nema STAR]
One of the pillars of object-orlentation,
-In inherience a new class is derived from an existing class:
1) existing class is called guper-cass
2) derived clas is called sub-class
‘A sub-class is a specialized version of ts super-class:
4) has all non-private members of is super-class
2) may provide ts own implementation of super-cass methods
Objects ofa sub-class are a special kind of objects ofa superclass.
‘What snot possible using java class Inheritance? acces
1 Private members ofthe supecas arent inherited bythe subelassandcan ony be inet accessed,
2. Members that have default accesbilty nthe superclass are also not inherited by subclasses in other pac
‘members are only accessible by thei simple names in subclasses within the same package as the superclass,
3. Since constructors and initializer blocks are nat members ofa clas, they are pot inherited by asubCl@Ss. |, ogee.
4. Asubciass can extend only one superciass // CALe7 Extetref mol Hh Ore
Inheritance Syntax
Syntax:
class sub-class extends superclass {
;
Each class has at most one super-lass; no mult-inheritance in Java. No class isa sub-class of itself
public class A
inex:
public void #0
system.out.print("Java"
y
y
public class B extends A
int é;
y
public class C extends 8(
Inet
?
ic as xa
eric stati old meinString (1 =resK
‘hes new a0;
Boenew
Connew bs
bees
em:inheritance and Private Members 1
‘Adlass may declare some of its members private. A sub-class has no access to the private members of its super-class:
ass A{
Hes
pee et
When U bocer
; Yen ee long fo
lexjey
Snecma Wfowte Yone,
class 8 extends A{
int to
‘void surm(){
total =i;
y
»
* Uses of Super
Two uses of super:
1) to invoke the super-class constructor
supert); |
2) to access super-class members
super.variable;
super.method!..}:
“Super and Hiding
‘Why is super needed to access super-class members?
‘When a sub-class declares the variables of methods with the same names and types asitssuper- [0 O¥-o1OR /@ fencirmley of om
OX ESfLOG 1H
1 Se ae eee
‘The benefit of averriding is: ability to define a behavior that's specific'to the sub class typ ich means a subclass can implement a
Rules for method overriding:
‘© The argument list should be exactly the same as that of the overridden method.
© The return type should be the same or a subtype of the return type declared in the original overridden method in the super
class,
+The access level cannot Sve than the overridden method's acces lve. For example: if the super lass
Inthe is deced pub then he ovrling method ine sub css conot be eer private or publ: However the
acess levelcan be less restrictive than the overidden method's acces level
Instance methade can be overridden ony they are inherited bythe subclats.
‘method deciared final cannt be overridden
‘A method declared sali cannot be oatidde but canbe re-decared
fa method cannot be inher then Reannot be overridden
‘subclass within the same package asthe instance’s superclass can overtide any supercass method thats not declared
private oral
{subclass ina diferent package can only override the non-fina methods declared public or protected
‘An overiing method can throw any uncheck exceptions, regrdles of whether the overridden method throws exceptions
‘ormot. However the overridden method shoud not throw checked exceptions that are new or broader than the ones