Upload
james-melton
View
258
Download
4
Tags:
Embed Size (px)
Citation preview
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Advanced Java Programming
CSE 7345/5345/ NTU 538NSession 2
Welcome Welcome Back!!!Back!!!
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
[email protected]@engr.smu.edu
Chantale Laurent-
Rice
Welcome Welcome Back!!!Back!!!
[email protected]@aol.com
Office Hours:by appt3:30pm-4:30pmSIC 353
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Introduction
• Chapter 1– Course Objectives– Organization of the Book
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Objectives
• Upon completing this chapter, you will understand – Create, compile, and run Java
programs– Primitive data types
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Book Chapters• Part I: Fundamentals of Programming
– Chapter 1 Introduction to Java
– Chapter 2 Primitive Data Types and Operations
– Chapter 3 Control Statements
– Chapter 4 Methods
– Chapter 5 Arrays
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Book Chapters, cont.• Part II: Object-Oriented Programming
– Chapter 6 Objects and Classes
– Chapter 7 Strings
– Chapter 8 Class Inheritance and Interfaces
– Chapter 9 Object-Oriented Software Development
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Book Chapters, cont.
• Part III: GUI Programming
– Chapter 10 Getting Started with GUI Programming
– Chapter 11 Creating User Interfaces
– Chapter 12 Applets and Advanced GUI
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Book Chapters, cont.• Part IV: Developing Comprehensive
Projects– Chapter 13 Exception Handling
– Chapter 14 Internationalization
– Chapter 15 Multithreading
– Chapter 16 Multimedia
– Chapter 17 Input and Output
– Chapter 18 Networking
– Chapter 19 Java Data Structures
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Chapter 1 • Objectives:• Get an overall perspective of what
capabilities and features are encompassed by Java and its development kit.
• Take a first look at Java syntax.• Getting Input from Input Dialog
Boxes • Style and Documentation
Guidelines
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
What is Java?• An Object-Oriented Programming Language
developed at Sun Microsystems• A Virtual Machine (run-time environment)
that can be embedded in web browsers (e.g. Netscape Navigator, Microsoft Internet Explorer and IBM WebExplorer) and operating systems.
• A set of standardized Class libraries (packages), that support:– Creating graphical user interfaces– Communicating over networks– Controlling multimedia data
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
History• James Gosling and Sun Microsystems
• Oak
• Java, May 20, 1995, Sun World
• HotJava – The first Java-enabled Web browser
• JDK Evolutions
• J2SE, J2ME, and J2EE (not mentioned in the book)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Characteristics of Java
• Java is simple• Object-Oriented• Distributed• Interpreted• Robust
• Secure• Architecture-
neutral• Portable• High-performance• Multithreaded• dynamic
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java is Simple
• Java is not just a language for use with the Internet.
• It is a full featured Object-Oriented Programming Language (OOPL).
• Java is a bit easier than the popular OOP language C++.
• Java uses automatic memory allocation and garbage collection.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
What is Object-Oriented Programming?
• Think of OOP as a set of implementation techniques that– Can be done in any programming
language– Are very difficult to do in most
programming languages– OOP provides great flexibility,
modularity, and reusability.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java is Distributed
• Distributed computing involves several computers working together on a network.
• Java’s concurrency features make is unique for developing many interactive and networked applications.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java is Interpreted• Java Virtual Machine:
– Java is compiled to byte-codes whose target architecture is the Java Virtual machine (JVM).
– The virtual machine is embeddable within other environments, e.g. web browser and operating systems.
– Utilize a byte-code verifier when reading in byte-codes. The class loader is employed for “classes” loaded over the network (enhances security)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java Virtual Machine
• JVM
Java Source code .java
Java byte-code .class
Environment
Java VMjavac java
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java is Robust• Robust means reliable.• No programming language can ensure
complete reliability.• Java puts a lot of emphasis on early
checking for possible errors, because Java compilers can detect many problems that would first show up at execution time in other languages.
• Java has a runtime exception-handling feature to provide programming support for robustness.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java Is Architecture-Neutral• Java is interpreted.• JIT compiler
– Just-in-time compilers– This provides
•Improved performance•Better match to specific hardware
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
JIT Compiler
• JIT- takes byte-codes and change it to machine code.
JVMRunning
Applet or Application
J.I.T.Compiler
.class file
machine code
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
JIT Compiler
• Because of the need for architecture independence, performance tuning must be performed on the client-side.
• This client-side compilation is known as Just-In-Time (JIT) compilation.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Portable, Dynamic, Multithreaded, and Extensible
• Java runtime based on architecturally-neutral byte-codes
(per class).• Multithreading is a program’s capability to perform
several tasks simultaneously.
interpretedJavaRuntime
Native .dll
Native .dll
call
loadedclasses
(byte-codes)
.classfiles
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Advantages• Byte-code is a compact machine
language form. In Java the target machine is the Java Virtual Machine (VM).
• These byte-codes are thus portable across architecture boundaries.
• Applets and Applications have “class” files loaded on their behalf in order to execute.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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.
This book uses J2SE to introduce Java programming.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java IDE Tools
• Forte by Sun MicroSystems • Borland JBuilder
• Microsoft Visual J++
• WebGain Café
• IBM Visual Age for Java
• IBM Eclipse
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Getting Started with Java Programming
• A Simple Java Application
• Compiling Programs
• Executing Applications
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Command Line Example 1.1//This application program prints Welcome//to Java! package chapter1;
public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }}
RunRunSourceSource
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Creating and Compiling Programs
• On command line– javac file.java
Source Code
Create/Modify Source Code
Compile Source Code i.e. javac Welcome.java
Bytecode
Run Byteode i.e. java Welcome
Result
If compilation errors
If runtime errors or incorrect result
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Executing Applications• On command line
– java classname
JavaInterpreter
on Windows
JavaInterpreter
on Sun Solaris
JavaInterpreteron Linux
Bytecode
...
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Command line Example
javac Welcome.java
java Welcome
output:...
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Compiling and Running a Program
Where are the files stored in the directory?
c:\example
chapter1 Welcome.class
Welcome.java
chapter2
.
.
.
Java source files and class files for Chapter 2
chapter19 Java source files and class files for Chapter 19
Welcome.java~
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
There are three forms of comments in Java.
1- int i = 10; // i is used as a counter2- The multiline comment /* This is a comment */
This form of comment may also extend over several lines as shown here:/* This is a longer comment
that extends over five lines.
*/
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
There are three forms of comments in
Java. 3- This is the documentation comment.
/** This is a Java documentation comment
*/The advantage of documentation comments is that tools can extract them from source files and automatically generate documentation for your programs. The JDK has a tool named javadoc that performs this function.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Package•The second line in the program (package chapter1;) specifies a package name, chapter1, for the class Welcome.
•Forte compiles the source code in Welcome.java, generates Welcome.class, and stores Welcome.class in the chapter1 folder.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Blocks
A pair of braces in a program forms a block that groups components of a program.
public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
Class block
Method block
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Block Styles
Use end-of-line style for braces.
public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } }
public class Test { public static void main(String[] args) {
System.out.println("Block Styles"); } }
End-of-line style
Next-line style
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
main MethodThe main method provides the control of program flow. The Java interpreter executes the application by invoking the main method. The main method looks like this: public static void main(String[] args) { // Statements;
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Displaying Text in a Message Dialog Box
• you can use the showMessageDialog method in the JOptionPane class.
• JOptionPane is one of the many predefined classes in the Java system, which can be reused.
RunRunSourceSource
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2", JOptionPane.INFORMATION_MESSAGE));
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
A simple Java Applet
import java.awt.*;import java.awt.event.*;import java.applet.Applet;import java.awt.Graphics;
/*<applet code="FirstApplet" width=200 height=200></applet>
*/
public class FirstApplet extends Applet{
public void paint(Graphics g){ g.drawString("This is my first applet!", 20, 100);}
}See word doc for output.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Integral Literals
• Integral literals may be expressed in decimal, octal, or hexadecimal.
• The default is decimal.• To indicate octal, prefix the literal with 0
(zero)• To indicate hexadecimal, prefix the
literal with 0x or 0X; • the hex digits may be upper-or
lowercase.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Integral Literals For example:
The value twenty-eight may be expressed the following ways:
28 034 0x1c 0x1C 0X1c 0X1C
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Integral Literals
• By default, an integral literal is a 32-bit value.
• To indicate a long (64-bit) literal, append the suffix L to the literal expression.
• The suffix can be lowercase, but then it looks so much like a one that makes it confusing.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Literals
• Literals are explicit data values that appear in your program.
• A literal is a value specified in the program source, as opposed to one determined at runtime. Literals can represent primitive or string variables, and may appear on the right side of assignments or in method calls. You cannot assign a value into a literal, so they cannot appear on the left of an assignment.
For example:
int x = 25;
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Boolean Literals • The only literals of boolean type
are true and false.
For example: 1. boolean isBig = true; 2. boolean isLittle = false;
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
char Literals
A char literal can be expressed by enclosing the desired character in single quotes,
For example:
char c = ' w ';
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Chapter 1 Topic Summary
• Java is many things– A concurrent object-oriented
programming language– A virtual machine and Web-aware
run-time– A powerful and stable set of class
libraries.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Chapter 2Liang, Nutshell
Objectives:• Introduce Programming with an
Example• Identifiers, Variables, and Constants• Primitive Data Types
– byte, short, int, long, float, double, char, boolean
• Expressions• Operators, Precedence, Associativity,
Operand Evaluation Order: ++, --, *, /, %, +=, -=, *=, /=, %=, ^, &, |, +, -,
• Syntax Errors, Runtime Errors, and Logic Errors
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java Reserved Words or Keywords
• abstract default if private this• boolean do implements protected throw• break double import public throws• byte else instanceof return transient• case extends int short try• catch final interface static void• char finally long strictfpvolatile• class float native super while• const for new switch• continue goto package synchronized
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Keyword and identifiers • An identifier is a word used by a
programmer to name a variable, method, class, or label.
• Keywords and reserved words may not be used as identifiers.
• An identifier must begin with a letter, a dollar sign (4), or an underscore (_); subsequent characters may be letter, dollar signs, underscores, or digits.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Examples • foobar // legal
• BIGinterface // legal
• $incomeAfterExpenses // legal
• 3_nodes5 // illegal
• !theCase // illegal
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Using Keyword
•Using a keyword as an identifier is a syntax error
•Keywords that are reserved, but not used, by Java–const–goto
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Reserved Words•Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program.
•For example, when the compiler sees the word class, it understands that the word after class is the name for the class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Java support eight different basic data
type • Type Description Keyword
• character 16-bit Unicode character data char• boolean true/false values boolean• byte 8-bit signed integer numbers byte• short 16-bit signed integer numbers short• integer32-bit signed integer numbers int• long 64-bit signed integer numbers long• float 32-bit signed floating-point numbers float• double 64-bit signed floating-point numbers double
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Primitive Data Type • Java's Primitive C++ Simple data type
data type integral floating
boolean char float char short long byte int long
double short long int enum long unsigned char float unsigned short double unsigned int
unsigned long
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Primitive Data Types and Operations
• Type Precision Default Valuebyte 8 bits 0short 16 bits 0
int* 32 bits 0long 64 bits 0char 16 bits \u0000float 32 bits +0.0fdouble 64 bits +0.0dboolean - false‘obj-ref’ - null
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Valid Control Character• Valid control character are:
– \b backspace– \t horizontal tab– \n linefeed– \f formfeed– \r carriage return– \” double quote– \’ single quote– \\ backslash– “dddd” for Unicode - is 0000 to hex ffff
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Operator Precedence• var++, var--• +, - (Unary plus and minus), ++var,--var• (type) Casting• ! (Not)• *, /, % (Multiplication, division, and modulus)• +, - (Binary addition and subtraction)• <, <=, >, >= (Comparison or Relational)• ==, !=; (Equality) • & (Unconditional AND)• ^ (Exclusive OR) • | (Unconditional OR) • && (Conditional AND) Short-circuit AND• || (Conditional OR) Short-circuit OR• =, +=, -=, *=, /=, %= (Assignment operator)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise OperatorsJava defines several bitwise
operators which can be applied to the integer types,
long, int, short, char, byte
These operators act upon the individual bits of their operands.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise OperatorsOperator Name ~ Bitwise unary NOT & Bitwise AND
| Bitwise OR ^ Bitwise exclusive OR >> Shift right >>> Shift right zero fill << Shift left
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise Operators
Operator Name
&= Bitwise AND assignment |= Bitwise OR assignment
^= Bitwise exclusive OR assignment >>= Shift right assignment >>>= Shift right zero fill assignment <<= Shift left assignment
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise NOT ( ~)• Also called the bitwise complement, the
unary NOT operator, ~ , • Inverts all the bits of its operand.
• Example Number 74 before bitwise NOT -> 01001010 after the NOT operator applied -> 10110101
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise AND ( & )• Produces a 1 bit if both operands are
also 1, otherwise a zero is produced. Example Number 74 & 29 -> 8
-> 0 1 0 0 1 0 1 0 -> & 0 0 0 1 1 1 0 1
After -> 0 0 0 0 1 000
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise OR ( | )• Combines bits such that if either of the
bits in the operands is a 1, then the resultant bit is a 1. A zero if both bits are zeros.
Example Number 74 | 29 -> 95
-> 0 1 0 0 1 0 1 0 -> | 0 0 0 1 1 1 0 1
After -> 0 1 0 1 1 1 1 1
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Bitwise XOR ( ^ )• Combines bits such that if exactly one
operand is 1, then the result is 1. Otherwise, the result is zero.
Example Number 74 | 29 -> 87
-> 0 1 0 0 1 0 1 0 -> ^ 0 0 0 1 1 1 0 1
After -> 0 1 0 1 0 1 1 1
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Left shift ( << )Right shift ( >> )
unsigned right shift ( >>>)• Left shift (>>) shifts all of the bits in a value
to the left a specified number of times.• Right shift (>>) shifts all of the bits in a value
to the right a specified number of times.• Unsigned right shift (>>>) automatically fills
the high-order bits with its previous contents each time a shift occurs. This preserves the sign of the value.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Relational or Comparisons Operators
Operator Name== Equal to!= Not equal to> Greater than< Less than>= Greater than or equal to<= Less than or equal to
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Relational OperatorsThe relational operators determine
the relationship that one operand has to the other
They determine equality and ordering.
The result of these operations is a boolean value.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Boolean Logical OperatorsOperator Name
& Logical AND| Logical OR^ Logical XOR (exclusive OR)|| Short-circuit OR&& Short-circuit AND! Logical unary NOT (inverts)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Boolean Logical OperatorsOperator Name
&= AND assignment|= OR assignment^= XOR assignment== Equal to!= Not equal to?: Ternary if-then-else
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Boolean Logical OperatorsThe Boolean Logical operators
operate only on boolean operands.
All of the binary logical operators combine two boolean values to form a resultant boolean value.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
The boolean Type and Operators
boolean lightsOn = true;
boolean lightsOn = false;
boolean b = (1 > 2);
&& (and) (1 < x) && (x < 100)• || (or) (lightsOn) || (isDayTime)• ! (not) !(isStopped)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Truth Table for Operator !Truth Table for Operator !
Operand !Operand
true false
false true
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Truth Table for Operator &&
Operand1Operand2Operand1 && Operand2
false false false
false true false
true false false
true true true
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Truth Table for Operator ||Operand1 Operand2 Operand1 || Operand2
false false false
false true true
true false true
true true true
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Truth Table for Operator ^
Operand1 Operand2 Operand1 ^ Operand2
false false false
false true true
true false true
true true false
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
The & and | Operators&&: conditional AND operator&: unconditional AND operator||: conditional OR operator|: unconditional OR operator
exp1 && exp2(1 < x) && (x < 100)
(1 < x) & (x < 100)
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
The & and | OperatorsIf x is 1, what is x after this expression?
(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?
(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?
(1 == x) || (10 > x++)?
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog( null, “Prompt Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE));where x is a string for the prompting message and y is a string for the title of the input dialog box.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Convertting Strings to Doubles
To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Read / Work With (Course Links)
• Liang, Nutshell Chapter 3-4• Life Cycle of Applets• List Of Basic Tags• Try It Editor
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Chapter 3 Control Statements
•Selection Statements–Using if and if...else–Nested if Statements–Using switch Statements–Conditional Operator
•Repetition Statements–Looping: while, do-while, and for–Nested loops–Using break and continue
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Selection Statements
• if Statements
• switch Statements
• Conditional Operators
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
CautionAdding a semicolon at the end of an if clause is a common mistake.if (radius >= 0);
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.
Wrong
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
switch Statementsswitch (year) { case 7: annualInterestRate = 7.25; break; case 15: annualInterestRate = 8.50; break; case 30: annualInterestRate = 9.0; break; default: System.out.println( "Wrong number of years, enter 7, 15, or 30");}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Repetitions
• while Loops
• do-while Loops• for Loops
• break and continue
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Chapter 4 Methods• Introducing Methods
– Benefits of methods, Declaring Methods, and Calling Methods
• Passing Parameters– Pass by Value
• Overloading Methods– Ambiguous Invocation
• Scope of Local Variables
• Method Abstraction
• The Math Class
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Introducing MethodsMethod Structure
A method is a collection of statements that are grouped together to perform an operation.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Methods• A method is essentially a set of program
statements. It forms the fundamental unit of execution in Java. Each method exists as part of a class.During the execution of a program, methods may invoke other methods in the same or a different class. No program code can exist outside a method, and no method can exist outside a class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Using Methods For example:
public class TheMethod{
public static void main(String[] args){
System.out.println(“First method”);}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
All methods are passed by value.
• All methods are passed by value. This means that copies of the arguments are provided to a method.
• Any changes to those copies are not
visible outside the method.
• This situation changes when an array or object is passed as an argument.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
call-by-value argument passing
• In this case the entire array or object is not actually copied.
• Instead, only a copy of the reference is provided.
• Therefore, any changes to the array or object are visible outside the method.
• However, the reference itself is passed by value.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
call-by-value argument passing
• Method a( ) accepts three arguments:
• an int• an int array• an object reference
The value of these arguments are displayed before and after the method call.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
call-by-value argument passing
• The key points to note are:
• The change to the first argument is not visible to the main( ) method.
• The changes to the array and object are visible to the main( ) method.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example:public class CallByValue{
public static void main(String[] args){
// Initializes variablesint i = 5;int j[] = { 1, 2, 3, 4, };StringBuffer sb = new StringBuffer("abcd");
// Display variablesdisplay(i, j, sb);
// call methoda(i, j, sb);
//Display variables againdisplay(i, j, sb);
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example (con’t)public static void a(int i, int j[], StringBuffer sb){
i = 7;j[0] =11;sb.append("fghi");
}public static void display(int i, int j[], StringBuffer sb){
System.out.println(i);for (int index = 0; index < j.length; index++)
System.out.print(j[index] + " ");System.out.println(" ");System.out.println(sb);
}}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Methods that return Values.
The return type for a method can be used in the Java
• The return type for a method can be
any type used in the Java programming language, which includes the primitive (or scalar) types int, double, char, and so on, as well as class type (including class types you create).
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Methods that return valuespublic class GettingARaise{
public static void main(String[] args){
double mySalary = 200.00;
System.out.println("Demonstrating some raises");
predictRaise(mySalary);System.out.println("Demonstrating my salary " +
mySalary);predictRaise(400.00);predictRaiseGivenIncrease(600, 800);
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Methods that return values public static void predictRaise(double moneyAmount) {
double newAmount;newAmount = moneyAmount * 1.10;System.out.println("With raise salary is " +
newAmount);}
public static void predictRaiseGivenIncrease(double moneyAmount, double percentRate){
double newAmount;newAmount = moneyAmount * (1 + percentRate);System.out.println("With raise predicted given salary is
" + newAmount);}
}