Download presentation
Presentation is loading. Please wait.
Published byJames Melton Modified over 9 years ago
1
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Advanced Java Programming CSE 7345/5345/ NTU 538N Session 2 Welcome Back!!!
2
Liang, Oreilly, Herbert Schildt, Joseph O’Neil claurent@engr.smu.edu Chantale Laurent-Rice Welcome Back!!! trice75447@aol.com Office Hours: by appt 3:30pm-4:30pm SIC 353
3
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Introduction Chapter 1 –Course Objectives –Organization of the Book
4
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Objectives Upon completing this chapter, you will understand –Create, compile, and run Java programs –Primitive data types
5
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
6
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
7
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
8
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
9
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
10
Liang, Oreilly, Herbert Schildt, Joseph O’Neil What Is Java? History Characteristics of Java
11
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
12
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)
13
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
14
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.
15
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.
16
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.
17
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)
18
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Java Virtual Machine JVM Java Source code.java Java byte-code.class Environment Java VM javac java
19
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.
20
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
21
Liang, Oreilly, Herbert Schildt, Joseph O’Neil JIT Compiler JIT- takes byte-codes and change it to machine code. JVM Running Applet or Application J.I.T. Compiler.class file machine code
22
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.
23
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. interpreted Java Runtime Native.dll Native.dll call loaded classes (byte-codes).class files
24
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.
25
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)
26
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.
27
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
28
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Getting Started with Java Programming A Simple Java Application Compiling Programs Executing Applications
29
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!"); } RunSource
30
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating and Compiling Programs On command line –javac file.java
31
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Executing Applications On command line –java classname
32
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Command line Example javac Welcome.java java Welcome output:...
33
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Compiling and Running a Program Where are the files stored in the directory?
34
Liang, Oreilly, Herbert Schildt, Joseph O’Neil There are three forms of comments in Java. 1-int i = 10; // i is used as a counter 2-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. */
35
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.
36
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.
37
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Blocks A pair of braces in a program forms a block that groups components of a program.
38
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Block Styles Use end-of-line style for braces.
39
Liang, Oreilly, Herbert Schildt, Joseph O’Neil main Method The 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; }
40
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. RunSource
41
Liang, Oreilly, Herbert Schildt, Joseph O’Neil The showMessageDialog Method JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2", JOptionPane.INFORMATION_MESSAGE));
42
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; /* */ public class FirstApplet extends Applet { public void paint(Graphics g) { g.drawString("This is my first applet!", 20, 100); } See word doc for output.
43
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.
44
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
45
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.
46
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;
47
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;
48
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 ';
49
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.
50
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Chapter 2 Liang, 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
51
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Java Reserved Words or Keywords abstractdefault ifprivatethis booleandoimplementsprotectedthrow breakdoubleimportpublicthrows byteelseinstanceofreturntransient caseextendsintshorttry catchfinalinterfacestaticvoid charfinallylongstrictfpvolatile classfloatnativesuperwhile constfornewswitch continuegotopackagesynchronized
52
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.
53
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Examples foobar// legal BIGinterface// legal $incomeAfterExpenses// legal 3_nodes5// illegal !theCase// illegal
54
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
55
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.
56
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Java support eight different basic data type TypeDescriptionKeyword character 16-bit Unicode character datachar booleantrue/false valuesboolean byte8-bit signed integer numbersbyte short16-bit signed integer numbersshort integer32-bit signed integer numbersint long64-bit signed integer numberslong float32-bit signed floating-point numbersfloat double64-bit signed floating-point numbersdouble
57
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
58
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Primitive Data Types and Operations TypePrecisionDefault Value byte 8 bits0 short 16 bits0 int* 32 bits0 long 64 bits0 char 16 bits\u0000 float 32 bits+0.0f double 64 bits+0.0d boolean -false ‘obj-ref’ -null
59
Liang, Oreilly, Herbert Schildt, Joseph O’Neil The four signed data types are: byte short int long
60
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Valid Control Character Valid control character are: –\bbackspace –\thorizontal tab –\nlinefeed –\fformfeed –\rcarriage return –\”double quote –\’single quote –\\backslash –“dddd”for Unicode - is 0000 to hex ffff
61
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)
62
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Bitwise Operators Java 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.
63
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Bitwise Operators OperatorName ~Bitwise unary NOT & Bitwise AND | Bitwise OR ^Bitwise exclusive OR >>Shift right >>>Shift right zero fill <<Shift left
64
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Bitwise Operators OperatorName &=Bitwise AND assignment |= Bitwise OR assignment ^=Bitwise exclusive OR assignment >>=Shift right assignment >>>=Shift right zero fill assignment <<=Shift left assignment
65
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
66
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 Number74 & 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
67
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 Number74 | 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
68
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 Number74 | 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
69
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Left 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.
70
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Relational or Comparisons Operators OperatorName ==Equal to !=Not equal to >Greater than <Less than >=Greater than or equal to <=Less than or equal to
71
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Relational Operators The 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.
72
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Boolean Logical Operators OperatorName &Logical AND |Logical OR ^Logical XOR (exclusive OR) ||Short-circuit OR &&Short-circuit AND !Logical unary NOT (inverts)
73
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Boolean Logical Operators OperatorName &=AND assignment |=OR assignment ^=XOR assignment ==Equal to !=Not equal to ?:Ternary if-then-else
74
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Boolean Logical Operators The Boolean Logical operators operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value.
75
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)
76
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Truth Table for Operator ! Operand!Operand true false false true
77
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Truth Table for Operator && Operand1Operand2Operand1 && Operand2 falsefalsefalse falsetruefalse truefalsefalse truetruetrue
78
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Truth Table for Operator || Operand1Operand2Operand1 || Operand2 falsefalsefalse falsetruetrue truefalsetrue truetruetrue
79
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Truth Table for Operator ^ Operand1Operand2Operand1 ^ Operand2 falsefalsefalse falsetruetrue truefalsetrue truetruefalse
80
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)
81
Liang, Oreilly, Herbert Schildt, Joseph O’Neil The & and | Operators If 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++)?
82
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.
83
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”.
84
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
85
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
86
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Selection Statements if Statements switch Statements Conditional Operators
87
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Caution Adding 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
88
Liang, Oreilly, Herbert Schildt, Joseph O’Neil switch Statements switch (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"); }
89
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Repetitions while Loops do-while Loops for Loops break and continue
90
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
91
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation.
92
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.
93
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”); }
94
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.
95
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.
96
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.
97
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.
98
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example: public class CallByValue { public static void main(String[] args) { // Initializes variables int i = 5; int j[] = { 1, 2, 3, 4, }; StringBuffer sb = new StringBuffer("abcd"); // Display variables display(i, j, sb); // call method a(i, j, sb); //Display variables again display(i, j, sb); }
99
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); }
100
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).
101
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Methods that return values public 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); }
102
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); }
103
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Read / Work With (Course Links) Liang, Nutshell Chapter 4-6 Life Cycle of Applets List Of Basic Tags Try It Editor
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.