+ All Categories
Home > Documents > Advanced Java Programming CSE 7345/5345/ NTU 531

Advanced Java Programming CSE 7345/5345/ NTU 531

Date post: 21-Jan-2016
Category:
Upload: stu
View: 34 times
Download: 0 times
Share this document with a friend
Description:
Welcome Back!!!. Advanced Java Programming CSE 7345/5345/ NTU 531. Session 4. Office Hours: by appt 3:30pm-4:30pm SIC 353. Chantale Laurent-Rice. Welcome Back!!!. [email protected]. [email protected]. What value is printed out at line 6?. - PowerPoint PPT Presentation
98
Liang, Oreilly, Herbert Schildt, Joseph O’Neil Advanced Java Programming CSE 7345/5345/ NTU 531 Session 4 Welcome Welcome Back!!! Back!!!
Transcript
Page 1: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Advanced Java Programming

CSE 7345/5345/ NTU 531Session 4

Welcome Welcome Back!!!Back!!!

Page 2: Advanced Java Programming CSE 7345/5345/ NTU 531

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

Page 3: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

What value is printed out at line 6?• // Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts

• 1. class Checking{• 2. public static void main(String args[]) {• 3. Holder h = new Holder();• 4. h.held = 100;• 5. h.bump(h);• 6. System.out.println(h.held);• 7. }• 8. }• 9.• 10. class Holder{• 11. public int held;• 12. public void bump(Holder theHolder) {• 13. theHolder.held++;• 14. }• 15. }

Page 4: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Input/output selection

• Introducing Java's Control Statements•  The if Statement • The if statement is one of Java's selection

statements (sometimes called conditional statements).

• Its operation is government by one of the outcome of a conditional test that evaluates to either true or false.

Page 5: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example• if (10 > 9)

System.out.println("true");  // Input/output selection

public class IfDemo{

public static void main(String[] args){

if (args.length == 0)System.out.println("You must have

command line argument");}

}

Page 6: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Remember

• Remember, a number is not a boolean. Therefore, it is not valid to have an if statement such as the following:

 if (count + 1)

System.out.println("Not Zero"); Such a line generates a compiler error.

Page 7: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

If-else statementpublic class IfDemo

{public static void main(String[] args){

if (args.length = = 0)System.out.println("You must have

command line argument");else

System.out.prinltn(“not good”);}

}

Page 8: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The for statement • The for loop is one of Java's three loop

statements. • It allows one or more statements to be

repeated and is considered by many Java programmers to be its most flexible loop.

 • The for loop is used to repeat a statement or

block of statements a specified number of times. Its general form for repeating a single statement is as followed:

for(initialization; test; increment) statement;

Page 9: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example• public class ForLoop

{public static void main(String[] args){ for (int num = 1; num < 11; num =

num + 1)System.out.print(num + " ");

System.out.println("terminating");}

}

Page 10: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The Increment operators • public class ForLoopIncr

{public static void main(String[] args){

for (int num = 1; num < 11; num ++)

System.out.print(num + " ");System.out.println("terminating");

}}

Page 11: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The decrement operators public class ForLoopDecr{

public static void main(String[] args){

for (int num = 1; num >= 11; num --)

System.out.print(num + " ");

System.out.println("terminating");}

}

Page 12: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

What value is printed out at line 6? • // Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts

• 1. class DecMe{• 2. public static void main(String args[]) {• 3. double d = 12.3;• 4. Decrementer dec = new Decrementer();• 5. dec.decrement(d);• 6. System.out.println(d);• 7. }• 8. }• 9.• 10. class Decrementer{• 11. public void decrement(double decMe){• 12. decMe = decMe -1.0;• 13. • 14. }• 15. }

Page 13: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Introduction

• Chapter 6 con’t– Objects and classes

Page 14: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

In this chapter

• Object-Oriented Programming

• Introducing classes and objects• Class methods• Input and output methods• Objects and garbage collection

Page 15: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Object and classes• Overloading Method Names• Overloading is the reuse of a method name in

the one class or subclass for a different method.• Overloading methods are effectively

independent, and there are no constraints on the accessibility, return type, or exceptions that may be thrown. Changing parameter names is not sufficient to count as overloading.

• public void oMethod(String s){ }• public void oMethod() { }• public void oMethod(int i, String s) { }• public void oMethod(String s, int i) { }

Page 16: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Consider this code 1. public class ConsideringIt{2. public float oMethod(float a, float b){3. }4. }

Which of the following methods would be legal if added (individually) at line 4?

a. public int oMethod(int a, int b) { }b. public float oMethod(float a, float b) { }c. public float oMethod(float a, float b, int c )

throws Exception { }d. public float oMethod(float c, float d) { }e. private float oMethod(int a, int b, int c) { }

Page 17: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class

• The keyword class indicates that a class names clsName is being declared.

• This name must follow the Java naming conventions for identifiers.

Page 18: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class (con’t)

• Constructors always have the same name as the class. They do not have return values.

Page 19: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Declaring classes

• A class begins with the class keyword followed by braces that delimit the class’s content:– class AnyClass– {

• ……….

– }

Page 20: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Declaring classes

• Most classes have one or more methods, such as main(), which is found in all stand-alone Java applications.– Class AnyClass– {

• public static void main(String[] args)• {

– //statements inside main( )

• }

– }

Page 21: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Declaring classes• You can also create other methods and call them from

main() and from other places.class AnyClass{

public static void main(String args[]){

HiThere(); // Call HiThere( ) method}

public static void HiThere(){

System.out.println("Hi There!");}

}

Page 22: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class Name

• Class names are usually capitalized.

• Variables and methods begin with lowercase letters.

• These conventions are not requirements, but help make program clearer to read and understand.

Page 23: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class Bagclass Bag

{boolean flag;int i, j =2, k = 3, l, m;double array[] = { -3.4, 8.8e100, 09.2e-

100};String s1, s2 = new String(“Hello”);

}

Page 24: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class Bagclass BagTest{

public static void main(String[] args){

Bag bag = new Bag();System.out.println(bag.flag); System.out.println(bag.i); System.out.println(bag.j); System.out.println(bag.k); System.out.println(bag.l); System.out.println(bag.m);for(int i =0; i < bag.array.length; i++)

System.out.println(bag.array[i]); System.out.println(bag.s1); System.out.println(bag.s2);

}}

Page 25: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Object-oriented key concepts:

• In Java, object-oriented programming revolves around a few concepts:

• classes • objects • data members • methods• and inheritance

Page 26: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Questions to consider….

• What are those terms mean:• classes, • objects, • data members, • methods, • and inheritance.

Page 27: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Which one statement is true about this code?a. Line 8 will not compile, it is static reference to a private variableb. line 13 will not compile, because it is a static reference to a private variablec. The program compiles, and the output is x = 102.d. The program compiles, and the output is x = 103.e. The program compiles, and the output is x = 104.

• 1. class HasStatic• 2. {• 3. private static int x =100;• 4. • 5. public static void main(String args[]) • 6. {• 7. HasStatic has1 = new HasStatic();• 8. has1.x++;• 9. HasStatic has2 = new HasStatic();• 10. has2.x++;• 11. has1 = new HasStatic();• 12. has1.x++;• 13. HasStatic.x++;• 14. System.out.println("x = " + x);• 15. }• 16. }

Consider this code

Page 28: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating an object

• To create a object, you call a class’s constructor, which is a method with the same name as the class itself.

• This constructor creates a new object of the class.

• You call an instance of a class an object.

• An object is a variable.

Page 29: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating an object

• An object occupies space in memory, and it must be initialized.

Page 30: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The new Operator

• Up to this point, you have been creating objects indirectly, such as through the use of some Java’s static methods.

• It is now time to learn how to create an object directly.

Page 31: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Objects

• Objects are created using the new operator.

• Or, put differently, the new operator creates an instance of a class.

• It is invoked as follows:– clsName ObjRef = new

clsName(args);

Page 32: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating objects

• clsName is the name of the class to be instantiated.

• Instantiated means to create an instance of that class.

• A reference to the new object is assigned to a variable name objRef.

• Notice the expression immediately to the right of the keyword new. – clsName ObjRef = new clsName(args);

• This is known as a constructor.

Page 33: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Constructor

• A constructor creates an instance of a class.It has the same name as the class and may optionally have an argument list args.

• The next slide illustrates the relationship between objects and object reference variables.

• In the diagram, the variable named varA refers to one object.

• Variables named varB and varC both refer to a second object.

• The third object is referred to by the variable named varD.

Page 34: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Objects and object references

• Here, i is a simple int value and s is a String object. Notice that the second form of the constructor can throw an exception if the constructor argument is not correctly formatted.

• The first form of the constructor cannot throw an exception because any int can be used to create an Integer object.varA

varB

varC

varD

Object

Object

Object

Page 35: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Keypoint

• A key point to understand is that the variable is distinct from the object.

• In effect, a variable that serves as an object reference has an implicit pointer to the object.

• However, a Java programmer cannot directly access the pointer.

• Also note that multiple variables may refer to the same object.

Page 36: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The symbol null

• The symbol null has a special meaning in Java.

• It represents the value of an object reference variable when that variable does not reference any object.

Page 37: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Again Classes and Objects

• Classes and objects form the building blocks of any Java program.

Therefore, a basic understanding of them is necessary.

Page 38: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Constructor Modifiers

These are three modifiers that may precede the declaration of a constructor.

These are summarized in the following table:Keyword Meaning

Private Can be invoked only by code in the same class

Protected Can be invoked only by code in a subclass or the same

package

Public Can be invoked by any other class

Page 39: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Constructor Modifiers

• These modifiers are mutually exclusive.

• If none is specified• The default is that only code in

the same package may access that

• constructor.

Page 40: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example:class Person{

// declare variable;String name;int age;

public Person(String name, int age){

this.name = name;this.age = age;

}

private Person() {

}}

Page 41: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Exampleclass PrivateConstructor{

public static void main(String[] agrs){

// Public constructor may be invokedPerson p1 = new Person(“John”, 30);System.out.println(p1.name);System.out.println(p1.age);//Private constructor may not be invoked//Person p2 = new Person();

}}

Page 42: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Method Modifiers

• There are eight possible modifiers that may precede the declaration of a method.

• These are summarized in the following table:

Page 43: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Method ModifiersKeyword Meaning Abstract Is not implement by this

class

Final May not be overridden

Native The method is implemented in the machine Code used

by the host CPU, not using Java bytecodes.

Page 44: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Method ModifiersPrivate Can be invoked only by code in the

same class

Protected Can be invoked only by code in a subclass. Or the same package

Public Can be invoked by any other class

Static Is not an instance variable

Synchronized Acquires a lock when it begins execution.

Page 45: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

MeaningsIf a class contains an abstract method, that class itself must also be declared abstract. Otherwise, the Java compiler issues an error message.

The public, protected, and private modifiers are mutually

exclusive.

The synchronized modifier is very important in multithreaded programming.

The native modifier is beyond the scope of programming.

If none of these modifiers are specified, the method is assumed to be a non-abstract, non-final, non-native, non-synchronized method. It may be accessed only by code in the same package.

Page 46: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example• The class JetPlane declares one abstract method

named numEngines().• Therefore, the class itself must also be declared

abstract.• There are two concrete subclasses named DC8 and

DC10. Each of these provided a different implementation of numEngines() method.

• The main() method instantiates each of these classes and invoke its numEngines method.

• This is an excellent example of run-time polymorphism.

• Each subclass provides a different form of the method.

Page 47: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

abstract class JetPlane{

abstract int numEngines();

}class DC8 extends JetPlane{

int numEngines(){

return 4;}

}

class DC10 extends JetPlane

{int numEngines(){

return 3;}

}

Page 48: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example cont

class JetPlanes{

public static void main(String[] args){

System.out.println(new DC8().numEngines());

System.out.println(new DC10().numEngines());

}}

Page 49: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Chapter 7 The StringBuffer Class

• There is no way to change the character sequence encapsulated by String object after it is created.

• The StringBuffer class also encapsulates a sequence of characters.

Page 50: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Its constructor has the following forms:

• /* This form of the constructor initializes the buffer size to 16 character*/

StringBuffer( )

• /*This form explicitly sets the buffer capacity to size characters*/

StringBuffer(int size)  • /*This form initializes the buffer with the contents of s

and also reserves another 16 characters for expansion*/

StringBuffer String s

Page 51: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Create StringBuffer objects

• This example creates StringBuffer objects by using the three form of constructors and displays their current capacity and sizes.

Page 52: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Examplepublic class StringBufferExample{

public static void main(String[] args){ StringBuffer sb1 = new StringBuffer( ); StringBuffer sb2 = new StringBuffer(30 ); StringBuffer sb3 = new StringBuffer("abcde" );

  System.out.println("sb1.capacity = " +

sb1.capacity( ));

System.out.println("sb2.capacity = " + sb2.capacity( ));

System.out.println("sb3.capacity = " + sb3.capacity( ));

 System.out.println("sb3.length = " +

sb3.length( ));}

}

Page 53: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Read / Work With (Course Links)

• Liang, Nutshell Chapter 7-9• Life Cycle of Applets• List Of Basic Tags• Try It Editor

Page 54: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating Strings//Creating a String object:public class StringObject{

public static void main(String[] args){

String s1 = "Hello from Java";String s2;String s3 = new String();s2 = "Hello from s2 Java";//s3 = new String();s3 = "Hello from s3 Java!";System.out.println(s1);System.out.println(s2);System.out.println(s3);

}}

Page 55: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Question

• 1. Can you change a String object at runtime? Why?Why not?

• 2. What is the default constructor of a String class?

• 3. Is a class an object?• 4. What are the Java’s String class

constructors?

Page 56: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

String:

• String: use this one for fixed length strings that will not change at run-time. A String object is immutable.

• StringBuffer: use this class for variable-length strings that might change at runtime. A StringBuffer object is mutable.

Page 57: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Getting String Lengthpublic class StringLength{

public static void main(String[] args){

String s1 = "Hello from Java!"; System.out.println("\"" + s1 + "\"" + "is

" + s1.length() + " characters long.");

}}

Page 58: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Concatenating Strings• Concatenating strings means joining them together.

// Concatenating strings means joining them together.public class Concatenating{

public static void main(String[] args){

String s1 = "Hello!";String s2 = s1 + "from";

String s3 = s2 + "Java"; String s4 = s1.concat("from"); String s5 = s4.concat(" Java!");

System.out.println(s3); System.out.println(s5);

}}

Page 59: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Getting Characters and Substring

public class GettingChar{

public static void main(String[] args){ String s1 = "Hello from Java!"; char c1 = s1.charAt(0); System.out.println("The first character of

\"" + s1 + "\" is " + c1);}

}

Page 60: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Converting a String object into a char array//Using toCharArray and getChars

public class GettingCharArray{

public static void main(String[] args){

String s1 = "Hello from Java!";char c1 = s1.charAt(0);System.out.println("The first character of \"" + s1 +

"\" is " + c1);char chars1[] = s1.toCharArray();

System.out.println("The second character of \"" + s1 + "\" is " + chars1[1]);

char chars2[] = new char[5];s1.getChars(0, 5, chars2, 0);System.out.println("The first five character of \"" +

s1 + "\" are " + new String(chars2));}

}

Page 61: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Searching for and replacing Strings// Using indexOf, lastIndexOfpublic class IndexOf{

public static void main(String[] args){

String s1 = "I have drawn a nice drawing!";System.out.println("The first position of draw is

" + s1.indexOf("draw"));System.out.println("The last position of

draw is at location " + s1.lastIndexOf("draw"));

String s2 = "Edna, you're hired!";System.out.println(s2.replace('h', 'f'));

}}

Page 62: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Changing Case in Strings//Using toLowerCase, toUpperCasepublic class LowerUpperCase{

public static void main(String[] args){ System.out.println("Hello from Java!".toLowerCase()); System.out.println("Hello from Java!".toUpperCase());}

}

Page 63: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Formatting Numbers in Strings//Formattingimport java.text.*;public class Formatting{

public static void main(String[] args){

double value = 1.23456789;NumberFormat nf =

NumberFormat.getNumberInstance();nf.setMaximumFractionDigits(6);String s = nf.format(value);System.out.println(s);

}}

Page 64: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The String class

• The String class provides several good examples of instance methods.

• You may declare a variable of type String and initialize it with a string.

• Example:– String s = “Enter an integer value: “;

• After this statement executes, s contains the string “Enter an integer value:.”.

• You can use it anywhere.• (see Table 2-2)

Page 65: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

Class First10Chars{

public static void main(String args[]){

String s = “One Two Three Four Five Six Seven”;String substring = s. substring(0, 10);System.out.println(substring);

}}

Page 66: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Output

• One Two Th

• It s=displays the substring formed by the first 10 characters of string

Page 67: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Integer Class

• Integer is one of the commonly used classes in the Java class libraries.

• An integer object encapsulates a simple int value.

• In other words,• Integer is a wrapper class for int.• Integer is an excellent example of a

class that provides both static and instance methods.

Page 68: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The Integer MAX_VALUE

• The Integer class defined MAX_VALUE and MIN_VALUE as two of its static variables.

• These contain the maximum and minimum values that can be accommodate by the 32 bits of a simple int type. (See table 2-3, 2-4)

Page 69: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Table 2-3, 2-4

• Table 2-3 summarizes some of the most commonly used static methods of this class.

• Notice that some of these methods can generate an exception if their string argument is not correctly formatted.

• Table 2-4 summarizes some of the most commonly used instance methods of this class.

Page 70: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

The following program illustrates how some of the Integer static

and instance methods can be used.

public class StringToInt{

public static void main(String[] args){

//Declare variablesString s = “125”;Integer obj = Integer.valueOf(s);int i = obj.intValue();i += 10;System.out.println(i);

}}

Page 71: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Explain please….

• The main() method begins by assigning a string literal to variable s.

• The static method valueOf() accepts this String object as an argument.

• It creates a new Integer object that encapsulates the value represented by s and returns this object.

• This object is assigned to the variable obj.

Page 72: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Keep explaining…

• The instance method named intValue() is then used to obtain a simple int equivalent to the value encapsulated by obj.

• The value returned by this method is assigned to the variable i.

• The variable i is incremented by 10 and displayed by println().

Page 73: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Output

• The output is 135

Page 74: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Chapt 8 con’t Inheritance

• Inheritance and variables• The class inherits the state and behavior

defined by all of its superclasses.• State is determined by variables;• Behavior is determined by methods.

• Therefore, an object has one copy of every instance variable defined not only by its class but also by every superclass of its class.

Page 75: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Inheritance and Variables

• A static or instance variable in a subclass may have the same name as a superclass variable.

• In that case, the variable hides the superclass variable.

• These two variables may have the same type or different types.

Page 76: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Inheritance and variables

• The following application demonstrates a class inheritance hierarchy.

• Class W extends Object and has one instance variable of type float.

• Class X extends W and has one instance variable of type StringBuffer.

• Class Y extends X and has one instance variable of type String.

• Class Z extends Y and has one instance variable of type Integer.

Page 77: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Inheritance and Variable con’t

• An object of class Z has the instance variables that are defined in all of the superclasses.

• The main() method instantiates class Z with the new operator, initializes the instance variables, and displays their values.

Page 78: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example: Inheritance and variables

• Class W{

float f;}class X extends W{

StringBuffer sb;}class Y extends X{

String s;}class Z extends Y{

Integer i;}

Page 79: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example: Inheritance and Variables

• Class Wxyz{

public static void main(String[] args){

Z z = new Z(); z.f = 4.567f; z.sb = new StringBuffer(“abcde”); z.s = “ Learning this Inheritance Stuff”;

z.i = new Integer(41); System.out.println(“z.f = “ + z.f);

System.out.println(“z.sb = “ + z.sb); System.out.println(“z.s = “ + z.s); System.out.println(“z.i = “ + z.i);}

}

Page 80: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

FinalThe following application illustrateshow the final keyword can be used in a class

modifier. This program does no compile because• the declaration of V2 attempts to extend V1,• which is declared as a final class

• Final cannot be extended.• classes are sometimes declared in this manner

so• the methods implemented by that class cannot

be• overridden.

Page 81: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

final con’t

• One of the common uses of final is to create named constants.

• For example, the following application illustrates this use of final.

• It creates a variable x whose value cannot be changed.

Page 82: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

final con’t

• One of the common uses of final is to create named constants.

• For example, the following application illustrates this use of final.

• It creates a variable x whose value cannot be changed.

Page 83: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example: Finalfinal class V1{}class V2 extends V1{}class FinalClass{

public static void main(String args[]){

V1 obj = new V1();}

}//Will not compile because cannot inherit from final V1//class V2 extends V1// cannot inherit from final V1//class V2 extends V1 because final cannot be

extended

Page 84: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example: final

class L{

static final int x = 5;}class FinalVariable{

public static void main(String[] args){

System.out.println(L.x);}

}

Page 85: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Constructor Modifiers

These are three modifiers that may precede the declaration of A constructor.These are summarized in the following table:Keyword Meaning

Private Can be invoked only by code in the same class

Protected Can be invoked only by code in a subclass

Or the same package

Public Can be invoked by any other class

Page 86: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

• The class JetPlane declares one abstract method named numEngines().

• Therefore, the class itself must also be declared abstract.

• There are two concrete subclasses named DC8 and DC10. Each of these provided a different implementation of numEngines() method.

• The main() method instantiates each of these classes and invoke its numEngines method.

• This is an excellent example of run-time polymorphism.

• Each subclass provides a different form of the method.

Page 87: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

abstract class JetPlane{

abstract int numEngines();}class DC8 extends JetPlane{

int numEngines(){

return 4;}

}

Page 88: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example cont

class DC10 extends JetPlane{

int numEngines(){

return 3;}

}

Page 89: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example cont

class JetPlanes{

public static void main(String[] args){

System.out.println(new DC8().numEngines());

System.out.println(new DC10().numEngines());

}}

Page 90: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Chapt 9 Applets

• How applets and Applications Are Different?

• Java applications are standalone Java programs that can be run by using just the Java interpreter.

• Java applets, however, are from inside a WWW browser.

Page 91: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating applets

• To create an applet, you create a subclass of the class Applet.

• The applet class, part of the java.applet package provides much of the behavior your applet needs to work inside a java-enabled browser.

Page 92: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating applets con’t

• Applets also take strong advantage of Java’s Abstract Windowing Toolkit and applications: drawing to the screen: creating windows, menu bars, buttons, check boxes, and other UI elements; and managing user input such as mouse clicks and keypresses.

• The AWT classes are part of the java.awt.package.

Page 93: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Major applet activities

• To create a basic Java application, your class has to have one method, main() method, with a specific signature.

• Then, when your application runs, main() is found and executed, and from main() you can set up the behavior that your program needs to run.

Page 94: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating applets con’t

• Applets are similar but more complicated - and in facts, applets don’t need a main() method at all.

• Applets have many different activities that correspond to various major events in the life cycle of the applet.

For example, initialization, painting, and mouse events.Each activities has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods.

Page 95: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

5 important Applets methods

Initialization- occurs when the applet is first loaded or reloaded, similar to the main() method.

public void init(){... }

Starting- start the applet (can happen many different times during an applet’s lifetime.

public void start(){... }

Page 96: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

5 important Applets methods

• Painting- is the way the applet actually draws something on the screen, be it text, a line, a colored background, or an image.– public void paint(Graphics g){…..}

Page 97: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

5 important applets methods

Stopping- goes hand in hand with starting. Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop().

public void stop(){….}

• Destroying- enables the applet to clean up after itself just before it is freed or the browser exits.– public void destroy(){…. }

Page 98: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The keyword “super”

• It is possible to access a hidden variable by using the super keyword, as follows:

super.VarNameHere, varName is the name of the variable in the superclass.This syntax may be use to read or write the hidden variable.


Recommended