Download - part time class
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 1/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 2/79
Ch aracteristics of JavaJava is simpleJava is object-oriented
Java is distributed
Java is interpreted
Java is robust
Java is secure
Java is arc h itecture-neutral
Java is portable
Java s performance
Java is multit h readed
Java is dynamic 2
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 3/79
JDK Versions
JDK 1.02 (1995)JDK 1.1 (1996)Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
3
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 4/79
JDK Editions
Java Standard Edition (J2SE)± J2SE can be used to develop client-side standalone
applications or applets.
Java Enterprise Edition (J2EE)± J2EE can be used to develop server-side applications
such as Java servlets and Java ServerPages.
Java Micro Edition (J2ME).± J2ME can be used to develop applications for mobile
devices such as cell phones.
4
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 5/79
G etting Started wit h JavaProgramming
Overview of Java
Simple Java Application
Compiling ProgramsExecuting Applications
5
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 6/79
6
Overview of Java
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 7/79
H ow does Java work?
7
Java source code is compiled intomac h ine independent bytecodesTh e bytecodes can be run directly byan interpreterTh e bytecodes can be converted to
mach
ine code and executed ( Just inTime (JIT) compilation).An optimizing interpreter candynamically identify program
h otspots and create code optimizedfor t h e specific mac h ine/environment.
Optimizing interpreter coming soonfrom SUN.
Java Source code
Java ³Bytecodes´
Compiler
Mac Unix PC
Bytecode
Interpreter
JITCompiler
Machine Code
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 8/79
Java Data Types
Sizes fully specified by Java standard.Java is a very strongly typed languageInteger types± int (4 bytes signed)± sh ort (2 bytes signed)± long (8 bytes signed) use suffix L (eg 1000000000L)± byte (1 byte signed)
Floating-point types± float (4 bytes) use suffix F (eg 1.28F)± double( 8 bytes)
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 9/79
Additional Data Types
ch ar± Two-byte unicode
± Assignment with
e.g. c h ar c = h ;
boolean± true or false
e.g. boolean x = true;
if (x){ };
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 10/79
Operators/ Control Flow
Almost exactly like regular ANSI C .+, *, -, /, %, ++, --, +=, etc.==, !=, >, < , etc.if statements, for loops, w h ile loops, do loops, switc h statements, etc.continue, break, return, System.exit(0).
Read pp 54 in Core Java.No need to spend class time going over t h ese.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 11/79
Scoping
Braces are used as in C to denote begin/end of blocksBe careful of t h e following:int j = 0;
if ( j <1 ){int k = 2;
}
k = 3; //Error! k inaccessible h ereDeclarations do not propogate upwards.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 12/79
Adding datatypes -- classes
Java h as h andful of built-in datatypes just discussed(int, float, etc.)Just like in C , user typically creates own h omemadedatatypes to work wit h particular application (iestructs and enums ).In Java t h ese are called classes .
M any class definitions come as a standard part of t h eJava distribution. M ost common Example is Stringclass.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 13/79
Strings
Java provides a class definition for a type calledStringSince t h e String class is part of t h e java.lang package,no special imports are required to use it (like ah eader file in C).Just like regular datatypes (and like C), variables of type String are declared as:String s1;String s2, s3; //etc.Note t h at String is uppercase. T h is is t h e Javaconvention for classnames.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 14/79
Strings
Initializing a String is painlesss1 = Th is is some java String ;
Note t h at double quotes are required.M emory is allocated dynamically.Th ink of above met h od as s h ortcut for morestandard way (assuming s1 h as been declared):
s1 = new String( T h is is some java String );new operator required to create memory for newString object.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 15/79
Anatomy of a Java ProgramCommentsPackageReserved wordsM odifiersStatementsBlocks
ClassesM et h odsTh e main met h od
1 5
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 16/79
Comments
In Java, comments are preceded by two slashes (//) ina line, or enclosed between /* and */ in one or multiple lines. When the compiler sees //, it ignoresall text after // in the same line. When it sees /*, itscans for the next */ and ignores any text between /*and */.
1 6
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 17/79
Reserved Words
Reserved words or k eywords are words that have aspecific meaning to the compiler and cannot be usedfor other purposes in the program. For example, when
the compiler sees the word class, it understands thatthe word after class is the name for the class. Other reserved words in Example 1 .1 are public, static, andvoid. Their use will be introduced later in the book.
1 7
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 18/79
M odifiers
Java uses certain reserved words called m odifiers thatspecify the properties of the data, methods, andclasses and how they can be used. Examples of
modifiers are public and static. Other modifiers areprivate, final, abstract, and protected. A public datum,method, or class can be accessed by other programs.A private datum or method cannot be accessed by
other programs. Modifiers are discussed in Chapter 6,"Objects and Classes."
18
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 19/79
Statements
A statement represents an action or a sequence of actions. T h e statement System.out.println("Welcometo Java!") in t h e program in Example 1.1 is a
statement to display t h e greeting "Welcome to Java!"Every statement in Java ends wit h a semicolon (;).
19
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 20/79
Writing first program
To keep t h ings simple our first few programswill all be written as just a single mainprogram.In java, t h e file in w h ich your program residesmust contain a .java extension (e.g.M yFirstProgram.java).
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 21/79
Writing first program
Th en, t h e program must be wrapped in a classdefinition w h ich is t h e same as t h e filebasename ( M yFirstProgram). Careful, Java iscase-sensitive.
class M yFirstProgram { }
Finally, main is defined similar to C , but wit h afew more modifiers:
public static void main(String[] args){ }Th ese are all required . No s h ortcuts.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 22/79
A Simple Application
Example 1.1//This application program prints Welcome//to Java!
Public class Welcome {public static void main(String[] args) {
System.out.println("Welcome to Java!");}
}
22
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 23/79
Compiling/running first java program
Create source code file (call it for exampleM yFirstProgram.java).To compile:prompt >> javac M yFirstProgram.java
Th is produces byte code file namedM yFirstProgram.class
To run:prompt >> java M yFirstProgram
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 24/79
Creating and Compiling Programs
On command line± j avac file. j ava
24
ource ¡ ode
¡ reate/ ¢ odi£
y
ource ¡ ode
¡
ompile
ource¡
odei.e.¤
avac Welcome.¤
ava
¥ ytecode
Run¥
yteodei.e.¤
ava Welcome
Result
I¦
compilation err ors
I¦
runtime errors or incorrect result
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 25/79
Executing Applications
On command line± j ava classname
25
JavaInterpreter
on Windows
JavaInterpreter
on Sun Solaris
JavaInterpreter on Linux
Bytecode
...
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 26/79
Example
j avac Welcome. j ava
j ava Welcome
output:...
26
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 27/79
Observations
.class file is not mac h ine code. It is intermediate formcalled Java Byte code. Can run on any platform aslong as platform h as a Java Virtual M ac h ine (JVM ).
Th e second step on previous slide invokes t h e JVM tointerpret t h e byte code on t h e given platform.In th eory, byte code can be moved to anot h erplatform and be run t h ere wit h out recompiling t h is
is th
e magic of applets.Leave off t h e .class part w h en invoking t h e JVM .
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 28/79
Observations
Th is is an old-fas h ioned command-lineprogram. Java also supports G UI applicationsand web-browser h osted programs calledapplets .After t h e first couple of weeks we will usegrap h ical rat h er t h an scripting front-ends.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 29/79
Parsing Strings
Recall t h at t h e args array is an array of Strings. T h us,to accept key input as integers, float, etc. we mustconvert.
To convert to int, use t h e Integer.parseInt(String)function.Ex. String s1 = 32 ;
int j = Integer.parseInt(s1); // j now h olds 32
Converting to double is analogous:Ex. String s1 = 32 ;double j = Double.parseDouble(s1); // j now h olds 32
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 30/79
Parsing Strings
Note t h at t h e conversion met h ods are just regularprocedural functions. T h at is, no object was createdin order to call t h e met h od. T h e entity before t h e . is
_not_ an object.M
ore on th
is later.Wh at if t h e String is unparseable? (e.g. andrewrat h er t h an 32 ).Study t h e Integer and Double classes and look for a
description of th
e errors th
at are throw n by th
evarious met h ods. Does anyt h ing stand out? Seeexample Looper.java. M ore on t h is later.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 31/79
Th e Virtual M ac h ine
Java is both compiled and interpreted± Source code is compiled into Java b ytecode± Which is then interpreted by the Ja va Virtu al M a chine
(JVM)± Therefore bytecode is machine code for the JVM
Java bytecode can run on any JVM, on any platform± «including mobile phones and other hand-held devices
Networking and distribution are core features± In other languages these are additional APIs± Makes Java very good for building networked applications,
server side components, etc.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 32/79
Features of t h e JVM
Th e G arbage Collector± Java manages memory for you, t h e developer h as no control over t h e
allocation of memory (unlike in C/ C++).± Th is is muc h simpler and more robust (no c h ance of memory leaks or
corruption)± Runs in t h e background and cleans up memory w h ile application is
running
Th e Just In Time compiler (JIT)± Also known as H ot Spot± Continually optimises running code to improve performance± Can approac h th e speed of C++ even t h oug h its interpreted
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 33/79
Blocks
33
A pair of braces in a program forms a block thatgroups components of a program.
public class Test {public static void main(String[] args) {
System.out.println("Welcome to Java!");}
}
lass block
ethod block
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 34/79
Classes
The cla ss is the essential Java construct. A class is atemplate or blueprint for objects. To program in Java,you must understand classes and be able to write and
use them. The mystery of the class will continue to beunveiled throughout this book. For now, though,understand that a program is defined by using one or more classes.
34
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 35/79
M et h ods
What is System.out.println? It is a m ethod : acollection of statements that performs a sequence of operations to display a message on the console. It canbe used even without fully understanding the detailsof how it works. It is used by invoking a statementwith a string argument. The string argument isenclosed within parentheses. In this case, theargument is "Welcome to Java!" You can call thesame println method with a different argument toprint a different message.
35
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 36/79
main M et h od
The main method provides the control of programflow. The Java interpreter executes the application byinvoking the main method.
The main method looks like this :
public static void main(String[] args) {// Statements;
}
36
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 37/79
Th e exit M et h od
Use Exit to terminate the program and stop allthreads.
NOTE : When your program starts, a thread isspawned to run the program. When theshowMessageDialog is invoked, a separate threadis spawned to run this method. The thread is not
terminated even you close the dialog box. Toterminate the thread, you have to invoke the exitmethod.
37
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 38/79
Object Orientation
38
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 39/79
Introduction to OOP
39
Java is an object orientedprogramming language, so somerudimentary knowledge of OOterminology is required
Classes (e.g. Employee , Track )Objects
specific instances of a class (e.g.Tony Joh nson , Track 5 )
In Java all functions are containedwit h in classesFor largely h istorical reasonsfunctions are often called met h ods or
member functionsInh eritance (aka subclassing)
e.g. Associate Director , DriftCh amber Track
EncapsulationVariables/Functions can be declared:
privateonly functions wit h in same classor superclass can access t h em(c.f. C++ protected)
publicany function can access t h em
Java also implementsstatic
Applies to class not objectfinal
Cannot be overridden bysubclass
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 40/79
Wh at is OOP?
M odelling real-world objects in softwareWh y design applications in t h is way?± We naturally class ify objects into different types .
± By attempting to do t h is wit h software aim to make itmore maintainable, understandable and easier to reuse
In a conventional application we typically:± decompose it into a series of functions,
± define data structures th
at th
ose functions act upon± th ere is no relations h ip between t h e two ot h er t h an t h efunctions act on t h e data
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 41/79
Wh at is OOP?
H ow is OOP different to conventional programming?± Decompose t h e application into abstract data types by
identifying some useful entities/abstractions
± An abstract type is made up of a series of be h aviours andth e data t h at t h ose be h aviours use.
Similar to database modelling, only t h e types h avebot h be h aviour and state (data)
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 42/79
Wh at is an OO program?
Wh at does an OO program consist of?± A series of objects t h at use eac h ot h ers be h aviours in order to carry
out some desired functionality± Wh en one object invokes some be h aviour of anot h er it sends it a
message± In Java terms it invokes a method of t h e ot h er object± A met h od is t h e implementation of a given be h aviour.
OO programs are intrinsically modular± Objects are only related by t h eir public be h aviour (met h ods)
± Th erefore objects can be swapped in and out as required (e.g. for amore efficient version)± Th is is anot h er advantage of OO systems
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 43/79
Object-Oriented Programming
Understanding OOP is fundamental to writing good Javaapplications± Improves design of your code± Improves understanding of t h e Java APIs
Th ere are several concepts underlying OOP:± Abstract Types ( Classes)± Encapsulation (or Information H iding)± Aggregation
± Inh eritance± Polymorp h ism
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 44/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 45/79
Classesclass Employee{
public Employee (String n, double s){
name = n;salary = s;
}public Employee (String n)
{ name = n;salary = 0;
}public void raiseSalary(double byPercent){
salary *= 1 + byPercent / 100;
}public double getSalary(){
return salary;}private String name;private double salary;
}
Class Declaration
Private Member Variables
Constructor
Overloaded Constructor
Access Method
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 46/79
ObjectsObjects represent instances of classes
Employee j avaExpert = new Employee(³Joe´,100000);
j avaExpert.RaiseSalary(10); // Raise salary by 10%
system.out.println(³Salary is´ + j avaExpert.GetSalary());
Note t h at Java uses t h e keyword new for creation of new objects.Unlike C++ th ere is no delete keyword for t h e deletion of objects.
± Java h andles deletion of objects (and recovery of t h e memory t h ey occupy)automatically as soon as t h ere are no longer any references to t h em.
± Th is makes writing code muc h easier, it is impossible to create a memoryleak in Java..
± Th e process of keeping track of w h en objects are unreferenced and deleting
th
em is called garbage collection . It does impose some processing overh
eadwh ich slows down Java programs compared to equivalent programs in C orC++.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 47/79
Inh eritanceclass Manager Extends Employee{
public M anager (String n, double s, Employee e){
name = n;salary = s;secretary = e;
}public String GetSecretary(){
return secretary;}public void RaiseSalary(double byPercent){
double bonus = 10;super.RaiseSalary(byPercent + bonus);}private Employee secretary;
}
Class Declaration
New member variables
Constructor
New Access Method
Overridden Method
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 48/79
InterfacesInterfaces in Java are a replacementfor t h e concept of multipleinh eritance in C++.Suppose we want to sort managersby t h e number of employees t h eyh ave.
Interfaces± Objects can implement any number of
interfaces± Can h ave h ierarc h ies of interfaces± Interfaces cannot h ave met h ods± Cleaner but not quite as powerful as
multiple in h eritance± Only way to implement callbacks in
JavaEmployee
SortableManager
In C++ both Employee and Sortablecan be classesIn Java one (probably sortable) mustbe an ³interface´
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 49/79
Abstract Data Types
Identifying abstract types is part of t h e modelling/designprocess± Th e types t h at are useful to model may vary according to t h e
individual application± For example a payroll system mig h t need to know about Departments,
Employees, M anagers, Salaries, etc± An E-Commerce application may need to know about Users, S h opping
Carts, Products, etcObject-oriented languages provide a way to define abstractdata types, and t h en create objects from t h em
± It s a template (or cookie cutter ) from w h ich we can create new objects± For example, a Car class mig h t h ave attributes of speed, colour, and
be h aviours of accelerate, brake, etc± An individual Car object will h ave t h e same be h aviours but its own values
assigned to t h e attributes (e.g. 30mp h , Red, etc)
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 50/79
" § § ¨
rogramming" --©
bstract Types c ombine data and behaviour
--------------------
--------------------
--------------------
"Conventional¨
rogramming" --Functions or
¨
rocedures operating on independent data
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 51/79
Encapsulation
Th e data (state) of anobject is private itcannot be accessed
directly.Th e state can only bech anged t h roug h itsbe h aviour, ot h erwiseknown as its publici nterface or contract Th is is calledencapsulat i on
Private Data
Public Interface
"The Doughnut Diagram"Showing that an object hasprivate state and public
behaviour. State can only bechanged by invoking somebehaviour
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 52/79
Encapsulation
M ain benefit of encapsulation± Internal state and processes can be c h anged independently of t h e
public interface± Limits t h e amount of large-scale c h anges required to a system
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 53/79
Aggregation
Aggregation is t h e ability to create new classes out of existingclasses± Treating t h em as building blocks or components
Aggregation allows reuse of existing code± H oly G rail of software engineering
Two forms of aggregationWh ole-Part relations h ips± Car is made of Engine, Ch assis, W h eels
Containment relations
hips± A Sh opping Cart contains several Products
± A List contains several Items
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 54/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 55/79
OO Programming Concepts
data ield 1
method n
data ield n
method 1
n ob ect
...
...
tate
ehavior
Data Fieldradius = 5
Methodind rea
Circle ob ect
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 56/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 57/79
Class Declaration
class Circle {double radius = 1.0;
double findArea(){return radius * radius * 3.14159;
}}
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 58/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 59/79
Creating Objects
ob j ectReference = new ClassName();
Example:myCircle = new Circle();
Th e object reference is assigned to t h e objectreference variable.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 60/79
Declaring/ Creating Objects
in a Single StepClassName ob j ectReference = new ClassName()
Example:Circle myCircle = new Circle();
Diff b t i bl f
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 61/79
Differences between variables of primitive Data types and object types
1
c: Circle
radius = 1
Primitive type int i = 1 i
Object type Circle c c reference
Created usingnew Circle()
f
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 62/79
Copying Variables of Primitive DataTypes and Object Types
1
c1 : Circle
radius = 5
Primitive type assignmenti = j
Before :
i
2j
2
After :
i
2j
Object type assignmentc1 = c2
Before :
c1
c2
After :
c1
c2
c2: Circle
radius = 9
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 63/79
G arbage Collection
Consider, c 1 =c2. After the assignmentstatement c 1 = c2, c 1 points to the sameobject referenced by c2. The object
previously referenced by c 1 is no longer useful. This object is known as garbage.
arbage is automatically collected by JVM.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 64/79
G arbage Collection, cont
TIP : If you know that an object is no longer needed, you can explicitly assign null to areference variable for the object. The Java
VM will automatically collect the space if theobject is not referenced by any variable.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 65/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 66/79
Constructors
Circle(double r) {radius = r;
}
Circle() {radius = 1.0;
}
myCircle = new Circle(5.0);
Constructors are aspecial kind of methods that areinvoked to constructobjects.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 67/79
Constructors, cont.
A constructor with no parameters is referred to as adef a ul t constructor .
· Constructors must have the same name as the
class itself.· Constructors do not have a return type²noteven void.
· Constructors are invoked using the newoperator when an object is created. Constructorsplay the role of initializing objects.
Vi ibili M difi d
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 68/79
Visibility M odifiers andAccessor M et h ods
By default, t h e class, variable, or data can beaccessed by any class in t h e same package.
public
The class, data, or method is visible to any class in anypackage.
private
The data or methods can be accessed only by the declaringclass.
The get and set methods are used to read and modify privateproperties.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 69/79
InstanceVariables, and M et h ods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of the class.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 70/79
Cl V i bl C t t
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 71/79
Class Variables, Constants,and M et h ods, cont.
To declare class variables, constants, and methods,use the static modifier.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 72/79
Scope of Variables
Th e scope of instance and class variables is t h eentire class. T h ey can be declared anyw h ere
inside a class.Th e scope of a local variable starts from itsdeclaration and continues to t h e end of t h e blockth at contains t h e variable. A local variable mustbe declared before it can be used.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 73/79
Th e Keyword t h is
Use t h is to refer to t h e current object.
Use t h is to invoke ot h er constructors of t h e
object.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 74/79
1d Arrays
Arrays in Java are dynamic; t h ey are allocatedwit h th e new operator.Creating a (1d) array is a two-step process:int[] x; //declare x to be an array of ints
//x h as t h e value of null rig h t nowx = new int[100]; //allocate 100 ints wort h
At t h is point t h e values of x are all zeroes.Assignment is t h en just like C .
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 75/79
1d Arrays
Note t h at in Java, unlike C , t h e compiler will not letyou overrun t h e bounds of an array. G ive it a try.Note t h at you must use t h e new operator to size t h earray. It cannot be done statically as in C . Until t h is isdone, t h e array reference h as a value of null.Th e array comes wit h a field called lengt h wh ich stores t h e number of elements in t h e array. Tryprinting x.lengt h in t h e previous example. T h is is asimple but nice convenience.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 76/79
Array of Objects
Circle[] circleArray = new Circle[ 10 ];
An array of objects is actually an a rr a y of
reference v a ri abl es. So invokingcircleArray[ 1 ].findArea() involves two levels of referencing as shown in the next figure.circleArray references to the entire array.circleArray[ 1 ] references to a Circle object.
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 77/79
Array of Objects, cont.
Circle[] circleArray = new Circle[ 10 ];
re erence Circle ob ect 0 circleArray[ 0 ]circleArraycircleArray[ 1 ]
circleArray[ 9 ] Circle ob ect 9
Circle ob ect 1
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 78/79
8/7/2019 part time class
http://slidepdf.com/reader/full/part-time-class 79/79
Th ank You